Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): do not announce INITIALIZING for a retired engine

Yudhi Armyndharis8e7122a76620
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 27159b941..675b353c7 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -706,7 +706,11 @@ export class SessionEngineLifecycle {
// await, ownership is re-validated by object identity + the synchronous stop mark before the
// adapter is allowed to initialize — a retired engine must never reach initialize() (which would
// re-arm a torn-down adapter and open an untracked socket).
- const initialStatusPromise = this.updateStatus(id, SessionStatus.INITIALIZING);
+ const initialStatusPromise = this.updateStatus(
+ id,
+ SessionStatus.INITIALIZING,
+ () => !this.closed && this.isLiveEngine(id, engine) && !this.stoppingSessions.has(id),
+ );
this.pendingInitialStatuses.set(id, { engine, promise: initialStatusPromise });
try {
await initialStatusPromise;
@@ -1508,8 +1512,8 @@ export class SessionEngineLifecycle {
// Deliberately NON-async: callers (initializeEngine's pending-initial-status fence above all)
// must await the broadcaster's own promise object, keeping the exact settlement profile the
// inline method had — an async wrapper would add adoption hops the retirement-race specs catch.
- updateStatus(id: string, status: SessionStatus): Promise<void> {
- return this.broadcaster.updateStatus(id, status);
+ updateStatus(id: string, status: SessionStatus, canAnnounce?: () => boolean): Promise<void> {
+ return this.broadcaster.updateStatus(id, status, canAnnounce);
}
/**
diff --git a/src/modules/session/session-initial-status-retirement.spec.ts b/src/modules/session/session-initial-status-retirement.spec.ts
new file mode 100644
index 000000000..e21e28fdf
--- /dev/null
+++ b/src/modules/session/session-initial-status-retirement.spec.ts
@@ -0,0 +1,223 @@
+import { SessionEngineLifecycle } from './session-engine-lifecycle.service';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { Session, SessionStatus } from './entities/session.entity';
+import { ENGINE_TEARDOWN_TIMEOUT_MS, SessionLifecycleFences } from './session-lifecycle-fences';
+
+const ID = '11111111-1111-4111-8111-111111111111';
+
+function deferred() {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+
+async function waitFor(check: () => void): Promise<void> {
+ for (let i = 0; i < 200; i++) {
+ try {
+ check();
+ return;
+ } catch {
+ await Promise.resolve();
+ }
+ }
+ check();
+}
+
+describe('initial status replies after engine retirement', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+ afterEach(() => {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ jest.restoreAllMocks();
+ });
+
+ function fixture() {
+ let row: Session | null = { id: ID, name: 'pending-session', phone: null, config: {} } as Session;
+ let firstInitial = true;
+ const reply = deferred();
+ const committed: SessionStatus[] = [];
+ const emitSessionStatus = jest.fn();
+ const dispatch = jest.fn().mockResolvedValue(undefined);
+ const state = { attachTo: <T>(value: T): T => value, clear: jest.fn(), set: jest.fn(), get: jest.fn() };
+ const repository = {
+ findOne: jest.fn(() => Promise.resolve(row ? { ...row } : null)),
+ exists: jest.fn().mockResolvedValue(false),
+ update: jest.fn((id: string, patch: Partial<Session>) => {
+ expect(id).toBe(ID);
+ if (row) Object.assign(row, patch);
+ if (patch.status) committed.push(patch.status);
+ // The database effect precedes its delayed reply; no commit reordering is simulated.
+ if (patch.status === SessionStatus.INITIALIZING && firstInitial) {
+ firstInitial = false;
+ return reply.promise.then(() => ({ affected: 1 }));
+ }
+ return Promise.resolve({ affected: row ? 1 : 0 });
+ }),
+ };
+ const query = {
+ select: jest.fn(),
+ addSelect: jest.fn(),
+ where: jest.fn(),
+ andWhere: jest.fn(),
+ orderBy: jest.fn(),
+ addOrderBy: jest.fn(),
+ limit: jest.fn(),
+ getRawMany: jest.fn().mockResolvedValue([]),
+ };
+ for (const method of ['select', 'addSelect', 'where', 'andWhere', 'orderBy', 'addOrderBy', 'limit'] as const) {
+ query[method].mockReturnValue(query);
+ }
+ const manager = {
+ delete: jest.fn().mockResolvedValue({ affected: 0 }),
+ remove: jest.fn(() => {
+ row = null;
+ return Promise.resolve();
+ }),
+ };
+ const dataSource = {
+ options: { type: 'postgres' },
+ getRepository: (target: unknown) => ({
+ target,
+ find: jest.fn().mockResolvedValue([]),
+ createQueryBuilder: () => query,
+ }),
+ transaction: jest.fn((run: (manager: unknown) => Promise<unknown>) => run(manager)),
+ };
+ const createEngine = () => ({
+ initialize: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ });
+ const engines: Array<ReturnType<typeof createEngine>> = [];
+ const factory = {
+ create: jest.fn(() => {
+ const engine = createEngine();
+ engines.push(engine);
+ return engine;
+ }),
+ purgeSessionData: jest.fn().mockResolvedValue(undefined),
+ };
+ const registry = new EngineRegistry();
+ const lifecycle = new SessionEngineLifecycle(
+ repository as never,
+ dataSource as never,
+ factory as never,
+ registry,
+ {} as never,
+ {} as never,
+ state as never,
+ state as never,
+ state as never,
+ { emitSessionStatus } as never,
+ { dispatch } as never,
+ { execute: jest.fn().mockResolvedValue({ continue: true }) } as never,
+ {} as never,
+ );
+ const initialize = (): Promise<void> =>
+ (lifecycle as unknown as { initializeEngine(id: string, session: Session): Promise<void> }).initializeEngine(ID, {
+ ...row!,
+ });
+ const initial = initialize().then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ return {
+ reply,
+ committed,
+ emitSessionStatus,
+ dispatch,
+ registry,
+ lifecycle,
+ initialize,
+ initial,
+ engines,
+ row: () => row,
+ };
+ }
+
+ async function retire(f: ReturnType<typeof fixture>, action: 'stop' | 'delete'): Promise<void> {
+ const awaitingStatus = jest.spyOn(SessionLifecycleFences.prototype, 'awaitInitialStatus');
+ const control = action === 'stop' ? f.lifecycle.stop(ID) : f.lifecycle.delete(ID);
+ void control.catch(() => undefined);
+ await waitFor(() => expect(awaitingStatus).toHaveBeenCalledWith(ID, f.engines[0]));
+ await jest.advanceTimersByTimeAsync(ENGINE_TEARDOWN_TIMEOUT_MS + 1);
+ await control;
+ expect(f.registry.has(ID)).toBe(false);
+ expect(f.engines[0].initialize).not.toHaveBeenCalled();
+ }
+
+ it.each([
+ ['stop', false],
+ ['delete', false],
+ ['stop', true],
+ ['delete', true],
+ ] as const)('keeps %s notifications final when an initial reply rejects=%s', async (action, rejected) => {
+ const f = fixture();
+ try {
+ expect(f.committed).toEqual([SessionStatus.INITIALIZING]);
+ await retire(f, action);
+ const events = f.emitSessionStatus.mock.calls.slice();
+ const webhooks = f.dispatch.mock.calls.slice();
+ const failure = new Error('delayed reply failed');
+ if (rejected) f.reply.reject(failure);
+ else f.reply.resolve();
+ expect(await f.initial).toBe(rejected ? failure : undefined);
+ expect(f.emitSessionStatus.mock.calls).toEqual(events);
+ expect(f.dispatch.mock.calls).toEqual(webhooks);
+ expect(f.row()?.status ?? null).toBe(action === 'stop' ? SessionStatus.DISCONNECTED : null);
+ expect(f.committed).toEqual(
+ action === 'stop' ? [SessionStatus.INITIALIZING, SessionStatus.DISCONNECTED] : [SessionStatus.INITIALIZING],
+ );
+ } finally {
+ f.reply.resolve();
+ await f.initial;
+ }
+ });
+
+ it('announces a delayed initial reply while the same engine remains current', async () => {
+ const f = fixture();
+ try {
+ await jest.advanceTimersByTimeAsync(ENGINE_TEARDOWN_TIMEOUT_MS + 1);
+ f.reply.resolve();
+ expect(await f.initial).toBeUndefined();
+ expect(f.engines[0].initialize).toHaveBeenCalledTimes(1);
+ expect(f.emitSessionStatus).toHaveBeenCalledWith(ID, SessionStatus.INITIALIZING);
+ expect(f.dispatch).toHaveBeenCalledWith(ID, 'session.status', {
+ sessionId: ID,
+ status: SessionStatus.INITIALIZING,
+ });
+ } finally {
+ f.reply.resolve();
+ await f.initial;
+ }
+ });
+
+ it('preserves a replacement READY announcement when an older initial reply settles', async () => {
+ const f = fixture();
+ try {
+ await retire(f, 'stop');
+ f.lifecycle.clearStopping(ID);
+ await f.initialize();
+ const replacement = f.registry.get(ID);
+ await f.lifecycle.updateStatus(ID, SessionStatus.READY);
+ const events = f.emitSessionStatus.mock.calls.slice();
+ const webhooks = f.dispatch.mock.calls.slice();
+ f.reply.resolve();
+ expect(await f.initial).toBeUndefined();
+ expect(f.registry.get(ID)).toBe(replacement);
+ expect(f.row()?.status).toBe(SessionStatus.READY);
+ expect(f.emitSessionStatus.mock.calls).toEqual(events);
+ expect(f.dispatch.mock.calls).toEqual(webhooks);
+ } finally {
+ f.reply.resolve();
+ await f.initial;
+ }
+ });
+});
diff --git a/src/modules/session/session-lifecycle-fences.ts b/src/modules/session/session-lifecycle-fences.ts
index cf66313ec..e01999dbf 100644
--- a/src/modules/session/session-lifecycle-fences.ts
+++ b/src/modules/session/session-lifecycle-fences.ts
@@ -176,8 +176,9 @@ export class SessionLifecycleFences {
* Wait for the captured `engine`'s exact in-flight `updateStatus(INITIALIZING)` write to settle.
* Called by every retiring lifecycle control (stop/logout/delete/forceKill) AFTER the stop mark is
* set and reconnect cancelled, and BEFORE teardown / the final DISCONNECTED write / parent-row
- * deletion. This keeps the control action the final persisted owner: a delayed INITIALIZING write
- * always settles first, so it can never land after the DISCONNECTED write or the row removal.
+ * deletion. A write that settles within the deadline precedes the control's final mutation.
+ * Retirement proceeds at the deadline; a late initial-status reply separately checks its captured
+ * engine before announcing, so it cannot emit after that engine has retired.
*
* Identity-checked on the engine object: a control action that captured engine A awaits ONLY A's
* pending promise, never a replacement B's entry (and never deletes it). A bounded wait mirrors
diff --git a/src/modules/session/session-status-broadcaster.spec.ts b/src/modules/session/session-status-broadcaster.spec.ts
index d10e8c68b..8055445c7 100644
--- a/src/modules/session/session-status-broadcaster.spec.ts
+++ b/src/modules/session/session-status-broadcaster.spec.ts
@@ -102,4 +102,40 @@ describe('SessionStatusBroadcaster', () => {
await broadcaster.updateStatus('s1', SessionStatus.READY);
expect(emitSessionStatus).toHaveBeenCalledTimes(2);
});
+
+ it.each([false, true])('checks announcement permission after the write settles: %s', async allowed => {
+ const { broadcaster, update, emitSessionStatus, dispatch } = make();
+ let resolve!: () => void;
+ update.mockImplementationOnce(() => new Promise<void>(yes => (resolve = yes)));
+ let current = true;
+ const canAnnounce = jest.fn(() => current);
+ broadcaster.lastDispatchedStatus.set('s1', SessionStatus.DISCONNECTED);
+
+ const pending = broadcaster.updateStatus('s1', SessionStatus.INITIALIZING, canAnnounce);
+ expect(canAnnounce).not.toHaveBeenCalled();
+ current = allowed;
+ resolve();
+ await pending;
+
+ expect(update).toHaveBeenCalledWith('s1', { status: SessionStatus.INITIALIZING });
+ expect(canAnnounce).toHaveBeenCalledTimes(1);
+ expect(emitSessionStatus).toHaveBeenCalledTimes(allowed ? 1 : 0);
+ expect(dispatch).toHaveBeenCalledTimes(allowed ? 1 : 0);
+ expect(broadcaster.lastDispatchedStatus.get('s1')).toBe(
+ allowed ? SessionStatus.INITIALIZING : SessionStatus.DISCONNECTED,
+ );
+ });
+
+ it('propagates a failed write without checking or announcing its status', async () => {
+ const { broadcaster, update, emitSessionStatus, dispatch } = make();
+ const failure = new Error('write failed');
+ update.mockRejectedValueOnce(failure);
+ const canAnnounce = jest.fn(() => true);
+
+ await expect(broadcaster.updateStatus('s1', SessionStatus.INITIALIZING, canAnnounce)).rejects.toBe(failure);
+
+ expect(canAnnounce).not.toHaveBeenCalled();
+ expect(emitSessionStatus).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
});
diff --git a/src/modules/session/session-status-broadcaster.ts b/src/modules/session/session-status-broadcaster.ts
index 971ce7c53..8c9e38c32 100644
--- a/src/modules/session/session-status-broadcaster.ts
+++ b/src/modules/session/session-status-broadcaster.ts
@@ -39,13 +39,18 @@ export class SessionStatusBroadcaster {
this.logger = deps.logger;
}
- async updateStatus(id: string, status: SessionStatus): Promise<void> {
+ /**
+ * `canAnnounce`, when given, is asked once the write has settled: a caller whose engine can retire
+ * while the write is in flight keeps a late reply from announcing a status that is no longer current.
+ */
+ async updateStatus(id: string, status: SessionStatus, canAnnounce?: () => boolean): Promise<void> {
await this.sessionRepository.update(id, { status });
this.logger.debug(`Session status updated to ${status}`, {
sessionId: id,
status,
action: 'status_update',
});
+ if (canAnnounce?.() === false) return;
this.announce(id, status);
}