Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): close the proxy dispatcher on teardown (#1809)
Yudhi Armyndharis323b485fd04e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dce8f8629..78e87cc59 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Close the Baileys session proxy's fetch dispatcher when the session disconnects, logs out or is destroyed.- Apply the Java SDK request timeout to the response body as well as the headers.- Keep a new dashboard template draft when an earlier template save finishes.- Stop the dashboard Chats page from marking the open chat read on a newly selected session.diff --git a/src/engine/adapters/baileys-lifecycle.spec.ts b/src/engine/adapters/baileys-lifecycle.spec.tsindex 51799232d..df8f958b8 100644--- a/src/engine/adapters/baileys-lifecycle.spec.ts+++ b/src/engine/adapters/baileys-lifecycle.spec.ts@@ -170,3 +170,68 @@ describe('BaileysLifecycle QR refresh', () => {expect(onQRCode).not.toHaveBeenCalled();});});++describe('BaileysLifecycle proxy fetch dispatcher', () => {+ function lifecycle() {+ const noCallback = (): undefined => undefined;+ const host = {+ authPath: '/nonexistent/openwa-lifecycle-spec/session-sess-1',+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },+ config: {+ sessionId: 'sess-1',+ dbSessionId: 'db-1',+ proxyUrl: 'http://user:[email protected]:8080',+ messageStore: { clearSession: jest.fn().mockResolvedValue(undefined) },+ },+ liveCalls: new Map(),+ fenceStoredWrites: jest.fn(),+ getOnStateChanged: noCallback,+ getOnDisconnected: noCallback,+ getOnError: noCallback,+ getOnCredentialTeardownStarted: noCallback,+ } as unknown as BaileysLifecycleHost;+ const engine = new BaileysLifecycle(host);+ engine.sock = {+ user: { id: '628999:[email protected]' },+ query: jest.fn().mockResolvedValue({ tag: 'iq' }),+ generateMessageTag: () => 'tag-1',+ end: jest.fn(),+ } as unknown as BaileysLifecycle['sock'];+ return engine;+ }++ // The pooled proxy tunnels must not outlive the session: teardown closes the dispatcher (gracefully,+ // so a request already in progress still finishes) and forgets it, so a later fetch gets a fresh one.+ it.each([+ ['disconnect', (engine: BaileysLifecycle) => engine.disconnect()],+ ['destroy', (engine: BaileysLifecycle) => engine.destroy()],+ ['logout', (engine: BaileysLifecycle) => engine.logout()],+ [+ 'a failed logout',+ async (engine: BaileysLifecycle) => {+ jest.mocked(engine.sock!.query).mockRejectedValue(new Error('timed out'));+ await expect(engine.logout()).rejects.toThrow('timed out');+ },+ ],+ [+ 'a WhatsApp-side logout',+ (engine: BaileysLifecycle) =>+ (engine as unknown as { handleRemoteLoggedOut(): Promise<void> }).handleRemoteLoggedOut(),+ ],+ ])('closes the dispatcher on %s and builds a fresh one afterwards', async (_name, teardown) => {+ const engine = lifecycle();+ const dispatcher = engine.fetchDispatcher();+ if (!dispatcher) throw new Error('Expected a proxy dispatcher');+ const close = jest.spyOn(dispatcher, 'close');+ const destroy = jest.spyOn(dispatcher, 'destroy');++ await teardown(engine);++ expect(close).toHaveBeenCalledTimes(1);+ expect(destroy).not.toHaveBeenCalled();+ const fresh = engine.fetchDispatcher();+ expect(fresh).toBeDefined();+ expect(fresh).not.toBe(dispatcher);+ await fresh?.close();+ });+});diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex ce49e54c6..4c11622f1 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -207,7 +207,7 @@ export class BaileysLifecycle {private lastConnectionCloseAt = 0;/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */private lib?: typeof BaileysLib;- /** The session proxy's fetch dispatcher, built once: the proxy URL is fixed for the adapter's life. */+ /** The session proxy's fetch dispatcher, built on first use and closed at teardown. */private dispatcher?: Dispatcher;constructor(private readonly host: BaileysLifecycleHost) {@@ -232,6 +232,16 @@ export class BaileysLifecycle {return (this.dispatcher ??= createProxyDispatcher(proxyUrl));}+ /**+ * Drop the proxy's pooled tunnels at teardown instead of leaving them to idle out. close(), not+ * destroy(): a request already in progress finishes. A later fetch builds a fresh dispatcher.+ */+ private closeFetchDispatcher(): void {+ const dispatcher = this.dispatcher;+ this.dispatcher = undefined;+ void dispatcher?.close().catch(() => undefined);+ }+async initialize(): Promise<void> {// Single-use after teardown: disconnect()/destroy()/forceDestroy()/logout() set this latch, and// it must NOT be re-armed here. A retired adapter (e.g. one whose session was stopped/deleted@@ -855,6 +865,7 @@ export class BaileysLifecycle {this.cancelAddressbookRestore();void this.sock?.end(undefined);this.sock = null;+ this.closeFetchDispatcher();// Cached call handles die with the socket — drop them so a later rejectCall() reports// not-found instead of acting on a closed connection.this.host.liveCalls.clear();@@ -942,6 +953,7 @@ export class BaileysLifecycle {} catch {// end() may already have run from Baileys' own close handler — a safe no-op.}+ this.closeFetchDispatcher();// Cached call handles die with the connection — drop them so a later rejectCall() reports// not-found (404) instead of acting on a dead socket (mirrors disconnect/destroy).this.host.liveCalls.clear();@@ -974,6 +986,7 @@ export class BaileysLifecycle {// A message still being processed must not recreate a row of the unlinked account after the wipe below.this.host.fenceStoredWrites();void dead?.end(undefined);+ this.closeFetchDispatcher();const cleanup = (async (): Promise<void> => {try {@@ -1031,6 +1044,7 @@ export class BaileysLifecycle {this.cancelAddressbookRestore();void this.sock?.end(undefined);this.sock = null;+ this.closeFetchDispatcher();this.host.liveCalls.clear();this.setStatus(EngineStatus.DISCONNECTED);return Promise.resolve();