Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): answer a protocol timeout on chat and contact ops with 503

Yudhi Armyndharis93229682451a
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 5d1f93fc3..c8d798daf 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2436,7 +2436,7 @@ Get a single contact by its WhatsApp id.
}
```
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Contact <id> not found` (engine returned null) · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-read, so the lookup reached no answer (distinct from the `404`, which asserts the contact does not exist)
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Contact <id> not found` (engine returned null) · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-read or the command timed out, so the lookup reached no answer (distinct from the `404`, which asserts the contact does not exist)
#### GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
@@ -3995,7 +3995,7 @@ Every chat carrying a label.
**Response** `200` — a bare array of `ChatSummary`, the same shape `GET /sessions/:sessionId/chats` returns.
-**Errors:** `400` session not started (also when the session does not exist) · `401` · `404` label or chat not found · `501` Baileys, which has no label query · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)
+**Errors:** `400` session not started (also when the session does not exist) · `401` · `404` label or chat not found · `501` Baileys, which has no label query · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died or the command timed out, so nothing was read (retryable; says nothing about whether the label exists)
#### PUT /api/sessions/:sessionId/labels/:labelId
diff --git a/openapi.json b/openapi.json
index d332fad10..9de99af4a 100644
--- a/openapi.json
+++ b/openapi.json
@@ -4691,7 +4691,7 @@
"description": "The session is not connected: an engine exists for it but is not `ready`, meaning disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it, and for those few seconds the answer is a `409` naming the reload; retry shortly."
},
"503": {
- "description": "The whatsapp-web.js page connection died mid-read, so the lookup could not reach an answer. Distinct from the `404` above, which asserts the contact does not exist: this one asserts nothing about the contact. Retry once the session is ready again."
+ "description": "The whatsapp-web.js page connection died mid-read, or WhatsApp Web did not answer within the protocol timeout, so the lookup could not reach an answer. Distinct from the `404` above, which asserts the contact does not exist: this one asserts nothing about the contact. Retry once the session is ready again."
}
},
"summary": "Get a specific contact by ID",
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index 0be5b1091..ceadc4479 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -5,6 +5,7 @@ import { EngineTransportError } from '../../common/errors/engine-transport.error
import { chatKind, isChannelJid } from '../identity/wa-id';
import { WwebjsMessaging } from './wwebjs-messaging';
import { type WwebjsEngineHost } from './wwebjs-host';
+import { isProtocolTimeout } from './wwebjs-lifecycle';
/**
* Chat-list operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public methods as
@@ -93,6 +94,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'sendSeen');
throw new EngineTransportError('Transport died while marking a chat as read');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while marking a chat as read');
+ }
this.host.logger.error(`Error marking chat ${chatId} as read`, String(error));
return false;
}
@@ -114,6 +118,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'clearChatMessages');
throw new EngineTransportError('Transport died while clearing a chat');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while clearing a chat');
+ }
this.host.logger.error(`Error clearing messages in chat ${chatId}`, String(error));
return false;
}
@@ -146,6 +153,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'archiveChat');
throw new EngineTransportError('Transport died while archiving a chat');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while archiving a chat');
+ }
this.host.logger.error(`Error ${archive ? 'archiving' : 'unarchiving'} chat ${chatId}`, String(error));
return false;
}
@@ -176,6 +186,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'requireResolvableChat');
throw new EngineTransportError('Transport died while resolving a chat');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while resolving a chat');
+ }
chat = undefined; // an unknown chat rejects too — that is the 400 below
}
if (!chat) throw new BadRequestException(`Chat ${chatId} does not exist on this session`);
@@ -233,6 +246,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'markUnread');
throw new EngineTransportError('Transport died while marking a chat as unread');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while marking a chat as unread');
+ }
this.host.logger.error(`Error marking chat ${chatId} as unread`, String(error));
return false;
}
@@ -256,6 +272,9 @@ export class WwebjsChats {
this.host.reportIfPageTransportError(error, 'deleteChat');
throw new EngineTransportError('Transport died while deleting a chat');
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer in time while deleting a chat');
+ }
this.host.logger.error(`Error deleting chat ${chatId}`, String(error));
return false;
}
diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.ts
index abb81fa81..85ae40614 100644
--- a/src/engine/adapters/wwebjs-contacts.ts
+++ b/src/engine/adapters/wwebjs-contacts.ts
@@ -4,6 +4,7 @@ import { EngineTransportError } from '../../common/errors/engine-transport.error
import { userPart } from '../identity/wa-id';
import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';
import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { isProtocolTimeout } from './wwebjs-lifecycle';
/** The raw whatsapp-web.js contact element type, kept local so the wwebjs `Contact` type never leaks. */
type RawWwebjsContact = Awaited<ReturnType<Client['getContacts']>>[number];
@@ -153,6 +154,10 @@ export class WwebjsContacts {
this.host.reportIfPageTransportError(error, 'getContactById');
throw new EngineTransportError(`Transport died while reading contact ${contactId}`);
}
+ // A command that outran the protocol budget got no answer either way: a 503, but no death.
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError(`WhatsApp Web did not answer the read of contact ${contactId} in time`);
+ }
this.host.logger.warn(`Failed to get contact: ${contactId}`, { error: String(error) });
return null;
}
diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
index a65eec51a..52e9af859 100644
--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
@@ -1,3 +1,4 @@
+import { BadRequestException } from '@nestjs/common';
import { Callback } from 'puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js';
import { Client } from 'whatsapp-web.js';
import configuration, { MAX_TIMER_MS } from '../../config/configuration';
@@ -6,6 +7,9 @@ import { WhatsAppWebJsAdapter } from './whatsapp-web-js.adapter';
import { WwebjsLifecycle } from './wwebjs-lifecycle';
import { WwebjsGroups } from './wwebjs-groups';
import { WwebjsLabels } from './wwebjs-labels';
+import { WwebjsChats } from './wwebjs-chats';
+import { WwebjsContacts } from './wwebjs-contacts';
+import { type WwebjsMessaging } from './wwebjs-messaging';
import { type WwebjsEngineHost } from './wwebjs-host';
import { createLogger } from '../../common/services/logger.service';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
@@ -170,9 +174,10 @@ describe('whatsapp-web.js protocol timeout', () => {
/**
* A timed-out command got no answer at all, so the verdict branches that read a rejection as "no such
- * group" (404), "no such invite" (404), "invalid invite" (400) or "no such label" (404) must not see
- * it. It is the 503 those routes document for a query that never came back, and it is not a death:
- * the session must not be torn down for a slow renderer.
+ * group" (404), "no such invite" (404), "invalid invite" (400), "no such label" (404), "no such
+ * contact" (404), "no such chat" (400) or "declined" (200 `success: false`) must not see it. It is
+ * the 503 those routes document for a query that never came back, and it is not a death: the session
+ * must not be torn down for a slow renderer.
*/
describe('a protocol timeout is a 503, never a not-found verdict', () => {
const makeHost = (
@@ -189,11 +194,21 @@ describe('a protocol timeout is a 503, never a not-found verdict', () => {
return { host, reportIfPageTransportError };
};
+ const CHAT = '[email protected]';
+ const chats = (host: WwebjsEngineHost): WwebjsChats => new WwebjsChats(host, {} as WwebjsMessaging);
+
const OPS: Record<string, [string, (host: WwebjsEngineHost) => Promise<unknown>]> = {
getGroupInfo: ['getChatById', host => new WwebjsGroups(host).getGroupInfo('[email protected]')],
getGroupJoinInfo: ['getInviteInfo', host => new WwebjsGroups(host).getGroupJoinInfo('AbCdEf')],
joinGroupViaInviteCode: ['acceptInvite', host => new WwebjsGroups(host).joinGroupViaInviteCode('AbCdEf')],
getChatsByLabel: ['getChatsByLabelId', host => new WwebjsLabels(host).getChatsByLabel('7')],
+ getContactById: ['getContactById', host => new WwebjsContacts(host).getContactById('[email protected]')],
+ sendSeen: ['getChatById', host => chats(host).sendSeen(CHAT)],
+ clearChatMessages: ['getChatById', host => chats(host).clearChatMessages(CHAT)],
+ archiveChat: ['archiveChat', host => chats(host).archiveChat(CHAT, true)],
+ muteChat: ['getChatById', host => chats(host).muteChat(CHAT, null)],
+ markUnread: ['getChatById', host => chats(host).markUnread(CHAT)],
+ deleteChat: ['getChatById', host => chats(host).deleteChat(CHAT)],
};
it.each(Object.keys(OPS))('%s answers an expired protocolTimeout with a 503 and reports no death', async op => {
@@ -207,18 +222,25 @@ describe('a protocol timeout is a 503, never a not-found verdict', () => {
// Negative twin: an ordinary page-side refusal keeps its not-found verdict.
it.each([
- ['getGroupInfo', undefined],
+ ['getGroupInfo', null],
['getGroupJoinInfo', GroupNotFoundError],
['joinGroupViaInviteCode', InvalidInviteCodeError],
['getChatsByLabel', LabelNotFoundError],
+ ['getContactById', null],
+ ['sendSeen', false],
+ ['clearChatMessages', false],
+ ['archiveChat', false],
+ ['muteChat', BadRequestException],
+ ['markUnread', false],
+ ['deleteChat', false],
])('%s keeps its verdict for an ordinary refusal', async (op, verdict) => {
const [method, call] = OPS[op];
const { host } = makeHost({ [method]: jest.fn().mockRejectedValue(new Error('Evaluation failed: not found')) });
- if (verdict) {
+ if (typeof verdict === 'function') {
await expect(call(host)).rejects.toBeInstanceOf(verdict);
} else {
- await expect(call(host)).resolves.toBeNull();
+ await expect(call(host)).resolves.toBe(verdict ?? null);
}
});
});
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index ff578f9a0..aca77371c 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -96,9 +96,10 @@ export class ContactController {
@ApiResponse({
status: 503,
description:
- 'The whatsapp-web.js page connection died mid-read, so the lookup could not reach an answer. ' +
- 'Distinct from the `404` above, which asserts the contact does not exist: this one asserts ' +
- 'nothing about the contact. Retry once the session is ready again.',
+ 'The whatsapp-web.js page connection died mid-read, or WhatsApp Web did not answer within the ' +
+ 'protocol timeout, so the lookup could not reach an answer. Distinct from the `404` above, which ' +
+ 'asserts the contact does not exist: this one asserts nothing about the contact. Retry once the ' +
+ 'session is ready again.',
})
async findOne(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
return this.contactService.getContactById(sessionId, contactId);