Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(session): extract the reconnect backoff decision as a pure policy

Yudhi Armyndharis6f1c3efe0554
diff --git a/src/modules/session/reconnect-policy.spec.ts b/src/modules/session/reconnect-policy.spec.ts
new file mode 100644
index 000000000..62cd771ed
--- /dev/null
+++ b/src/modules/session/reconnect-policy.spec.ts
@@ -0,0 +1,203 @@
+import {
+ decideReconnect,
+ clampReconnectDelay,
+ RECONNECT_STABILITY_RESET_MS,
+ RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS,
+ RECONNECT_DELAY_CAP_MS,
+ type ReconnectAttemptState,
+} from './reconnect-policy';
+
+const state = (over: Partial<ReconnectAttemptState> = {}): ReconnectAttemptState => ({
+ attempts: 0,
+ maxAttempts: Number.POSITIVE_INFINITY,
+ baseDelay: 5000,
+ ...over,
+});
+
+// Jitter is injected so the delay assertions are exact rather than ranged.
+const NO_JITTER = 0;
+
+describe('decideReconnect', () => {
+ describe('exponential backoff', () => {
+ it('schedules the first attempt at baseDelay', () => {
+ const s = state();
+
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+
+ expect(d).toMatchObject({ kind: 'schedule', delayMs: 5000, attempt: 1 });
+ });
+
+ it('doubles the delay per consecutive attempt', () => {
+ const s = state();
+ const delays: number[] = [];
+
+ for (let i = 0; i < 4; i++) {
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+ if (d.kind === 'schedule') delays.push(d.delayMs);
+ }
+
+ expect(delays).toEqual([5000, 10000, 20000, 40000]);
+ });
+
+ it('adds the supplied jitter before clamping', () => {
+ const s = state();
+
+ const d = decideReconnect(s, 1_000, 777);
+
+ expect(d).toMatchObject({ delayMs: 5777 });
+ });
+
+ it('parks at the cap once the exponent outgrows it (unlimited budget never overflows setTimeout)', () => {
+ const s = state({ attempts: 40 });
+
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+
+ expect(d).toMatchObject({ delayMs: RECONNECT_DELAY_CAP_MS });
+ });
+
+ it('advances the caller-owned attempt counter', () => {
+ const s = state();
+
+ decideReconnect(s, 1_000, NO_JITTER);
+ decideReconnect(s, 1_000, NO_JITTER);
+
+ expect(s.attempts).toBe(2);
+ });
+
+ it('records when the attempt was scheduled', () => {
+ const s = state();
+
+ decideReconnect(s, 12_345, NO_JITTER);
+
+ expect(s.lastAttemptAt).toBe(12_345);
+ });
+ });
+
+ describe('budget exhaustion', () => {
+ it('reports exhausted once attempts reach the cap', () => {
+ const s = state({ attempts: 3, maxAttempts: 3 });
+
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+
+ expect(d).toEqual({
+ kind: 'exhausted',
+ reason: 'Reconnection failed after 3 attempts — restart the session.',
+ });
+ });
+
+ it('distinguishes "auto-reconnect disabled" from "N attempts failed"', () => {
+ const s = state({ attempts: 0, maxAttempts: 0 });
+
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+
+ // maxAttempts:0 means disabled outright; "failed after 0 attempts" would be misleading.
+ expect(d).toEqual({
+ kind: 'exhausted',
+ reason:
+ 'Auto-reconnect is disabled (max attempts set to 0); the session was left disconnected — restart it manually.',
+ });
+ });
+
+ it('does not advance the counter once exhausted', () => {
+ const s = state({ attempts: 3, maxAttempts: 3 });
+
+ decideReconnect(s, 1_000, NO_JITTER);
+
+ expect(s.attempts).toBe(3);
+ });
+
+ it('never exhausts on the default unlimited budget', () => {
+ const s = state({ attempts: 10_000 });
+
+ expect(decideReconnect(s, 1_000, NO_JITTER).kind).toBe('schedule');
+ });
+ });
+
+ describe('stability reset', () => {
+ it('resets the budget when the session stayed up past the stability window', () => {
+ const s = state({ attempts: 4, maxAttempts: 5, lastAttemptAt: 1_000 });
+
+ const d = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS, NO_JITTER);
+
+ // Budget restarts, so this is attempt 1 at baseDelay rather than a 5th attempt.
+ expect(d).toMatchObject({ kind: 'schedule', attempt: 1, delayMs: 5000, stabilityReset: true });
+ });
+
+ it('keeps accruing inside the stability window', () => {
+ const s = state({ attempts: 4, maxAttempts: 5, lastAttemptAt: 1_000 });
+
+ const d = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS - 1, NO_JITTER);
+
+ expect(d).toMatchObject({ attempt: 5, stabilityReset: false });
+ });
+
+ it('rescues a session that would otherwise wedge FAILED after unrelated transient drops', () => {
+ const s = state({ attempts: 5, maxAttempts: 5, lastAttemptAt: 1_000 });
+
+ // Without the reset this is exhausted; with it the session gets a fresh budget.
+ const d = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS, NO_JITTER);
+
+ expect(d.kind).toBe('schedule');
+ });
+
+ it('does not reset on the very first attempt (no prior timestamp)', () => {
+ const s = state();
+
+ expect(decideReconnect(s, 10 ** 12, NO_JITTER)).toMatchObject({ stabilityReset: false });
+ });
+ });
+
+ describe('loop alerting', () => {
+ it(`flags every ${RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS}th consecutive attempt`, () => {
+ const s = state();
+ const alerts: number[] = [];
+
+ for (let i = 0; i < 12; i++) {
+ const d = decideReconnect(s, 1_000, NO_JITTER);
+ if (d.kind === 'schedule' && d.loopAlert) alerts.push(d.attempt);
+ }
+
+ expect(alerts).toEqual([5, 10]);
+ });
+
+ it('does not alert on the first attempt of an episode', () => {
+ expect(decideReconnect(state(), 1_000, NO_JITTER)).toMatchObject({ loopAlert: false });
+ });
+
+ it('re-arms from attempt 5 again after a stability reset (new episode, not a continuing cadence)', () => {
+ const s = state({ attempts: 4, lastAttemptAt: 1_000 });
+
+ // A stable stretch resets the streak, so the next attempt is #1 and must not alert.
+ const first = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS, NO_JITTER);
+ expect(first).toMatchObject({ attempt: 1, loopAlert: false });
+
+ const alerts: number[] = [];
+ for (let i = 0; i < 5; i++) {
+ const d = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS, NO_JITTER);
+ if (d.kind === 'schedule' && d.loopAlert) alerts.push(d.attempt);
+ }
+ expect(alerts).toEqual([5]);
+ });
+ });
+});
+
+describe('clampReconnectDelay', () => {
+ it('passes a normal delay through', () => {
+ expect(clampReconnectDelay(8000, 5000)).toBe(8000);
+ });
+
+ it('floors a negative delay at 0', () => {
+ expect(clampReconnectDelay(-1, 5000)).toBe(0);
+ });
+
+ it('caps a huge delay so setTimeout cannot overflow and fire immediately', () => {
+ expect(clampReconnectDelay(Number.MAX_SAFE_INTEGER, 5000)).toBe(RECONNECT_DELAY_CAP_MS);
+ });
+
+ it('falls back to baseDelay when the computed delay is not finite', () => {
+ // An operator-supplied non-numeric config would otherwise yield NaN → setTimeout fires at 0.
+ // Infinity is likewise not finite, so it takes the same fallback rather than the cap.
+ expect(clampReconnectDelay(NaN, 5000)).toBe(5000);
+ expect(clampReconnectDelay(Number.POSITIVE_INFINITY, 5000)).toBe(5000);
+ });
+});
diff --git a/src/modules/session/reconnect-policy.ts b/src/modules/session/reconnect-policy.ts
new file mode 100644
index 000000000..92c2e994f
--- /dev/null
+++ b/src/modules/session/reconnect-policy.ts
@@ -0,0 +1,124 @@
+/**
+ * The reconnect backoff *decision*, separated from its effects.
+ *
+ * `SessionService.scheduleReconnect` interleaves four rules (stability reset, budget exhaustion,
+ * exponential backoff with jitter, periodic loop alerting) with the side effects they trigger
+ * (status writes, engine eviction, webhooks, timers). The rules are the subtle part and the effects
+ * are the untestable part, so the rules live here as a pure function over explicit state.
+ *
+ * Pure by construction: no timers, no I/O, and `now`/`jitter` are injected, so every branch —
+ * including the ones that only occur after hours of uptime — is directly reachable in a test.
+ */
+
+/** Mutable per-session backoff state. Owned by the caller; this module only reads and derives. */
+export interface ReconnectAttemptState {
+ attempts: number;
+ maxAttempts: number;
+ baseDelay: number;
+ /** When the last attempt was scheduled (epoch ms) — feeds the stability reset. */
+ lastAttemptAt?: number;
+}
+
+/** Give up: the attempt budget is spent (or auto-reconnect was disabled outright). */
+export interface ReconnectExhausted {
+ kind: 'exhausted';
+ /** Operator-facing reason, surfaced via `lastError`. */
+ reason: string;
+}
+
+/** Schedule attempt `attempt` after `delayMs`. */
+export interface ReconnectScheduled {
+ kind: 'schedule';
+ delayMs: number;
+ /** 1-based number of the attempt being scheduled. */
+ attempt: number;
+ /** True when this attempt completes a loop-alert interval. */
+ loopAlert: boolean;
+ /** The attempt counter reset because the session had been stable. */
+ stabilityReset: boolean;
+}
+
+export type ReconnectDecision = ReconnectExhausted | ReconnectScheduled;
+
+/**
+ * A reconnect-attempt budget covers one CONTINUOUS bad stretch: once this much time has passed
+ * since the last scheduled attempt the session demonstrably stayed up, so `attempts` resets to 0.
+ * Without it a long-lived session would slowly accrue attempts toward an explicit cap across
+ * unrelated transient drops and one day wedge FAILED for no current reason.
+ */
+export const RECONNECT_STABILITY_RESET_MS = 300_000;
+
+/**
+ * A reconnect-loop alert fires once per this many CONSECUTIVE attempts of a session — one signal per
+ * ongoing episode, not spam per attempt. A broken-forever setup retries without limit (by design), so
+ * the 5th/10th/15th… scheduled attempt is the operator-facing tell; the streak resets via the
+ * stability window above (or onReady), so a later episode re-arms the alert from attempt 5 again.
+ */
+export const RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS = 5;
+
+/** Upper bound on a computed backoff delay (see clampReconnectDelay). */
+export const RECONNECT_DELAY_CAP_MS = 3_600_000;
+
+function clampNumber(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), max);
+}
+
+/**
+ * Clamp a computed backoff delay finite and within setTimeout's safe range (a huge value would
+ * overflow its 32-bit ms field and fire immediately).
+ */
+export function clampReconnectDelay(rawDelay: number, baseDelay: number): number {
+ return clampNumber(Number.isFinite(rawDelay) ? rawDelay : baseDelay, 0, RECONNECT_DELAY_CAP_MS);
+}
+
+/**
+ * Decide what should happen for the next reconnect of a session, and advance `state` accordingly.
+ *
+ * MUTATES `state` (attempts / lastAttemptAt) exactly as the original inline code did, so the caller
+ * keeps a single source of truth for the session's streak across calls.
+ *
+ * @param now Injected clock (epoch ms).
+ * @param jitter Injected jitter in ms, added before clamping (production passes `Math.random() * 1000`).
+ */
+export function decideReconnect(
+ state: ReconnectAttemptState,
+ now: number = Date.now(),
+ jitter: number = Math.random() * 1000,
+): ReconnectDecision {
+ // Stability reset: the attempt budget covers one CONTINUOUS bad stretch. When the session stayed
+ // up ≥5 min since the last scheduled attempt it demonstrably recovered, so the next drop
+ // restarts the budget — unrelated transient drops must not accrue toward an explicit cap over
+ // the session's lifetime.
+ let stabilityReset = false;
+ if (state.lastAttemptAt !== undefined && now - state.lastAttemptAt >= RECONNECT_STABILITY_RESET_MS) {
+ state.attempts = 0;
+ stabilityReset = true;
+ }
+
+ if (state.attempts >= state.maxAttempts) {
+ // maxAttempts:0 means auto-reconnect is disabled, not that N attempts were tried and failed — say
+ // so instead of the misleading "failed after 0 attempts".
+ return {
+ kind: 'exhausted',
+ reason:
+ state.maxAttempts === 0
+ ? 'Auto-reconnect is disabled (max attempts set to 0); the session was left disconnected — restart it manually.'
+ : `Reconnection failed after ${state.attempts} attempts — restart the session.`,
+ };
+ }
+
+ // Exponential backoff: baseDelay * 2^attempts (with jitter), clamped finite + within
+ // setTimeout's safe range so the timer can't overflow and fire immediately. With the default
+ // unlimited budget the delay parks at RECONNECT_DELAY_CAP_MS once the exponent outgrows it.
+ const delayMs = clampReconnectDelay(state.baseDelay * Math.pow(2, state.attempts) + jitter, state.baseDelay);
+ state.attempts++;
+ state.lastAttemptAt = now;
+
+ return {
+ kind: 'schedule',
+ delayMs,
+ attempt: state.attempts,
+ loopAlert: state.attempts > 0 && state.attempts % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS === 0,
+ stabilityReset,
+ };
+}
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index bd32079fc..fce28e2a0 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -24,6 +24,7 @@ import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-messa
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import { decideReconnect, clampReconnectDelay, type ReconnectAttemptState } from './reconnect-policy';
import { SessionLidResolver } from './session-lid-resolver.service';
import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
@@ -71,13 +72,9 @@ const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticke
// proves 50 too few.
const STATUS_SEED_LIMIT = 50;
-interface ReconnectState {
- attempts: number;
+interface ReconnectState extends ReconnectAttemptState {
+ /** The pending attempt's timer. Lives here, not in the policy, which stays free of side effects. */
timer: NodeJS.Timeout | null;
- maxAttempts: number;
- baseDelay: number;
- /** When the last attempt was scheduled (epoch ms) — feeds the stability reset in scheduleReconnect. */
- lastAttemptAt?: number;
}
// Reconnect-backoff bounds. An OPERATOR-supplied session.config feeds this math, so the values
@@ -86,21 +83,6 @@ interface ReconnectState {
const RECONNECT_BASE_DELAY_MIN_MS = 1000;
const RECONNECT_BASE_DELAY_MAX_MS = 300_000;
const RECONNECT_MAX_ATTEMPTS_CAP = 20;
-const RECONNECT_DELAY_CAP_MS = 3_600_000;
-/**
- * A reconnect-attempt budget covers one CONTINUOUS bad stretch: once this much time has passed
- * since the last scheduled attempt the session demonstrably stayed up, so `attempts` resets to 0.
- * Without it a long-lived session would slowly accrue attempts toward an explicit cap across
- * unrelated transient drops and one day wedge FAILED for no current reason.
- */
-const RECONNECT_STABILITY_RESET_MS = 300_000;
-/**
- * A reconnect-loop alert fires once per this many CONSECUTIVE attempts of a session — one signal per
- * ongoing episode, not spam per attempt. A broken-forever setup retries without limit (by design), so
- * the 5th/10th/15th… scheduled attempt is the operator-facing tell; the streak resets via the
- * stability window above (or onReady), so a later episode re-arms the alert from attempt 5 again.
- */
-const RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS = 5;
/**
* Session liveness watchdog. The engine layer is event-driven, so an engine that dies WITHOUT
* firing an event (a silent Chromium crash) is never noticed: the row sits READY forever and never
@@ -140,11 +122,7 @@ export function resolveReconnectConfig(
return { maxAttempts, baseDelay };
}
-/** Clamp a computed backoff delay finite and within setTimeout's safe range (a huge value would
- * overflow its 32-bit ms field and fire immediately). */
-export function clampReconnectDelay(rawDelay: number, baseDelay: number): number {
- return clampNumber(Number.isFinite(rawDelay) ? rawDelay : baseDelay, 0, RECONNECT_DELAY_CAP_MS);
-}
+export { clampReconnectDelay };
export function resolveMaxConcurrentSessions(configService?: Pick<ConfigService, 'get'>): number | null {
const configured = configService?.get<number>('sessions.maxConcurrent', 0) ?? 0;
@@ -2277,15 +2255,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const state = this.reconnectStates.get(id);
if (!state) return;
- // Stability reset: the attempt budget covers one CONTINUOUS bad stretch. When the session stayed
- // up ≥5 min since the last scheduled attempt it demonstrably recovered, so the next drop
- // restarts the budget — unrelated transient drops must not accrue toward an explicit cap over
- // the session's lifetime.
- if (state.lastAttemptAt !== undefined && Date.now() - state.lastAttemptAt >= RECONNECT_STABILITY_RESET_MS) {
- state.attempts = 0;
- }
+ // All the backoff rules (stability reset, budget, exponential delay, loop cadence) live in the
+ // pure policy; this method only applies the effects the decision calls for.
+ const decision = decideReconnect(state);
- if (state.attempts >= state.maxAttempts) {
+ if (decision.kind === 'exhausted') {
this.logger.error(`Max reconnect attempts reached for session: ${session.name}`, undefined, {
sessionId: id,
attempts: state.attempts,
@@ -2293,14 +2267,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
// Don't leave the session silently stuck DISCONNECTED — mark it terminally FAILED with a reason
// so findOne/findAll surface it via `lastError` and the dashboard shows it needs a restart.
- // maxAttempts:0 means auto-reconnect is disabled, not that N attempts were tried and failed — say
- // so instead of the misleading "failed after 0 attempts".
- this.sessionErrors.set(
- id,
- state.maxAttempts === 0
- ? 'Auto-reconnect is disabled (max attempts set to 0); the session was left disconnected — restart it manually.'
- : `Reconnection failed after ${state.attempts} attempts — restart the session.`,
- );
+ this.sessionErrors.set(id, decision.reason);
void this.updateStatus(id, SessionStatus.FAILED);
// Terminal path — evict the dead engine so it neither holds a concurrency slot nor makes a
// subsequent start() reject the session as "already started". This mirrors onError's terminal
@@ -2314,22 +2281,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return;
}
- // Exponential backoff: baseDelay * 2^attempts (with jitter), clamped finite + within
- // setTimeout's safe range so the timer can't overflow and fire immediately. With the default
- // unlimited budget the delay parks at RECONNECT_DELAY_CAP_MS once the exponent outgrows it.
- const delay = clampReconnectDelay(
- state.baseDelay * Math.pow(2, state.attempts) + Math.random() * 1000,
- state.baseDelay,
- );
- state.attempts++;
- state.lastAttemptAt = Date.now();
-
+ const delay = decision.delayMs;
const maxAttemptsLabel = Number.isFinite(state.maxAttempts) ? String(state.maxAttempts) : '∞';
this.logger.log(
- `Scheduling reconnect attempt ${state.attempts}/${maxAttemptsLabel} in ${Math.round(delay / 1000)}s`,
+ `Scheduling reconnect attempt ${decision.attempt}/${maxAttemptsLabel} in ${Math.round(delay / 1000)}s`,
{
sessionId: id,
- attempt: state.attempts,
+ attempt: decision.attempt,
delayMs: delay,
action: 'reconnect_scheduled',
},
@@ -2337,21 +2295,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
incrementSessionReconnectAttempts();
- // Loop alert every RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS consecutive attempts: with the default
- // unlimited budget a permanently-broken setup retries forever, and this is the one operator-facing
- // signal per ongoing episode (not per attempt). The streak resets via the stability window/onReady,
- // so a fresh episode re-arms the alert instead of continuing an old cadence.
- if (state.attempts > 0 && state.attempts % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS === 0) {
- this.logger.warn(`Session is reconnect-looping: attempt ${state.attempts} scheduled`, {
+ // One operator-facing signal per ongoing episode, not spam per attempt (see the policy).
+ if (decision.loopAlert) {
+ this.logger.warn(`Session is reconnect-looping: attempt ${decision.attempt} scheduled`, {
sessionId: id,
- attempts: state.attempts,
+ attempts: decision.attempt,
nextDelayMs: delay,
action: 'reconnect_loop',
});
incrementSessionReconnectLoopAlerts();
void this.webhookService.dispatch(id, 'session.reconnect_loop', {
sessionId: id,
- attempts: state.attempts,
+ attempts: decision.attempt,
nextDelayMs: delay,
});
}