Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): stop a failed reconnect arming over the attempt after it

Yudhi Armyndharis6619c648b8e7
diff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.ts
index 91571a011..6f1bc55bb 100644
--- a/src/modules/session/session-engine-lifecycle-races.spec.ts
+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts
@@ -75,6 +75,7 @@ interface Internals {
logger: { warn: (...args: unknown[]) => void };
executeReconnect(id: string, session: Session, state: ReconnectState): Promise<void>;
scheduleReconnect(id: string, session: Session): void;
+ handleEngineReady(id: string, engine: unknown, phone: string, pushName: string): void;
rejectRebind(id: string, engine: unknown, name: string, previous: string, incoming: string): Promise<void>;
}
@@ -113,7 +114,12 @@ describe('SessionEngineLifecycle races', () => {
MessageProjector,
{
provide: EventsGateway,
- useValue: { emitSessionStatus: jest.fn(), emitSessionDisconnected: jest.fn(), emitQRCode: jest.fn() },
+ useValue: {
+ emitSessionStatus: jest.fn(),
+ emitSessionDisconnected: jest.fn(),
+ emitQRCode: jest.fn(),
+ emitSessionAuthenticated: jest.fn(),
+ },
},
{ provide: WebhookService, useValue: { dispatch: jest.fn().mockResolvedValue(undefined) } },
{ provide: HookManager, useValue: { execute: jest.fn().mockResolvedValue({ continue: true, data: {} }) } },
@@ -265,4 +271,69 @@ describe('SessionEngineLifecycle races', () => {
});
});
});
+
+ describe('a reconnect attempt failing while the next one tears its engine down', () => {
+ it('leaves the episode to the later attempt instead of arming another over it', async () => {
+ const state: ReconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };
+ internals.reconnectStates.set(ID, state);
+ const initA = deferred();
+ const destroyA = deferred();
+ const engineA = {
+ ...makeEngine(),
+ initialize: jest.fn().mockReturnValue(initA.promise),
+ destroy: jest.fn().mockReturnValue(destroyA.promise),
+ };
+ const engineB = makeEngine();
+ engineFactory.create.mockReturnValueOnce(engineA).mockReturnValueOnce(engineB);
+
+ const attemptA = internals.executeReconnect(ID, session(), state);
+ await flush();
+ expect(internals.engines.get(ID)).toBe(engineA);
+
+ // Engine A drops mid-init: the next attempt is armed and fires, then waits on A's destroy.
+ internals.scheduleReconnect(ID, session());
+ clearTimeout(state.timer!);
+ state.timer = null;
+ const attemptB = internals.executeReconnect(ID, session(), state);
+ await flush();
+
+ // Closing A is what makes its pending initialize() reject, before B has registered anything.
+ initA.reject(new Error('Target closed'));
+ await attemptA;
+ expect(state.timer).toBeNull();
+
+ destroyA.resolve();
+ await attemptB;
+ await flush();
+
+ expect(internals.engines.get(ID)).toBe(engineB);
+ expect(state.timer).toBeNull();
+ expect(engineFactory.create).toHaveBeenCalledTimes(2);
+ });
+
+ it('re-arms when the attempt armed after it was cancelled by a READY before it fired', async () => {
+ const state: ReconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };
+ internals.reconnectStates.set(ID, state);
+ const initA = deferred();
+ const engineA = { ...makeEngine(), initialize: jest.fn().mockReturnValue(initA.promise) };
+ engineFactory.create.mockReturnValueOnce(engineA);
+
+ const attemptA = internals.executeReconnect(ID, session(), state);
+ await flush();
+ expect(internals.engines.get(ID)).toBe(engineA);
+
+ // Engine A drops mid-init and arms the next attempt, then reaches READY, which cancels that timer.
+ internals.scheduleReconnect(ID, session());
+ expect(state.timer).not.toBeNull();
+ internals.handleEngineReady(ID, engineA, '628111', 'Push');
+ expect(state.timer).toBeNull();
+
+ // A's init still rejects afterwards: nothing else owns the episode, so A must arm a recovery.
+ initA.reject(new Error('Engine initialization timed out'));
+ await attemptA;
+
+ expect(internals.engines.has(ID)).toBe(false);
+ expect(state.timer).not.toBeNull();
+ });
+ });
});
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 497484e14..2bd81b0ce 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -56,6 +56,12 @@ export interface ReconnectState extends ReconnectAttemptState {
initInFlight?: boolean;
/** The failure parked during that window, applied or dropped by executeReconnect once init settles. */
parkedFailure?: { run: () => void; terminal: boolean };
+ /**
+ * How many attempts executeReconnect has started on this state. An attempt whose re-init fails compares
+ * it with its own number: a later attempt may be mid-teardown with nothing registered yet. A timer
+ * that READY cancelled never starts, so it does not count.
+ */
+ started?: number;
/** When the session last reached READY; consumed by the next scheduleReconnect (see STABLE_READY_MS). */
readyAt?: number;
/**
@@ -1246,6 +1252,7 @@ export class SessionEngineLifecycle {
// The engine this attempt registers, captured like start() does: the catch must reap this one, not
// whatever a later attempt has registered by the time the init rejects.
let mine: IWhatsAppEngine | undefined;
+ const attempt = (state.started = (state.started ?? 0) + 1);
try {
// Clean up old engine. Time-bound the teardown: a wedged Chromium (the common reconnect
// trigger) makes destroy() hang, and a raw await here would stall the reconnect forever —
@@ -1343,10 +1350,12 @@ export class SessionEngineLifecycle {
// start() sees the session as "already started". Only while it is still registered: otherwise the
// init deadline has reaped it already, or a later attempt destroyed it as its old engine.
if (mine && this.engines.isLive(id, mine)) this.evictAndForceDestroy(id, mine);
- // A disconnect of this attempt's engine mid-init re-armed the same state, and a later attempt
- // registered a replacement before this init rejected. That attempt owns the episode: arming
- // another would destroy its engine as the old one, or kill it on the exhausted branch.
- if (this.engines.has(id)) return;
+ // A disconnect of this attempt's engine mid-init re-armed the same state, so a later attempt that
+ // has started owns the episode, whether it has registered a replacement already or is still tearing
+ // this attempt's engine down (the teardown is often what made this init reject). Arming another
+ // would destroy its engine as the old one, or kill it on the exhausted branch. One still waiting on
+ // its timer needs no return: scheduleReconnect below keeps that timer.
+ if (this.engines.has(id) || state.started !== attempt) return;
if (this.stoppingSessions.has(id)) {
this.cancelReconnect(id);
return;