Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): honour reconnect attempt limits and cap delay at 5 min

Yudhi Armyndharis3f5dcb349cf8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9678d1971..ba50a2d67 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The Italian (`it`) dashboard translates the session proxy Save button, the webhook chat-kind filter label and the warning shown when a backup export leaves out media ([#1583](https://github.com/rmyndharis/OpenWA/pull/1583)). Thanks @albanobattistella.
+### Fixed
+
+- An explicit `maxReconnectAttempts` is honoured and the reconnect delay is capped at 5 minutes; the budget used to restart once the backoff passed 5 minutes, so the limit was never reached and the documented 1-hour cap never applied.
+
## [0.23.5] - 2026-09-14
### Security
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.md
index a3ea9657c..8876fe1c7 100644
--- a/docs/08-development-guidelines.md
+++ b/docs/08-development-guidelines.md
@@ -442,7 +442,7 @@ import { resolveReconnectConfig } from './session-engine-lifecycle.service';
describe('resolveReconnectConfig', () => {
it('keeps reconnect settings finite and bounded', () => {
// Invalid maxReconnectAttempts falls back to the default: unlimited retries (the backoff
- // parks at the 1h cap); an invalid baseDelay is clamped up to the 1s minimum.
+ // parks at the 5-minute cap); an invalid baseDelay is clamped up to the 1s minimum.
expect(resolveReconnectConfig({ maxReconnectAttempts: 'bad', reconnectBaseDelay: -1 })).toEqual({
maxAttempts: Number.POSITIVE_INFINITY,
baseDelay: 1000,
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index e6b7a4db8..37e7d1eec 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -113,7 +113,7 @@ describe('resolveReconnectConfig', () => {
maxReconnectAttempts: 'not-a-number',
reconnectBaseDelay: -1,
}),
- // non-numeric attempts → the default: unlimited retries (backoff parks at the 1h cap);
+ // non-numeric attempts → the default: unlimited retries (backoff parks at the 5-minute cap);
// negative baseDelay → clamped up to the 1s minimum
).toEqual({ maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 1000 });
});
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 152212a08..5c462dcfc 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -584,7 +584,7 @@ The reconnect backoff is configured **per session**, not by environment variable
`reconnectBaseDelay` is the exponential-backoff base in milliseconds (clamped to 1000–300000,
default 5000). `maxReconnectAttempts` is clamped to 0–20 — `0` disables auto-reconnect entirely, and
-leaving it unset means unlimited retries with the delay parking at a 1-hour cap. Subscribe to the
+leaving it unset means unlimited retries with the delay parking at a 5-minute cap. Subscribe to the
`session.reconnect_loop` webhook to be alerted on every 5th consecutive attempt.
On a slow host, raise the first-boot init wait with `WWEBJS_AUTH_TIMEOUT_MS` (see _QR generation
diff --git a/docs/31-session-lifecycle-design.md b/docs/31-session-lifecycle-design.md
index 0f80c889c..7bd864a94 100644
--- a/docs/31-session-lifecycle-design.md
+++ b/docs/31-session-lifecycle-design.md
@@ -103,11 +103,11 @@ the Chromium process still holds file handles → rm fails or races a browser re
**Pinned by:** `logout-teardown-race.spec.ts` — the module's most complete race corpus. Read it
before touching anything in the logout/forceKill path.
-### INV-9 — The reconnect loop bounds itself: backoff with jitter, clamp ≤ 1h and ≤ setTimeout's 32-bit range, alert every 5 consecutive attempts
+### INV-9 — The reconnect loop bounds itself: backoff with jitter, clamp ≤ 5 min and ≤ setTimeout's 32-bit range, alert every 5 consecutive attempts
-**Defense:** `reconnect-policy.ts` — a pure decision function (5-minute stability reset, loop
-alerts) consumed by the lifecycle; the clamps exist because a naive `delay * 2^attempt` reaches
-values `setTimeout` silently truncates.
+**Defense:** `reconnect-policy.ts` — a pure decision function (attempt budget, loop alerts)
+consumed by the lifecycle, which resets the budget only when the session reaches READY; the clamps
+exist because a naive `delay * 2^attempt` reaches values `setTimeout` silently truncates.
**Pinned by:** `reconnect-policy.spec.ts`.
### INV-10 — Boot auto-start is sequential, staggered (2s per Chromium), and detached from bootstrap
diff --git a/src/modules/session/reconnect-config.spec.ts b/src/modules/session/reconnect-config.spec.ts
index 3354b3bfa..1efc419f1 100644
--- a/src/modules/session/reconnect-config.spec.ts
+++ b/src/modules/session/reconnect-config.spec.ts
@@ -7,7 +7,7 @@ import { resolveReconnectConfig } from './session-engine-lifecycle.service';
// false). These helpers coerce + clamp the config so the math is always finite and bounded.
describe('resolveReconnectConfig', () => {
it('defaults to a 5000ms base delay and UNLIMITED attempts for absent or empty config', () => {
- // A long-lived session must keep retrying forever (the backoff parks at the 1h cap) instead of
+ // A long-lived session must keep retrying forever (the backoff parks at the 5-minute cap) instead of
// dying permanently after ~2.5 minutes like the old 5-attempt default did.
expect(resolveReconnectConfig(null)).toEqual({ baseDelay: 5000, maxAttempts: Number.POSITIVE_INFINITY });
expect(resolveReconnectConfig({})).toEqual({ baseDelay: 5000, maxAttempts: Number.POSITIVE_INFINITY });
@@ -51,6 +51,6 @@ describe('clampReconnectDelay', () => {
});
it('caps the exponential so it never exceeds setTimeout range and fires immediately', () => {
- expect(clampReconnectDelay(1e15, 5000)).toBe(3_600_000);
+ expect(clampReconnectDelay(1e15, 5000)).toBe(300_000);
});
});
diff --git a/src/modules/session/reconnect-policy.spec.ts b/src/modules/session/reconnect-policy.spec.ts
index 62cd771ed..b96cb30e0 100644
--- a/src/modules/session/reconnect-policy.spec.ts
+++ b/src/modules/session/reconnect-policy.spec.ts
@@ -1,10 +1,10 @@
import {
decideReconnect,
clampReconnectDelay,
- RECONNECT_STABILITY_RESET_MS,
RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS,
RECONNECT_DELAY_CAP_MS,
type ReconnectAttemptState,
+ type ReconnectDecision,
} from './reconnect-policy';
const state = (over: Partial<ReconnectAttemptState> = {}): ReconnectAttemptState => ({
@@ -22,7 +22,7 @@ describe('decideReconnect', () => {
it('schedules the first attempt at baseDelay', () => {
const s = state();
- const d = decideReconnect(s, 1_000, NO_JITTER);
+ const d = decideReconnect(s, NO_JITTER);
expect(d).toMatchObject({ kind: 'schedule', delayMs: 5000, attempt: 1 });
});
@@ -32,7 +32,7 @@ describe('decideReconnect', () => {
const delays: number[] = [];
for (let i = 0; i < 4; i++) {
- const d = decideReconnect(s, 1_000, NO_JITTER);
+ const d = decideReconnect(s, NO_JITTER);
if (d.kind === 'schedule') delays.push(d.delayMs);
}
@@ -42,7 +42,7 @@ describe('decideReconnect', () => {
it('adds the supplied jitter before clamping', () => {
const s = state();
- const d = decideReconnect(s, 1_000, 777);
+ const d = decideReconnect(s, 777);
expect(d).toMatchObject({ delayMs: 5777 });
});
@@ -50,7 +50,7 @@ describe('decideReconnect', () => {
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);
+ const d = decideReconnect(s, NO_JITTER);
expect(d).toMatchObject({ delayMs: RECONNECT_DELAY_CAP_MS });
});
@@ -58,26 +58,18 @@ describe('decideReconnect', () => {
it('advances the caller-owned attempt counter', () => {
const s = state();
- decideReconnect(s, 1_000, NO_JITTER);
- decideReconnect(s, 1_000, NO_JITTER);
+ decideReconnect(s, NO_JITTER);
+ decideReconnect(s, 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);
+ const d = decideReconnect(s, NO_JITTER);
expect(d).toEqual({
kind: 'exhausted',
@@ -88,7 +80,7 @@ describe('decideReconnect', () => {
it('distinguishes "auto-reconnect disabled" from "N attempts failed"', () => {
const s = state({ attempts: 0, maxAttempts: 0 });
- const d = decideReconnect(s, 1_000, NO_JITTER);
+ const d = decideReconnect(s, NO_JITTER);
// maxAttempts:0 means disabled outright; "failed after 0 attempts" would be misleading.
expect(d).toEqual({
@@ -101,7 +93,7 @@ describe('decideReconnect', () => {
it('does not advance the counter once exhausted', () => {
const s = state({ attempts: 3, maxAttempts: 3 });
- decideReconnect(s, 1_000, NO_JITTER);
+ decideReconnect(s, NO_JITTER);
expect(s.attempts).toBe(3);
});
@@ -109,41 +101,49 @@ describe('decideReconnect', () => {
it('never exhausts on the default unlimited budget', () => {
const s = state({ attempts: 10_000 });
- expect(decideReconnect(s, 1_000, NO_JITTER).kind).toBe('schedule');
+ expect(decideReconnect(s, 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 });
- });
+ describe('over real elapsed time', () => {
+ beforeEach(() => jest.useFakeTimers({ now: 1_700_000_000_000 }));
+ afterEach(() => jest.useRealTimers());
+
+ // Each decision lands once the previous delay has elapsed plus a ~2 s failed connect, as in production.
+ const drive = (s: ReconnectAttemptState, decisions: number): ReconnectDecision[] => {
+ const out: ReconnectDecision[] = [];
+ for (let k = 0; k < decisions; k++) {
+ const d = decideReconnect(s, NO_JITTER);
+ out.push(d);
+ if (d.kind === 'schedule') jest.advanceTimersByTime(d.delayMs + 2000);
+ }
+ return out;
+ };
- it('keeps accruing inside the stability window', () => {
- const s = state({ attempts: 4, maxAttempts: 5, lastAttemptAt: 1_000 });
+ it.each([7, 20])('exhausts an explicit budget of %i on the next decision', max => {
+ const s = state({ maxAttempts: max });
- const d = decideReconnect(s, 1_000 + RECONNECT_STABILITY_RESET_MS - 1, NO_JITTER);
+ const out = drive(s, max + 1);
- expect(d).toMatchObject({ attempt: 5, stabilityReset: false });
+ const scheduled = out.slice(0, max).map(d => (d.kind === 'schedule' ? d.attempt : d.kind));
+ expect(scheduled).toEqual(Array.from({ length: max }, (_, k) => k + 1));
+ const last = out[max];
+ expect(last.kind === 'exhausted' && last.reason).toContain(`failed after ${max} attempts`);
});
- 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);
+ it('parks an unlimited budget at the 5-minute cap and never resets the streak', () => {
+ expect(RECONNECT_DELAY_CAP_MS).toBe(300_000);
- 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 });
+ const out = drive(s, 30);
+
+ const delays = out.map(d => (d.kind === 'schedule' ? d.delayMs : -1));
+ // 5000 * 2^6 = 320 s is the first computed delay past the cap, so attempt 7 onward parks there.
+ expect(delays.slice(0, 6)).toEqual([5000, 10000, 20000, 40000, 80000, 160000]);
+ expect(delays.slice(6).every(ms => ms === RECONNECT_DELAY_CAP_MS)).toBe(true);
+ expect(out[29]).toMatchObject({ kind: 'schedule', attempt: 30 });
+ expect(s.attempts).toBe(30);
});
});
@@ -153,7 +153,7 @@ describe('decideReconnect', () => {
const alerts: number[] = [];
for (let i = 0; i < 12; i++) {
- const d = decideReconnect(s, 1_000, NO_JITTER);
+ const d = decideReconnect(s, NO_JITTER);
if (d.kind === 'schedule' && d.loopAlert) alerts.push(d.attempt);
}
@@ -161,19 +161,20 @@ describe('decideReconnect', () => {
});
it('does not alert on the first attempt of an episode', () => {
- expect(decideReconnect(state(), 1_000, NO_JITTER)).toMatchObject({ loopAlert: false });
+ expect(decideReconnect(state(), 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 });
+ it('re-arms from attempt 5 again once READY clears the streak', () => {
+ const s = state({ attempts: 4 });
- // 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);
+ // What the lifecycle does on READY.
+ s.attempts = 0;
+ const first = decideReconnect(s, 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);
+ const d = decideReconnect(s, NO_JITTER);
if (d.kind === 'schedule' && d.loopAlert) alerts.push(d.attempt);
}
expect(alerts).toEqual([5]);
diff --git a/src/modules/session/reconnect-policy.ts b/src/modules/session/reconnect-policy.ts
index 5c5daccbf..5467c33ec 100644
--- a/src/modules/session/reconnect-policy.ts
+++ b/src/modules/session/reconnect-policy.ts
@@ -1,13 +1,13 @@
/**
* The reconnect backoff *decision*, separated from its effects.
*
- * `SessionEngineLifecycle.scheduleReconnect` interleaves four rules (stability reset, budget exhaustion,
- * exponential backoff with jitter, periodic loop alerting) with the side effects they trigger
+ * `SessionEngineLifecycle.scheduleReconnect` interleaves three rules (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.
+ * Pure by construction: no timers, no I/O, and `jitter` is injected, so every branch,
+ * including the capped long-streak ones, is directly reachable in a test.
*/
/** Mutable per-session backoff state. Owned by the caller; this module only reads and derives. */
@@ -15,8 +15,6 @@ 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). */
@@ -34,30 +32,23 @@ export interface ReconnectScheduled {
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.
+ * the 5th/10th/15th… scheduled attempt is the operator-facing tell; the streak resets only when the
+ * session reaches READY, 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;
+/**
+ * Upper bound on a computed backoff delay (see clampReconnectDelay). Kept at 5 minutes so a session
+ * recovers within about that long once a lengthy outage ends.
+ */
+export const RECONNECT_DELAY_CAP_MS = 300_000;
export function clampNumber(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
@@ -74,27 +65,18 @@ export function clampReconnectDelay(rawDelay: number, baseDelay: number): number
/**
* 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
+ * MUTATES `state` (attempts) 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;
- }
-
+ // The attempt counter only resets when the session reaches READY (the lifecycle does that). A reset
+ // keyed on elapsed time would fire as soon as the backoff delay itself grew past the window, so an
+ // explicit cap would never be reached.
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".
@@ -112,13 +94,11 @@ export function decideReconnect(
// 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-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index f727800b3..3903fdda9 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -58,7 +58,7 @@ const RECONNECT_MAX_ATTEMPTS_CAP = 20;
/** Coerce + clamp the untyped session.config reconnect knobs to finite, bounded values. Defaults are
* a 5000ms base delay and UNLIMITED attempts (`Infinity`): a long-lived session must keep retrying
- * (the backoff parks at the 1h cap) instead of dying permanently after ~2.5 minutes. An EXPLICIT
+ * (the backoff parks at the 5-minute cap) instead of dying permanently after ~2.5 minutes. An EXPLICIT
* `maxReconnectAttempts: 0` (disable) is preserved, and 1..20 clamps as before. */
export function resolveReconnectConfig(
config: { maxReconnectAttempts?: unknown; reconnectBaseDelay?: unknown } | null,
@@ -970,7 +970,7 @@ export class SessionEngineLifecycle {
const state = this.reconnectStates.get(id);
if (!state) return;
- // All the backoff rules (stability reset, budget, exponential delay, loop cadence) live in the
+ // All the backoff rules (budget, exponential delay, loop cadence) live in the
// pure policy; this method only applies the effects the decision calls for.
const decision = decideReconnect(state);
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 66c2a6000..e9950e394 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1646,16 +1646,17 @@ describe('SessionService', () => {
timer: NodeJS.Timeout | null;
maxAttempts: number;
baseDelay: number;
- lastAttemptAt?: number;
}
>;
+ engines: { set: (id: string, engine: unknown) => void };
sessionErrors: Map<string, string>;
scheduleReconnect: (id: string, session: Session) => void;
executeReconnect: (...args: unknown[]) => Promise<void>;
+ handleEngineReady: (id: string, engine: unknown, phone: string, pushName: string) => void;
};
const internals = (): PolicyInternals => lifecycle as unknown as PolicyInternals;
- it('keeps scheduling past the old 5-attempt budget by default (unlimited), the backoff parking at the 1h cap', () => {
+ it('keeps scheduling past the old 5-attempt budget by default (unlimited), the backoff parking at the 5-minute cap', () => {
jest.useFakeTimers();
try {
const i = internals();
@@ -1675,8 +1676,8 @@ describe('SessionService', () => {
expect(jest.getTimerCount()).toBe(1); // still exactly one pending timer
// The 12th schedule computed its delay with attempts=11: 5000*2^11 ≈ 10.24M ms, clamped to
- // the 1h cap — the timer fires exactly at the cap, not earlier.
- jest.advanceTimersByTime(3_599_999);
+ // the 5-minute cap; the timer fires exactly at the cap, not earlier.
+ jest.advanceTimersByTime(299_999);
expect(exec).not.toHaveBeenCalled();
jest.advanceTimersByTime(1);
expect(exec).toHaveBeenCalledTimes(1);
@@ -1686,37 +1687,46 @@ describe('SessionService', () => {
}
});
- it('resets the attempt budget after a 5-minute stable stretch (transient drops must not accrue)', () => {
+ it('resets the attempt budget only on READY, never because time passed between attempts', () => {
jest.useFakeTimers();
try {
const i = internals();
- const state = {
- attempts: 4,
- timer: null,
- maxAttempts: Number.POSITIVE_INFINITY,
- baseDelay: 5000,
- lastAttemptAt: Date.now(),
- };
+ (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);
const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+ // Each failed attempt lands after its whole delay (at most the 5-minute cap) plus a 2 s connect.
+ const failedAttempt = (): void => {
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ jest.advanceTimersByTime(302_000);
+ };
- // A drop 299s after the last attempt is still the same bad stretch: the budget keeps accruing.
- jest.advanceTimersByTime(299_999);
- i.scheduleReconnect('sess-uuid-1', createMockSession());
- expect(state.attempts).toBe(5); // 4 -> 5, no reset
+ for (let k = 0; k < 6; k++) failedAttempt();
+ expect(state.attempts).toBe(6);
- // ≥5 min since the last attempt means the session demonstrably stayed up — the budget
- // restarts at 0 (the first schedule's 80s timer fires during this advance; irrelevant here).
- jest.advanceTimersByTime(300_000);
+ // READY is the only reset, so the next drop restarts at the base delay (~5s).
+ const engine = {
+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ };
+ i.engines.set('sess-uuid-1', engine);
+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');
+ expect(state.attempts).toBe(0);
i.scheduleReconnect('sess-uuid-1', createMockSession());
expect(state.attempts).toBe(1);
-
- // ...so the backoff restarts at the base delay (~5s), not 2^4 × base (80s).
const callsBefore = exec.mock.calls.length;
jest.advanceTimersByTime(4_999);
expect(exec.mock.calls.length).toBe(callsBefore);
jest.advanceTimersByTime(1_001);
expect(exec.mock.calls.length).toBe(callsBefore + 1);
+
+ // Six more slow failures spend the explicit budget of 7; the next drop is terminal.
+ jest.advanceTimersByTime(302_000);
+ for (let k = 0; k < 6; k++) failedAttempt();
+ expect(state.attempts).toBe(7);
+ expect(i.sessionErrors.get('sess-uuid-1')).toBeUndefined();
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/Reconnection failed after 7 attempts/);
} finally {
jest.clearAllTimers();
jest.useRealTimers();
@@ -1755,10 +1765,11 @@ describe('SessionService', () => {
timer: NodeJS.Timeout | null;
maxAttempts: number;
baseDelay: number;
- lastAttemptAt?: number;
}
>;
+ engines: { set: (id: string, engine: unknown) => void };
scheduleReconnect: (id: string, session: Session) => void;
+ handleEngineReady: (id: string, engine: unknown, phone: string, pushName: string) => void;
};
const internals = (): LoopInternals => lifecycle as unknown as LoopInternals;
const loopDispatches = (): unknown[][] =>
@@ -1814,33 +1825,28 @@ describe('SessionService', () => {
expect(calls[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 5 });
expect((calls[0][2] as { nextDelayMs: number }).nextDelayMs).toBeGreaterThanOrEqual(80_000);
expect((calls[0][2] as { nextDelayMs: number }).nextDelayMs).toBeLessThan(81_000);
- // Attempt 10: computed with attempts=9 → 5000*2^9 = 2560s (+ <1s jitter).
- expect(calls[1][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 10 });
- expect((calls[1][2] as { nextDelayMs: number }).nextDelayMs).toBeGreaterThanOrEqual(2_560_000);
- expect((calls[1][2] as { nextDelayMs: number }).nextDelayMs).toBeLessThan(2_561_000);
+ // Attempt 10: computed with attempts=9 → 5000*2^9 = 2560s, clamped to the 5-minute cap.
+ expect(calls[1][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 10, nextDelayMs: 300_000 });
} finally {
jest.clearAllTimers();
jest.useRealTimers();
}
});
- it('re-arms the alert after a stability reset: the next alert waits 5 fresh attempts', () => {
+ it('re-arms the alert after READY: the next alert waits 5 fresh attempts', () => {
jest.useFakeTimers();
try {
const i = internals();
- // Four attempts already consumed, then the session stayed up ≥5 min — the budget resets.
- const state = {
- attempts: 4,
- timer: null,
- maxAttempts: Number.POSITIVE_INFINITY,
- baseDelay: 5000,
- lastAttemptAt: Date.now(),
- };
+ // Four attempts already consumed, then the session reached READY, which resets the budget.
+ const state = { attempts: 4, timer: null, maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 5000 };
i.reconnectStates.set('sess-uuid-1', state);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ const engine = { getStatus: jest.fn().mockReturnValue(EngineStatus.READY) };
+ i.engines.set('sess-uuid-1', engine);
const alertsBefore = getSessionReconnectLoopAlertsTotal();
- jest.advanceTimersByTime(300_000); // stability window elapses (no timer pending yet)
+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');
for (let k = 0; k < 4; k++) {
i.scheduleReconnect('sess-uuid-1', createMockSession());
}