Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): fence overlapping reconnect attempts

Yudhi Armyndharis6fb6aed4640b
diff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.ts
index 4909b483d..6261d6ddc 100644
--- a/src/modules/session/session-engine-lifecycle-races.spec.ts
+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts
@@ -724,6 +724,118 @@ describe('SessionEngineLifecycle races', () => {
});
describe('a reconnect attempt failing while the next one tears its engine down', () => {
+ it.each(['older first', 'later first'])(
+ 'launches only the latest attempt when teardown finishes %s',
+ async order => {
+ const state: ReconnectState = { attempts: 2, timer: null, maxAttempts: 5, baseDelay: 5000 };
+ internals.reconnectStates.set(ID, state);
+ const olderDestroy = deferred();
+ const laterDestroy = deferred();
+ const oldEngine = {
+ ...makeEngine(),
+ destroy: jest.fn().mockReturnValueOnce(olderDestroy.promise).mockReturnValueOnce(laterDestroy.promise),
+ };
+ internals.engines.set(ID, oldEngine as unknown as IWhatsAppEngine);
+ const older = internals.executeReconnect(ID, session(), state);
+ await flush();
+ const later = internals.executeReconnect(ID, session(), state);
+ await flush();
+ try {
+ if (order === 'older first') {
+ olderDestroy.resolve();
+ await older;
+ laterDestroy.resolve();
+ await later;
+ } else {
+ laterDestroy.resolve();
+ await later;
+ olderDestroy.resolve();
+ await older;
+ }
+ expect(engineFactory.create).toHaveBeenCalledTimes(1);
+ const replacement = engineFactory.create.mock.results[0].value as Record<string, jest.Mock>;
+ expect(internals.engines.get(ID)).toBe(replacement);
+ expect(replacement.destroy).not.toHaveBeenCalled();
+ expect(replacement.forceDestroy).not.toHaveBeenCalled();
+ expect(state).toMatchObject({ attempts: 2, started: 2, timer: null });
+ expect(internals.reconnectStates.get(ID)).toBe(state);
+ } finally {
+ olderDestroy.resolve();
+ laterDestroy.resolve();
+ await Promise.allSettled([older, later]);
+ }
+ },
+ );
+
+ it.each(['resolves', 'rejects'])(
+ 'keeps the later initialization and parked failure when the older one %s',
+ async outcome => {
+ const state: ReconnectState = { attempts: 2, timer: null, maxAttempts: 5, baseDelay: 5000 };
+ internals.reconnectStates.set(ID, state);
+ const olderInit = deferred();
+ const laterInit = deferred();
+ const olderEngine = { ...makeEngine(), initialize: jest.fn().mockReturnValue(olderInit.promise) };
+ const laterEngine: Record<string, jest.Mock> = {
+ ...makeEngine(),
+ initialize: jest.fn().mockReturnValue(laterInit.promise),
+ };
+ engineFactory.create.mockReturnValueOnce(olderEngine).mockReturnValueOnce(laterEngine);
+ const older = internals.executeReconnect(ID, session(), state);
+ await flush();
+ const later = internals.executeReconnect(ID, session(), state);
+ await flush();
+ try {
+ const callbacks = (laterEngine.initialize.mock.calls as [EngineEventCallbacks][])[0][0];
+ callbacks.onError?.('temporary network failure');
+ const parked = state.parkedFailure;
+ expect(parked).toBeDefined();
+ if (outcome === 'resolves') olderInit.resolve();
+ else olderInit.reject(new Error('Target closed'));
+ await older;
+ expect(state.initInFlight).toBe(true);
+ expect(state.parkedFailure).toBe(parked);
+ expect(internals.engines.get(ID)).toBe(laterEngine);
+ expect(laterEngine.destroy).not.toHaveBeenCalled();
+ expect(laterEngine.forceDestroy).not.toHaveBeenCalled();
+ expect(state).toMatchObject({ attempts: 2, started: 2, timer: null });
+ } finally {
+ olderInit.resolve();
+ laterInit.resolve();
+ await Promise.allSettled([older, later]);
+ }
+ },
+ );
+
+ it.each(['removed', 'stopped'])(
+ 'keeps the replacement when an older retirement read finds the session %s',
+ async retired => {
+ const state: ReconnectState = { attempts: 2, timer: null, maxAttempts: 5, baseDelay: 5000 };
+ internals.reconnectStates.set(ID, state);
+ const read = deferred<Session | null>();
+ repository.findOne.mockReturnValueOnce(read.promise);
+ const olderEngine = makeEngine();
+ const laterEngine = makeEngine();
+ engineFactory.create.mockReturnValueOnce(olderEngine).mockReturnValueOnce(laterEngine);
+ const older = internals.executeReconnect(ID, session(), state);
+ await flush();
+ const later = internals.executeReconnect(ID, session(), state);
+ try {
+ await later;
+ read.resolve(retired === 'removed' ? null : session({ desiredState: 'stopped' }));
+ await older;
+ expect(internals.engines.get(ID)).toBe(laterEngine);
+ expect(olderEngine.destroy).toHaveBeenCalledTimes(1);
+ expect(laterEngine.destroy).not.toHaveBeenCalled();
+ expect(laterEngine.forceDestroy).not.toHaveBeenCalled();
+ expect(internals.reconnectStates.get(ID)).toBe(state);
+ expect(state).toMatchObject({ attempts: 2, started: 2, timer: null });
+ } finally {
+ read.resolve(session());
+ await Promise.allSettled([older, later]);
+ }
+ },
+ );
+
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);
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 093ea3e3d..6a8afe54c 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -1389,6 +1389,8 @@ export class SessionEngineLifecycle {
if (this.reconnectStates.get(id) === state) this.cancelReconnect(id);
return;
}
+ // Another attempt can finish tearing down this same engine first while sharing the episode.
+ if (state.started !== attempt) return;
// Re-initialize. An engine failure reported inside this window is parked (see
// parkReconnectInitFailure): a failed launch must retry, not land FAILED and strand the session.
@@ -1400,8 +1402,9 @@ export class SessionEngineLifecycle {
mine = registered !== before ? registered : undefined;
await init;
} finally {
- state.initInFlight = false;
+ if (state.started === attempt) state.initInFlight = false;
}
+ if (this.reconnectStates.get(id) !== state || state.started !== attempt) return;
// Init resolved, so a failure the engine reported meanwhile (a stuck-auth or readiness timer, an
// auth failure) is real: apply it, unless a stop/delete/start already replaced this state.
const parked = state.parkedFailure;
@@ -1422,10 +1425,10 @@ export class SessionEngineLifecycle {
retired = false;
}
if (retired) {
- const resurrected = this.engines.get(id);
- if (resurrected) {
- await this.fences.destroyWithEscalation(id, resurrected);
- this.engines.deleteIfLive(id, resurrected);
+ // The read can outlive this attempt. Only its captured engine is ours to retire.
+ if (mine && this.engines.isLive(id, mine)) {
+ await this.fences.destroyWithEscalation(id, mine);
+ this.engines.deleteIfLive(id, mine);
}
// Same start/delete window as start()'s post-init guard: this re-init re-created auth dirs
// delete() had already purged — purge again so no credentials outlive the row.
@@ -1438,12 +1441,11 @@ export class SessionEngineLifecycle {
sessionId: id,
action: 'reconnect_error',
});
+ // A delete (or delete + start) replaced this state while init ran: nothing here is ours any more,
+ // and a later attempt in the same episode owns its initialization marker and parked failure too.
+ if (this.reconnectStates.get(id) !== state || state.started !== attempt) return;
const parked = state.parkedFailure;
state.parkedFailure = undefined;
- // A delete (or delete + start) replaced this state while init ran: nothing here is ours any more,
- // and the engine in the map may be the replacement's. No await may sit between this check and
- // the eviction/scheduling below.
- if (this.reconnectStates.get(id) !== state) return;
// A failure only the operator can fix (re-scan, stale profile) stays terminal on a reconnect too.
if (parked && (parked.terminal || isKnownTerminalEngineFailure(errorMessage))) {
parked.run();