Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): tear down an engine (re)connected after the session was deleted (#521)
Yudhi Armyndharis19782e23955e
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex cf423ce19..68f1a75f8 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -566,6 +566,24 @@ describe('SessionService', () => {expect(i.engines.has('sess-uuid-1')).toBe(false);});+ it('tears down an engine created when a delete lands during init (session row gone, mark cleared)', async () => {+ const i = internals();+ // The delete↔reconnect race: delete() clears its teardown mark in finally (ms) AND removes the+ // session row, both well before a slow engine.initialize() (Chromium launch) resolves. Unlike+ // stop(), delete() does not leave the mark set, so the mark alone can't catch it — the post-init+ // guard must re-check that the session still exists before keeping the engine it just created.+ mockEngine.initialize.mockImplementation(() => {+ i.stoppingSessions.delete('sess-uuid-1');+ (repository.findOne as jest.Mock).mockResolvedValue(null);+ return Promise.resolve();+ });++ await i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);++ expect(mockEngine.destroy).toHaveBeenCalled();+ expect(i.engines.has('sess-uuid-1')).toBe(false);+ });+it('still re-initializes when the old engine destroy() hangs (time-bounded teardown)', async () => {jest.useFakeTimers();try {@@ -1703,6 +1721,26 @@ describe('SessionService', () => {expect(mockEngine.destroy).toHaveBeenCalled();expect(service.getEngine('sess-uuid-1')).toBeUndefined();});++ it('tears down the just-initialized engine if the session is deleted during start() (row gone, mark cleared)', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ // Unlike a stop(), a concurrent delete() clears its teardown mark in finally AND removes the+ // session row before this init resolves — the mark alone can't catch it, so the post-init guard+ // must re-check existence. start() then surfaces the now-missing session as NotFound.+ mockEngine.initialize.mockImplementationOnce(() => {+ (service as unknown as { stoppingSessions: Set<string> }).stoppingSessions.delete('sess-uuid-1');+ (repository.findOne as jest.Mock).mockResolvedValue(null);+ return Promise.resolve();+ });++ await expect(service.start('sess-uuid-1')).rejects.toThrow(NotFoundException);++ expect(mockEngine.destroy).toHaveBeenCalled();+ expect(service.getEngine('sess-uuid-1')).toBeUndefined();+ });});// ── sendSeen (markChatRead) ───────────────────────────────────────diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 188a55f37..bca6770b9 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -438,7 +438,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// A stop()/delete() may have landed while we awaited engine.initialize() — if so, tear down the// engine we just registered so the session isn't resurrected to READY (mirrors the post-init// guard in executeReconnect; initialize()'s callbacks can also fire async after this returns).- if (this.stoppingSessions.has(id)) {+ // delete() clears its teardown mark before this slow init resolves, so re-check the session row+ // exists, not just the mark; the findOne below then surfaces a deleted session as NotFound.+ if (await this.isSessionRetired(id)) {const resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');@@ -1043,6 +1045,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}, delay);}+ /**+ * True once a session must stay down: it is explicitly marked tearing-down, or it was deleted+ * outright while a slow engine.initialize() was in flight. delete() clears its `stoppingSessions`+ * mark in its finally (ms) and removes the session row well before a Chromium launch resolves, so+ * the mark alone can't catch a delete that raced a (re)connect — the session row is the source of+ * truth a post-init guard must re-check before keeping the engine it just created.+ */+ private async isSessionRetired(id: string): Promise<boolean> {+ if (this.stoppingSessions.has(id)) {+ return true;+ }+ return (await this.sessionRepository.findOne({ where: { id } })) == null;+ }+private async executeReconnect(id: string, session: Session, state: ReconnectState): Promise<void> {// The session may have been stopped/deleted before this fired — don't resurrect it.if (this.stoppingSessions.has(id)) {@@ -1062,9 +1078,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Re-initializeawait this.initializeEngine(id, session);- // A stop()/delete() may have run while we awaited init — if so, tear down the engine we- // just registered so it isn't orphaned (the session is meant to be down).- if (this.stoppingSessions.has(id)) {+ // A stop()/delete() may have run while we awaited init — if so, tear down the engine we just+ // registered so it isn't orphaned (the session is meant to be down). delete() clears its+ // teardown mark before this slow init resolves, so re-check the session row exists, not just+ // the mark — otherwise a delete that raced the reconnect leaks a live Chromium/socket.+ if (await this.isSessionRetired(id)) {const resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');