Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): do not register an engine once a stop has landed

Yudhi Armyndharisa80f75c67dcb
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 4a08677be..0f0055b2a 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -605,6 +605,11 @@ export class SessionEngineLifecycle {
}
private async initializeEngine(id: string, session: Session): Promise<void> {
+ // A stop that landed before this engine exists had nothing to tear down and already wrote its
+ // DISCONNECTED; registering now would overwrite it with INITIALIZING and then retire. start()
+ // clears its own mark and executeReconnect checks it on entry, so a mark seen here always came
+ // from a later stop, force-kill, logout or delete.
+ if (this.stoppingSessions.has(id)) return;
this.logger.log(`Initializing engine for session: ${session.name}`, {
sessionId: id,
action: 'engine_init',
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 2b88a1363..d93753045 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -7083,6 +7083,28 @@ describe('SessionService', () => {
expect(engineFactory.purgeSessionData).not.toHaveBeenCalledWith('sess-uuid-2');
});
+ it('keeps the DISCONNECTED a stop wrote while start() awaited session:starting', async () => {
+ // The stop finds no engine yet, so nothing fences its write: an engine registered after it
+ // would overwrite the row with INITIALIZING and then retire, leaving a stopped session that
+ // reads as starting, with no engine, until the next boot.
+ const row = createMockSession({ status: SessionStatus.DISCONNECTED });
+ (repository.findOne as jest.Mock).mockImplementation(() => Promise.resolve({ ...row }));
+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Partial<Session>) => {
+ Object.assign(row, patch);
+ return Promise.resolve({ affected: 1 });
+ });
+ (hookManager.execute as jest.Mock).mockImplementation(async (event: string) => {
+ if (event === 'session:starting') await service.stop('sess-uuid-1');
+ return { continue: true, data: {} };
+ });
+
+ await service.start('sess-uuid-1');
+
+ expect(row).toMatchObject({ status: SessionStatus.DISCONNECTED, desiredState: 'stopped' });
+ expect(engineFactory.create).not.toHaveBeenCalled();
+ expect(service.getEngine('sess-uuid-1')).toBeUndefined();
+ });
+
it('does not purge anything on a normal start (session row present throughout)', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });