Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): end the reconnect streak on a READY that already held
Yudhi Armyndharis02f706281ffd
diff --git a/docs/31-session-lifecycle-design.md b/docs/31-session-lifecycle-design.mdindex 86dfb8ba6..5c12dfac2 100644--- a/docs/31-session-lifecycle-design.md+++ b/docs/31-session-lifecycle-design.md@@ -109,9 +109,9 @@ before touching anything in the logout/forceKill path.**Defense:** `reconnect-policy.ts` — a pure decision function (attempt budget, loop alerts)consumed by the lifecycle, which resets the budget only when the session held READY for-`STABLE_READY_MS` (5 min) before its next drop, so a session that flaps keeps backing off and still-alerts; the clamps exist because a naive `delay * 2^attempt` reaches values `setTimeout` silently-truncates, and overflows to `Infinity` on a long enough streak.+`STABLE_READY_MS` (5 min) before its next drop or its next READY, so a session that flaps keeps+backing off and still alerts; the clamps exist because a naive `delay * 2^attempt` reaches values+`setTimeout` silently truncates, and overflows to `Infinity` on a long enough streak.**Pinned by:** `reconnect-policy.spec.ts`, `session.service.spec.ts` (scheduleReconnect cases).### INV-10 — Boot auto-start is sequential, staggered (2s per Chromium), and detached from bootstrapdiff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex a2ab3caef..27441bfd2 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -826,10 +826,15 @@ export class SessionEngineLifecycle {// Clear any stale failure reason on success. READY also ends the pending attempt: a reconnect// still armed (the watchdog reported this engine, then it recovered on its own) would tear the// recovered engine down. Only the timer goes; the state keeps the session's reconnect settings- // for its next drop. The attempt streak is not reset here: the next scheduleReconnect resets it+ // for its next drop. This READY does not reset the attempt streak: the next scheduleReconnect resets it// only if this READY held for STABLE_READY_MS, so a session that flaps keeps backing off.+ // Baileys fires READY again on every internal socket reopen, with no drop reported in between:+ // a previous READY that already held the window ends the streak here, before it is overwritten.const reconnectState = this.reconnectStates.get(id);if (reconnectState) {+ if (reconnectState.readyAt !== undefined && Date.now() - reconnectState.readyAt >= STABLE_READY_MS) {+ reconnectState.attempts = 0;+ }reconnectState.readyAt = Date.now();if (reconnectState.timer) {clearTimeout(reconnectState.timer);diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex e5338ef7b..43c8d0636 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1783,7 +1783,7 @@ describe('SessionService', () => {intern.reconnectStates.set('x', { attempts: 3, timer: null, readyAt: Date.now() });expect(lifecycle.isEngineActive('x')).toBe(false);- // An armed timer, attempts reset by a successful READY.+ // An armed timer on a fresh streak.intern.reconnectStates.set('x', { attempts: 0, timer: setTimeout(() => undefined, 60_000) });expect(lifecycle.isEngineActive('x')).toBe(true);clearTimeout((intern.reconnectStates.get('x') as { timer: NodeJS.Timeout }).timer);@@ -2179,6 +2179,63 @@ describe('SessionService', () => {}});+ it('ends the streak on a READY that held the stability window, even if another READY follows it', () => {+ // Baileys fires READY on every internal socket reopen with no gateway-level drop in between, so+ // a later READY must not restart the window and carry a long-finished streak forward.+ jest.useFakeTimers();+ try {+ const i = internals();+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ const state = { attempts: 0, timer: null, maxAttempts: 7, baseDelay: 5000 };+ i.reconnectStates.set('sess-uuid-1', state);+ jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);+ const engine = {+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),+ forceDestroy: jest.fn().mockResolvedValue(undefined),+ };+ i.engines.set('sess-uuid-1', engine);++ i.scheduleReconnect('sess-uuid-1', createMockSession());+ expect(state.attempts).toBe(1);+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');+ jest.advanceTimersByTime(STABLE_READY_MS);+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');+ jest.advanceTimersByTime(60_000);+ i.scheduleReconnect('sess-uuid-1', createMockSession());+ expect(state.attempts).toBe(1);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });++ it('keeps the streak when a second READY follows one that did not hold the stability window', () => {+ jest.useFakeTimers();+ try {+ const i = internals();+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ const state = { attempts: 0, timer: null, maxAttempts: 7, baseDelay: 5000 };+ i.reconnectStates.set('sess-uuid-1', state);+ jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);+ const engine = {+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),+ forceDestroy: jest.fn().mockResolvedValue(undefined),+ };+ i.engines.set('sess-uuid-1', engine);++ i.scheduleReconnect('sess-uuid-1', createMockSession());+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');+ jest.advanceTimersByTime(STABLE_READY_MS - 1);+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');+ jest.advanceTimersByTime(60_000);+ i.scheduleReconnect('sess-uuid-1', createMockSession());+ expect(state.attempts).toBe(2);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });+it('does not postpone an armed reconnect when the same episode reports another disconnect', () => {// The liveness watchdog re-probes a wedged engine that still reports READY and calls onDead// again ~120s later. With a 150s base delay, re-arming on every report would push the attempt