Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): answer 409 when a wwebjs reply or forward read dies

Yudhi Armyndharis7b6f89196109
diff --git a/src/engine/adapters/wwebjs-client-teardown.spec.ts b/src/engine/adapters/wwebjs-client-teardown.spec.ts
index b2b70da9f..9f5e5001f 100644
--- a/src/engine/adapters/wwebjs-client-teardown.spec.ts
+++ b/src/engine/adapters/wwebjs-client-teardown.spec.ts
@@ -84,6 +84,8 @@ const outcomeOf = (operation: Promise<unknown>): Promise<Outcome> =>
const found = (wid: string): { _serialized: string } => ({ _serialized: wid });
+const closedTarget = (): Error => new Error('Protocol error (Runtime.callFunctionOn): Target closed.');
+
interface Case {
name: string;
/** The client the operation runs against, with its first await parked on `parked`; `unreached` must stay uncalled. */
@@ -198,6 +200,31 @@ const CASES: Case[] = [
},
run: adapter => adapter.replyToMessage(CHAT, 'Q1', 'hi'),
},
+ {
+ // The history read precedes the send: a page that dies under it means nothing went out.
+ name: 'a reply parked in its history read',
+ build: parked => {
+ const reply = jest.fn();
+ const chat = { fetchMessages: () => parked.park().then(() => Promise.reject(closedTarget())) };
+ return {
+ client: { getNumberId: () => Promise.resolve(found(CHAT)), getChatById: () => Promise.resolve(chat) },
+ unreached: reply,
+ };
+ },
+ run: adapter => adapter.replyToMessage(CHAT, 'Q1', 'hi'),
+ },
+ {
+ name: 'a forward parked in the read of its source chat',
+ build: parked => {
+ const forward = jest.fn();
+ const source = { fetchMessages: () => parked.park().then(() => Promise.reject(closedTarget())) };
+ return {
+ client: { getNumberId: () => Promise.resolve(found(CHAT)), getChatById: () => Promise.resolve(source) },
+ unreached: forward,
+ };
+ },
+ run: adapter => adapter.forwardMessage('[email protected]', CHAT, 'M1'),
+ },
{
name: 'a forward parked in the destination lookup',
build: parked => {
@@ -304,6 +331,21 @@ describe('whatsapp-web.js operations that race a session teardown', () => {
});
});
+ it.each([
+ ['a reply', (adapter: WhatsAppWebJsAdapter) => adapter.replyToMessage(CHAT, 'Q1', 'hi')],
+ ['a forward', (adapter: WhatsAppWebJsAdapter) => adapter.forwardMessage('[email protected]', CHAT, 'M1')],
+ ])('leaves an ordinary failure in the history read of %s untouched on a ready session', async (_kind, run) => {
+ const boom = new Error('Evaluation failed: boom');
+ const chat = { fetchMessages: () => Promise.reject(boom) };
+ const { adapter, finish } = readyAdapter({
+ getNumberId: () => Promise.resolve(found(CHAT)),
+ getChatById: () => Promise.resolve(chat),
+ });
+
+ await expect(run(adapter)).rejects.toBe(boom);
+ await finish();
+ });
+
it('keeps a send that was already on the wire an outcome-unknown failure', async () => {
const onWire = gate();
const sendMessage = jest.fn(() =>
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 22e9b0f25..0d9631980 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -374,6 +374,22 @@ export class WwebjsMessaging {
return withPage(this.host, context, op);
}
+ /**
+ * A read that runs before a reply or forward has sent anything. When the page died under it, or the
+ * session went away meanwhile, nothing was sent: report the death, then answer the not-ready 409 a
+ * send gets everywhere else, not the plain page error the send breaker counts. Any other failure
+ * rethrows unchanged. Not for the send itself, whose failure leaves the outcome unknown.
+ */
+ private async readBeforeSend<T>(context: string, read: () => Promise<T>): Promise<T> {
+ try {
+ return await read();
+ } catch (error) {
+ this.host.reportIfPageTransportError(error, context);
+ this.host.ensureReady();
+ throw error;
+ }
+ }
+
// Cache of resolved individual recipients: `<phone>@c.us` -> the id `sendMessage` accepts (a
// `<lid>@lid` for a migrated contact, or the confirmed `@c.us` for a non-migrated one). `getNumberId`
// is a rate-limited WhatsApp Web existence probe that also throws intermittently, so caching every
@@ -719,11 +735,11 @@ export class WwebjsMessaging {
ensureSendable(chatId, 'reply');
try {
// Find the message to quote
- const chat = await this.client().getChatById(chatId);
+ const chat = await this.readBeforeSend('replyToMessage', () => this.client().getChatById(chatId));
if (!chat) {
throw new MessageNotFoundError(quotedMsgId, chatId);
}
- const messages = await chat.fetchMessages({ limit: 100 });
+ const messages = await this.readBeforeSend('replyToMessage', () => chat.fetchMessages({ limit: 100 }));
const quotedMsg = messages.find(m => m.id._serialized === quotedMsgId);
if (!quotedMsg) {
@@ -750,11 +766,11 @@ export class WwebjsMessaging {
async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {
this.host.ensureReady();
try {
- const chat = await this.client().getChatById(fromChatId);
+ const chat = await this.readBeforeSend('forwardMessage', () => this.client().getChatById(fromChatId));
if (!chat) {
throw new MessageNotFoundError(messageId, fromChatId);
}
- const messages = await chat.fetchMessages({ limit: 100 });
+ const messages = await this.readBeforeSend('forwardMessage', () => chat.fetchMessages({ limit: 100 }));
const msgToForward = messages.find(m => m.id._serialized === messageId);
if (!msgToForward) {