Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): name the cause of a 502 forward failure

Yudhi Armyndharis598d3b9b84d7
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 44f1efc84..a6d1ca068 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -62,10 +62,12 @@
>
> **A failed forward says whether the owner could have acted.** When the owner cannot be
> reached at all (connection refused, unresolvable or unusable `NODE_URL`), the answer is
-> `503` and the request was not carried out, so it is safe to retry. Once the request has
-> been sent, a failure answers `504` (no reply within `SESSION_PROXY_TIMEOUT_MS`) or `502`
-> (the connection broke mid-request): the owner may already have carried it out, so a
-> non-idempotent call such as a message send must not be repeated blindly on either.
+> `503` and the request was not carried out, so it is safe to retry. A timeout answers `504`
+> (no reply within `SESSION_PROXY_TIMEOUT_MS`), and any other failure answers `502` (the
+> connection broke, possibly after the request was sent; a TLS certificate the forwarding
+> node does not trust also lands here, with the cause code in its warning log): the owner
+> may already have carried it out, so a non-idempotent call such as a message send must not
+> be repeated blindly on either.
>
> **The lease compares timestamps written by different nodes, so their clocks must agree.** Each
> node writes `leaseExpiresAt` from its own clock and reads every other node's the same way, so a
diff --git a/src/modules/session/session-proxy.interceptor.spec.ts b/src/modules/session/session-proxy.interceptor.spec.ts
index ea56e7d1f..96733b6bf 100644
--- a/src/modules/session/session-proxy.interceptor.spec.ts
+++ b/src/modules/session/session-proxy.interceptor.spec.ts
@@ -365,10 +365,19 @@ describe('SessionProxyInterceptor', () => {
req => req.socket.destroy(),
async url => {
const { interceptor, context, next, res } = build({ row: row({ nodeUrl: url }), req: sendRequest() });
+ const warn = jest.spyOn((interceptor as unknown as { logger: { warn: () => void } }).logger, 'warn');
await interceptor.intercept(context, next);
expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(502);
+ // A 502 can also come from a failure before anything was sent (an untrusted TLS
+ // certificate), so the answer must not claim a send and must point at NODE_URL.
+ const { message } = (res.json.mock.calls[0] as [{ message: string }])[0];
+ expect(message).toContain('possibly after the request was sent');
+ expect(message).toContain('NODE_URL');
+ // fetch only says 'fetch failed'; the cause code is what names the real failure.
+ const [, logged] = warn.mock.calls[0] as unknown as [string, { cause: unknown }];
+ expect(logged.cause).toMatch(/^[A-Z_]+$/);
},
);
});
diff --git a/src/modules/session/session-proxy.interceptor.ts b/src/modules/session/session-proxy.interceptor.ts
index 950d98e75..582d83fe1 100644
--- a/src/modules/session/session-proxy.interceptor.ts
+++ b/src/modules/session/session-proxy.interceptor.ts
@@ -239,14 +239,17 @@ export class SessionProxyInterceptor implements NestInterceptor {
if (body.length > 0) response.send(body);
else response.end();
} catch (error) {
- this.logger.warn(`Forwarding to session owner '${ownerNodeId}' failed`, {
- ownerNodeUrl,
- error: error instanceof Error ? error.message : String(error),
- });
// Duck-typed rather than `instanceof`: fetch rejects with a DOMException on timeout, and its
// errors are not guaranteed to share this context's Error class.
const failure = (error ?? {}) as { name?: unknown; cause?: { code?: unknown } };
const code = failure.cause?.code;
+ // fetch reports every network failure as 'fetch failed'; the cause code (a TLS certificate
+ // error, a DNS failure) is what tells the operator what went wrong.
+ this.logger.warn(`Forwarding to session owner '${ownerNodeId}' failed`, {
+ ownerNodeUrl,
+ error: error instanceof Error ? error.message : String(error),
+ cause: code,
+ });
if (target === undefined || (typeof code === 'string' && NOT_DISPATCHED_CODES.has(code))) {
// Nothing reached the owner: 503 is the honest, retryable answer.
response.status(503).json({
@@ -258,9 +261,10 @@ export class SessionProxyInterceptor implements NestInterceptor {
});
return;
}
- // Anything else may have happened after the request was sent, so the owner may have acted on
- // it (a message may be out). Never 503 here: clients treat 503 as declined-before-acting and
- // replay non-idempotent sends on it.
+ // Anything else may have happened after the request was sent (an unlisted error such as a TLS
+ // handshake failure happens before it, but cannot be told apart), so the owner may have acted
+ // on it. Never 503 here: clients treat 503 as declined-before-acting and replay non-idempotent
+ // sends on it.
const timedOut = failure.name === 'TimeoutError' || failure.name === 'AbortError';
const status = timedOut ? 504 : 502;
response.status(status).json({
@@ -268,8 +272,8 @@ export class SessionProxyInterceptor implements NestInterceptor {
message: timedOut
? `node '${ownerNodeId}', which hosts this session, did not answer within ${timeoutMs}ms; ` +
'the request may still have been carried out there'
- : `forwarding to node '${ownerNodeId}', which hosts this session, failed after the request was sent; ` +
- 'it may have been carried out there',
+ : `forwarding to node '${ownerNodeId}', which hosts this session, failed, possibly after the request ` +
+ 'was sent; it may have been carried out there, check the owner node and its NODE_URL',
error: timedOut ? 'Gateway Timeout' : 'Bad Gateway',
});
}