Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): answer 409 for a wwebjs send racing a teardown
Yudhi Armyndharisd0f743bed318
diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.tsindex e1e183ac4..593b730ba 100644--- a/src/engine/adapters/wwebjs-host.ts+++ b/src/engine/adapters/wwebjs-host.ts@@ -5,6 +5,7 @@ import {type IncomingMessage,} from '../interfaces/whatsapp-engine.interface';import { type createLogger } from '../../common/services/logger.service';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';import { toCapturedPageError } from './wwebjs-lifecycle';@@ -34,6 +35,18 @@ export interface WwebjsEngineHost {getCallbacks(): EngineEventCallbacks;}+/**+ * The client of a send path, read after ensureReady() and any awaits since (a recipient lookup, a media fetch).+ * A teardown can null the adapter's client in that gap, and the host closure then hands back a null typed as a+ * Client: the send would die as a TypeError 500 and count toward the send breaker. It answers the retryable 409+ * a not-ready session gets instead.+ */+export function requireClient(host: WwebjsEngineHost): Client {+ const client = host.getClient() as Client | null | undefined;+ if (!client) throw new EngineNotReadyError();+ return client;+}+/*** Run a client operation, classifying a dead page/transport as the documented 503 plus an early* death signal instead of an opaque 500 under a status that still says READY - the split everydiff --git a/src/engine/adapters/wwebjs-messaging-client-gone.spec.ts b/src/engine/adapters/wwebjs-messaging-client-gone.spec.tsnew file mode 100644index 000000000..cb8587789--- /dev/null+++ b/src/engine/adapters/wwebjs-messaging-client-gone.spec.ts@@ -0,0 +1,86 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsMessaging } from './wwebjs-messaging';+import { WwebjsStatus } from './wwebjs-status';+import { createLogger } from '../../common/services/logger.service';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { countsTowardSendBreaker, sentNothing } from '../../modules/message/send-pacing.service';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * A teardown (logout, destroy, reconnect) nulls the adapter's client while a send is parked on an+ * await between ensureReady() and the sendMessage call: the recipient lookup, or a media fetch. The+ * host closure then hands the delegate that null as if it were a Client, so the send died as a+ * TypeError 500 and counted toward the send breaker. It answers the retryable not-ready 409 instead.+ */+const logger = createLogger('wwebjs-messaging-client-gone.spec');++const CHAT = '[email protected]';+// Base64 rather than a URL: a URL payload runs the real remote-media loader through the SSRF guard.+const IMAGE = {+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ mimetype: 'image/png',+};++function makeMessaging(): { messaging: WwebjsMessaging; sendMessage: jest.Mock } {+ const sendMessage = jest.fn().mockResolvedValue({ id: { _serialized: 'M1' }, timestamp: 1 });+ let client: unknown = { sendMessage };+ const host = {+ ensureReady: jest.fn(),+ ensureNotChannelRecipient: jest.fn(),+ getClient: () => client as Client,+ logger,+ config: {},+ // The recipient lookup is the await the teardown lands in.+ getNumberId: jest.fn(() => {+ client = null;+ return Promise.resolve(CHAT);+ }),+ capInboundMediaFor: jest.fn(),+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ return { messaging: new WwebjsMessaging(host), sendMessage };+}++describe('WwebjsMessaging when the client is torn down mid-send', () => {+ it.each([+ ['text', (m: WwebjsMessaging) => m.sendTextMessage(CHAT, 'hi')],+ ['image', (m: WwebjsMessaging) => m.sendImageMessage(CHAT, IMAGE)],+ ['location', (m: WwebjsMessaging) => m.sendLocationMessage(CHAT, { latitude: 1, longitude: 2 })],+ ])('answers the not-ready 409 for a %s send, which the send breaker ignores', async (_kind, send) => {+ const { messaging, sendMessage } = makeMessaging();++ const error: unknown = await send(messaging).catch((e: unknown) => e);++ expect(error).toBeInstanceOf(EngineNotReadyError);+ expect(sendMessage).not.toHaveBeenCalled();+ expect(countsTowardSendBreaker(error)).toBe(false);+ expect(sentNothing(error)).toBe(true);+ });+});++describe('WwebjsStatus when the client is torn down mid-post', () => {+ // A media status awaits its media before it reaches the client, so it has the same gap as a media send, and+ // a TypeError there reaches the status breaker as an account failure.+ it('answers the not-ready 409 for a media status, which the send breaker ignores', async () => {+ const sendMessage = jest.fn();+ let client: unknown = { sendMessage };+ const host = {+ // Readiness passes, then the teardown lands before the post reaches the client.+ ensureReady: jest.fn(() => {+ client = null;+ }),+ getClient: () => client as Client,+ logger,+ config: {},+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;++ const error: unknown = await new WwebjsStatus(host).postImageStatus(IMAGE, {}).catch((e: unknown) => e);++ expect(error).toBeInstanceOf(EngineNotReadyError);+ expect(sendMessage).not.toHaveBeenCalled();+ expect(countsTowardSendBreaker(error)).toBe(false);+ });+});diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex da9f5351a..4eaa2c9c9 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -29,7 +29,7 @@ import { buildIncomingMessageBase, mapContactFields } from './message-mapper';import { buildVCard } from './vcard';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';-import { type WwebjsEngineHost, withPage } from './wwebjs-host';+import { type WwebjsEngineHost, requireClient, withPage } from './wwebjs-host';import { toCapturedPageError } from './wwebjs-lifecycle';/**@@ -364,9 +364,9 @@ function ensureSendable(chatId: string, shape: 'reply' | 'location' | 'contact cexport class WwebjsMessaging {constructor(private readonly host: WwebjsEngineHost) {}- /** Post-ensureReady client handle. */+ /** Post-ensureReady client handle; see {@link requireClient} for a teardown that lands in between. */private client(): Client {- return this.host.getClient();+ return requireClient(this.host);}/** See {@link withPage} for what a dead page answers here. */diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.tsindex 0501f2b05..229ac6824 100644--- a/src/engine/adapters/wwebjs-status.ts+++ b/src/engine/adapters/wwebjs-status.ts@@ -10,7 +10,7 @@ import {import { SerializedWid, readWid } from '../types/whatsapp-web-js.types';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { toMessageMedia } from './wwebjs-messaging';-import { type WwebjsEngineHost, withPage, reportPageDeath } from './wwebjs-host';+import { type WwebjsEngineHost, requireClient, withPage, reportPageDeath } from './wwebjs-host';/*** The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a@@ -54,9 +54,9 @@ export function toStatusResult(msg: Message | undefined): StatusResult {export class WwebjsStatus {constructor(private readonly host: WwebjsEngineHost) {}- /** Post-ensureReady client handle. */+ /** Post-ensureReady client handle; see {@link requireClient} for a teardown that lands in between. */private client(): Client {- return this.host.getClient();+ return requireClient(this.host);}/** See {@link withPage} for what a dead page answers here. */