Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): let a start yield to a stop mark set while it waits
Yudhi Armyndhariseb918d186ca6
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex 1fc4c6169..f34686846 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -175,6 +175,10 @@ export class SessionEngineControls {throw new BadRequestException('Session is already starting');}this.initializingSessions.add(id);+ // A stop mark already set when this start began is stale (a start is how one is cleared). One set+ // while it waits below comes from a retirement that saw this start in flight, stopOrphanEngines+ // above all, which writes nothing else this start could read and counts on it aborting.+ const markedAtEntry = this.stoppingSessions.has(id);try {const session = await this.requireSession(id);@@ -219,7 +223,11 @@ export class SessionEngineControls {// again, so a refused start does not leave a false "already starting" mark behind (briefly held).await this.fences.awaitPendingTeardown(session.name);- // A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.+ // A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark, but+ // yield to one set after this start began, leaving it in place.+ if (this.stoppingSessions.has(id) && !markedAtEntry) {+ throw new SessionStoppedException(`Session ${id} was stopped`);+ }this.stoppingSessions.delete(id);// Cancel any reconnect timer a prior failed executeReconnect left pending, BEFORE the awaiteddiff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.tsindex a64d04bbd..9c2b77d25 100644--- a/src/modules/session/session-engine-lifecycle-races.spec.ts+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts@@ -1,6 +1,7 @@import { Test } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { BadRequestException } from '@nestjs/common';+import { SessionStoppedException } from './session-engine-controls';import { ConfigService } from '@nestjs/config';import { SessionService } from './session.service';import { SessionEngineLifecycle, type ReconnectState } from './session-engine-lifecycle.service';@@ -53,6 +54,21 @@ const makeEngine = (): Record<string, jest.Mock> => ({getQRCode: jest.fn().mockReturnValue(null),});+/** A promise the test settles by hand. */+const deferred = <T = void>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+};++const flush = async (): Promise<void> => {+ for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve));+};+interface Internals {engines: EngineRegistry;reconnectStates: Map<string, ReconnectState>;@@ -139,4 +155,36 @@ describe('SessionEngineLifecycle races', () => {expect(internals.engines.has(ID)).toBe(true);});});++ describe('stopOrphanEngines against a start still reading its row', () => {+ it('retires the start instead of letting it clear the stop mark', async () => {+ const read = deferred<Session>();+ repository.findOne.mockReturnValueOnce(read.promise);++ const starting = lifecycle.start(ID);+ const outcome = starting.then(+ () => undefined,+ (e: unknown) => e,+ );+ await flush();+ await expect(lifecycle.stopOrphanEngines([ID])).resolves.toEqual({+ stopped: [],+ notRunning: [ID],+ failed: [],+ });+ read.resolve(session());++ expect(await outcome).toBeInstanceOf(SessionStoppedException);+ expect(engineFactory.create).not.toHaveBeenCalled();+ expect(internals.engines.has(ID)).toBe(false);+ });++ it('still clears a stop mark left from before the start began', async () => {+ await lifecycle.stopOrphanEngines([ID]);++ await lifecycle.start(ID);++ expect(internals.engines.has(ID)).toBe(true);+ });+ });});