Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): keep a replacement's status on an init timeout

Yudhi Armyndharisb8f4806f84a8
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 675b353c7..94b06b66f 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -795,13 +795,26 @@ export class SessionEngineLifecycle {
// Do NOT port this reorder to delete()/stop()/forceKill(): there, engines.has(id) staying
// TRUE for the duration of the teardown await is the sole deterministic block on a concurrent
// start() (start() clears stoppingSessions rather than rejecting on it), so delete-first would
- // open a start()-during-teardown orphan-engine window. Verified in the teardown-ordering audit.
+ // open a start()-during-teardown orphan-engine window.
const wasLive = this.engines.deleteIfLive(id, engine);
+ const reconnectState = this.reconnectStates.get(id);
+ const reconnectAttempt = reconnectState?.started;
+ // The teardown below can outlast a stop, a start or a later reconnect attempt, whose engine and
+ // status this deadline must then leave alone.
+ const isCurrentTimeout = (): boolean =>
+ wasLive &&
+ !this.engines.has(id) &&
+ this.reconnectStates.get(id) === reconnectState &&
+ reconnectState?.started === reconnectAttempt;
if (wasLive) this.sessionErrors.set(id, err.message);
// Force-kill whatever got launched so a retry doesn't collide with an orphaned browser.
// teardownEngineSafely is itself time-bound, so this can't wedge a second time.
await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
- if (wasLive) await this.updateStatus(id, SessionStatus.DISCONNECTED);
+ if (isCurrentTimeout()) {
+ await this.sessionRepository.update(id, { status: SessionStatus.DISCONNECTED });
+ // A replacement may reach READY while the database response is still pending.
+ if (isCurrentTimeout()) this.broadcaster.announce(id, SessionStatus.DISCONNECTED);
+ }
// Map to a diagnostic 504 like the auth-timeout branch below, so a wedged init doesn't escape as a
// bare 500 (#733 follow-up). This deadline covers EVERY cause and cannot tell them apart: the
// auth-timeout below only fires once the page has LOADED (whatsapp-web.js navigates with
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index f31f8adf8..42146d1e8 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -3381,6 +3381,7 @@ describe('SessionService', () => {
expect(mockEngine.forceDestroy).toHaveBeenCalled(); // wedged browser reaped
expect(intern().engines.has('sess-uuid-1')).toBe(false); // slot freed for retry
expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });
+ expect(eventsGateway.emitSessionStatus).toHaveBeenLastCalledWith('sess-uuid-1', SessionStatus.DISCONNECTED);
expect(scheduleReconnect).not.toHaveBeenCalled(); // no auto-reconnect from a start() timeout
} finally {
jest.useRealTimers();
@@ -3464,6 +3465,126 @@ describe('SessionService', () => {
}
});
+ it('preserves a replacement READY status while the old timeout teardown settles', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));
+ let finishDestroy: () => void = () => undefined;
+ mockEngine.forceDestroy.mockImplementationOnce(
+ () =>
+ new Promise<void>(resolve => {
+ finishDestroy = resolve;
+ }),
+ );
+ const replacement = {
+ ...mockEngine,
+ initialize: jest.fn().mockImplementation((callbacks: EngineEventCallbacks) => {
+ callbacks.onReady?.('628123', 'Alice');
+ callbacks.onStateChanged?.(EngineStatus.READY);
+ return Promise.resolve();
+ }),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ };
+ jest.useFakeTimers();
+ try {
+ const pending = (
+ lifecycle as unknown as {
+ initializeEngine: (id: string, session: Session) => Promise<void>;
+ }
+ )
+ .initializeEngine('sess-uuid-1', createMockSession())
+ .catch((error: unknown) => error);
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(mockEngine.forceDestroy).toHaveBeenCalled();
+ expect(registry.has('sess-uuid-1')).toBe(false);
+ (engineFactory.create as jest.Mock).mockReturnValueOnce(replacement);
+ await service.start('sess-uuid-1', { explicit: true });
+ (repository.update as jest.Mock).mockClear();
+ (eventsGateway.emitSessionStatus as jest.Mock).mockClear();
+ finishDestroy();
+ const error = await pending;
+ expect((error as HttpException).getStatus()).toBe(HttpStatus.GATEWAY_TIMEOUT);
+ expect(registry.get('sess-uuid-1')).toBe(replacement);
+ expect(repository.update).not.toHaveBeenCalled();
+ expect(eventsGateway.emitSessionStatus).not.toHaveBeenCalled();
+ } finally {
+ finishDestroy();
+ jest.useRealTimers();
+ }
+ });
+
+ it('propagates a failed timeout status write without announcing disconnection', async () => {
+ const failure = new Error('status write unavailable');
+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Partial<Session>) =>
+ patch.status === SessionStatus.DISCONNECTED ? Promise.reject(failure) : Promise.resolve({ affected: 1 }),
+ );
+ mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));
+ jest.useFakeTimers();
+ try {
+ const pending = (
+ lifecycle as unknown as {
+ initializeEngine: (id: string, session: Session) => Promise<void>;
+ }
+ )
+ .initializeEngine('sess-uuid-1', createMockSession())
+ .catch((error: unknown) => error);
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(await pending).toBe(failure);
+ expect(registry.has('sess-uuid-1')).toBe(false);
+ expect(eventsGateway.emitSessionStatus).not.toHaveBeenCalledWith('sess-uuid-1', SessionStatus.DISCONNECTED);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('does not announce an old timeout after its status write response outlives a replacement', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));
+ let finishStatus: () => void = () => undefined;
+ let storedStatus = SessionStatus.CREATED;
+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Partial<Session>) => {
+ if (patch.status) storedStatus = patch.status;
+ if (patch.status === SessionStatus.DISCONNECTED) {
+ return new Promise(resolve => {
+ finishStatus = () => resolve({ affected: 1 });
+ });
+ }
+ return Promise.resolve({ affected: 1 });
+ });
+ const replacement = {
+ ...mockEngine,
+ initialize: jest.fn().mockImplementation((callbacks: EngineEventCallbacks) => {
+ callbacks.onReady?.('628123', 'Alice');
+ callbacks.onStateChanged?.(EngineStatus.READY);
+ return Promise.resolve();
+ }),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ };
+ jest.useFakeTimers();
+ try {
+ const pending = (
+ lifecycle as unknown as {
+ initializeEngine: (id: string, session: Session) => Promise<void>;
+ }
+ )
+ .initializeEngine('sess-uuid-1', createMockSession())
+ .catch((error: unknown) => error);
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(storedStatus).toBe(SessionStatus.DISCONNECTED);
+ (engineFactory.create as jest.Mock).mockReturnValueOnce(replacement);
+ await service.start('sess-uuid-1', { explicit: true });
+ expect(storedStatus).toBe(SessionStatus.READY);
+ finishStatus();
+ const error = await pending;
+ expect((error as HttpException).getStatus()).toBe(HttpStatus.GATEWAY_TIMEOUT);
+ expect(registry.get('sess-uuid-1')).toBe(replacement);
+ expect(storedStatus).toBe(SessionStatus.READY);
+ expect(eventsGateway.emitSessionStatus).toHaveBeenLastCalledWith('sess-uuid-1', SessionStatus.READY);
+ } finally {
+ finishStatus();
+ jest.useRealTimers();
+ }
+ });
+
it("start()'s catch leaves a replacement engine alone when its own engine was superseded mid-init", async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });