Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep backing off when a link drops right after opening
Yudhi Armyndharis833a3d035c4c
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex f89233e05..bc80d2b69 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -177,8 +177,9 @@ export interface BaileysLifecycleHost {}export class BaileysLifecycle {- /** A close this long after the previous close means the connection had been healthy in between —- * the backoff counter restarts from scratch instead of inheriting an old incident's attempts. */+ /** A connection that stayed open this long, or a close this long after the previous close, means the+ * connection had been healthy: the backoff counter restarts from scratch instead of inheriting an+ * old incident's attempts. */private static readonly RECONNECT_STABILITY_RESET_MS = 5 * 60_000;/** How long a first link's history sync must stay silent before the address-book pull runs. */private static readonly ADDRESSBOOK_QUIET_MS = 20_000;@@ -201,6 +202,8 @@ export class BaileysLifecycle {private addressbookTimer?: ReturnType<typeof setTimeout>;/** Date.now() of the last close that scheduled a reconnect — input to the stability reset. */private lastConnectionCloseAt = 0;+ /** Date.now() of the last 'open' not yet followed by a close, or 0: how long the connection stayed up. */+ private lastOpenAt = 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. */@@ -609,8 +612,10 @@ export class BaileysLifecycle {if (me?.id && me.lid) {this.host.addLidMappings([{ lid: `${userPart(me.lid)}@lid`, pn: `${userPart(me.id)}@s.whatsapp.net` }]);}- // I4: reset the reconnect counter on a successful connection.- this.reconnectAttempts = 0;+ // The reconnect counter is not reset here: a connection that drops seconds after the handshake+ // would otherwise redial at attempt 1 forever. The close branch resets it once the connection+ // has stayed up for the stability window.+ this.lastOpenAt = Date.now();this.setStatus(EngineStatus.READY);this.host.getOnReady()?.(this.phoneNumber ?? '', this.pushName ?? '');// WhatsApp only PUSHES a timelock when it changes, so a gateway that starts (or reconnects)@@ -668,8 +673,8 @@ export class BaileysLifecycle {// Every other close (408/411/428/500/503/515/undefined) is transient: reconnect with capped// backoff and NO attempt ceiling — a long network outage must- // not kill the session. The counter resets on 'open', on a scan, when a QR window runs out, and via- // the stability window below.+ // not kill the session. The counter resets on a scan, when a QR window runs out, and via the+ // stability window below.// Do NOT fire onDisconnected here; this is a transient drop, not a terminal disconnect.this.host.logger.log('Baileys connection dropped; reconnecting', {sessionId: this.host.config.sessionId,@@ -698,14 +703,22 @@ export class BaileysLifecycle {return;}- // Stability reset: a close >5 min after the previous one means the connection had been- // healthy in between — start the backoff fresh instead of inheriting the old counter.+ // Stability reset: a connection that stayed open for the stability window, or a close that long+ // after the previous one, means the connection had been healthy, so the backoff starts fresh+ // instead of inheriting the old counter. One that drops sooner keeps climbing it, so a link+ // that fails right after each handshake backs off instead of redialing every second or two.// A QR window that ran out resets it too: WhatsApp answered, and a QR left unscanned for hours// must not add up to a reconnect loop.const now = Date.now();- if (qrWindowEnded || now - this.lastConnectionCloseAt > BaileysLifecycle.RECONNECT_STABILITY_RESET_MS) {+ const stayedOpen = this.lastOpenAt > 0 && now - this.lastOpenAt >= BaileysLifecycle.RECONNECT_STABILITY_RESET_MS;+ if (+ qrWindowEnded ||+ stayedOpen ||+ now - this.lastConnectionCloseAt > BaileysLifecycle.RECONNECT_STABILITY_RESET_MS+ ) {this.reconnectAttempts = 0;}+ this.lastOpenAt = 0;this.lastConnectionCloseAt = now;this.scheduleReconnect(!qrWindowEnded);}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 3d84722a4..c14ac617c 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -1037,25 +1037,45 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',expect(onError).not.toHaveBeenCalled();});- it('successful connection resets the reconnect counter (next drop uses the attempt-1 delay)', async () => {- const adapter = await initWithRealTimers({});+ it('a connection that drops right after opening keeps climbing the backoff (1 s, 2 s, 4 s)', async () => {+ const onReconnecting = jest.fn();+ const adapter = await initWithRealTimers({ onReconnecting });baileys().default.mockClear();jest.useFakeTimers();jest.spyOn(Math, 'random').mockReturnValue(0);- // Drop + reconnect — the counter is now 1 (no 'open' yet).+ // Each cycle opens, then drops at once: the open alone must not restart the counter.+ for (const delay of [1_000, 2_000, 4_000]) {+ fireRecoverableClose();+ await jest.advanceTimersByTimeAsync(delay);+ fakeSock.fire('connection.update', { connection: 'open' });+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ }+ expect(onReconnecting.mock.calls).toEqual([+ [1, 1_000],+ [2, 2_000],+ [3, 4_000],+ ]);+ expect(baileys().default).toHaveBeenCalledTimes(3);+ });++ it('a connection that stayed open past the stability window restarts the backoff at attempt 1', async () => {+ const onReconnecting = jest.fn();+ await initWithRealTimers({ onReconnecting });+ jest.useFakeTimers();+ jest.spyOn(Math, 'random').mockReturnValue(0);+fireRecoverableClose();await jest.advanceTimersByTimeAsync(1_000);- expect(baileys().default).toHaveBeenCalledTimes(1);-- // Simulate a successful open — should reset the reconnect counter to 0.fakeSock.fire('connection.update', { connection: 'open' });- expect(adapter.getStatus()).toBe(EngineStatus.READY);+ fireRecoverableClose();+ await jest.advanceTimersByTimeAsync(2_000);+ fakeSock.fire('connection.update', { connection: 'open' });- // The next drop must schedule attempt 1 (1 s), not attempt 2 (2 s): 1.5 s settles it.+ // Up for the whole window, then dropped: a fresh incident, so attempt 1 (1 s), not attempt 3.+ jest.setSystemTime(Date.now() + 5 * 60_000);fireRecoverableClose();- await jest.advanceTimersByTimeAsync(1_500);- expect(baileys().default).toHaveBeenCalledTimes(2);+ expect(onReconnecting).toHaveBeenLastCalledWith(1, 1_000);});it('stability reset: a close >5 min after the previous close restarts the backoff at attempt 1', async () => {