Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): stop a superseded reconnect before it registers an engine
Yudhi Armyndharisda1bdb521e5b
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex f82d95cb0..b4d1f9046 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -1248,6 +1248,15 @@ export class SessionEngineLifecycle {// engine was created, so there is nothing to evict and no dir to purge).await this.awaitPendingTeardown(session.name);+ // A stop, force-kill, logout, delete or shutdown during the awaits above dropped or replaced this+ // state, and a start after it may already run its own engine: registering one now would overwrite+ // that engine in the registry and leave it running beyond any control's reach. Nothing is awaited+ // between this check and the registration inside initializeEngine.+ if (this.reconnectStates.get(id) !== state || this.stoppingSessions.has(id)) {+ if (this.reconnectStates.get(id) === state) this.cancelReconnect(id);+ 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.state.initInFlight = true;diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex d93753045..433dbb6ca 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1965,12 +1965,9 @@ describe('SessionService', () => {jest.useFakeTimers();try {- const run = intern().executeReconnect('sess-uuid-1', createMockSession(), {- attempts: 1,- timer: null,- maxAttempts: 5,- baseDelay: 5000,- });+ const state = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };+ (lifecycle as unknown as { reconnectStates: Map<string, unknown> }).reconnectStates.set('sess-uuid-1', state);+ const run = intern().executeReconnect('sess-uuid-1', createMockSession(), state);await jest.advanceTimersByTimeAsync(10_000); // the graceful-destroy teardown race is lostawait run;@@ -2733,9 +2730,16 @@ describe('SessionService', () => {executeReconnect: (id: string, session: Session, state: unknown) => Promise<void>;stoppingSessions: Set<string>;engines: Map<string, unknown>;+ reconnectStates: Map<string, unknown>;}const internals = (): Internals => lifecycle as unknown as Internals;- const reconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };+ let reconnectState: { attempts: number; timer: null; maxAttempts: number; baseDelay: number };++ beforeEach(() => {+ // Registered as scheduleReconnect leaves it just before its timer fires executeReconnect.+ reconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };+ internals().reconnectStates.set('sess-uuid-1', reconnectState);+ });it('does not create an engine when the session was already stopped (early guard)', async () => {const i = internals();@@ -2839,6 +2843,33 @@ describe('SessionService', () => {expect(i.engines.has('sess-uuid-1')).toBe(false);});+ it('does not replace the engine a stop and start registered while it tore down the old engine', async () => {+ const i = internals();+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ let releaseDestroy: () => void = () => undefined;+ const old = {+ destroy: jest.fn(() => new Promise<void>(resolve => (releaseDestroy = resolve))),+ forceDestroy: jest.fn().mockResolvedValue(undefined),+ disconnect: jest.fn().mockResolvedValue(undefined),+ };+ const started = { ...mockEngine, destroy: jest.fn(), forceDestroy: jest.fn() };+ const replacement = { ...mockEngine };+ (engineFactory.create as jest.Mock).mockReturnValueOnce(started).mockReturnValueOnce(replacement);+ i.engines.set('sess-uuid-1', old);+ const reconnect = i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);+ await new Promise(resolve => setImmediate(resolve));+ await service.stop('sess-uuid-1');+ await service.start('sess-uuid-1', { explicit: true });+ releaseDestroy();+ await reconnect;++ expect(engineFactory.create).toHaveBeenCalledTimes(1);+ expect(i.engines.get('sess-uuid-1')).toBe(started);+ expect(started.destroy).not.toHaveBeenCalled();+ expect(started.forceDestroy).not.toHaveBeenCalled();+ });+it('does not stack reconnect timers when scheduled twice back-to-back', () => {jest.useFakeTimers();try {