Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): guard start() against a concurrent double-start that orphans an engine (#328)

Yudhi Armyndharis9a9feb77a6c0
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 85fd66df6..b72647243 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -266,6 +266,37 @@ describe('SessionService', () => {
});
});
+ // ── start (concurrency) ───────────────────────────────────────────
+ describe('start concurrency (F-04)', () => {
+ it('rejects a concurrent second start for the same id, creating only one engine (no orphan)', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+
+ // Two near-simultaneous start() calls for the SAME id. The has()->set() window spans an
+ // awaited hook, so without a synchronous reservation both would create an engine and the
+ // second set() would orphan the first's Chromium/lock dir.
+ const results = await Promise.allSettled([service.start('sess-uuid-1'), service.start('sess-uuid-1')]);
+
+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1);
+ const rejected = results.filter(r => r.status === 'rejected');
+ expect(rejected).toHaveLength(1);
+ expect(rejected[0].reason).toBeInstanceOf(BadRequestException);
+ // The decisive assertion: exactly ONE engine was ever created — no orphaned second engine.
+ expect(engineFactory.create).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows a fresh start after the previous one completed (reservation is cleared)', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+
+ await service.start('sess-uuid-1');
+ // Engine is now in the map, so a second start is 'already started' (not wedged at 'starting').
+ await expect(service.start('sess-uuid-1')).rejects.toBeInstanceOf(BadRequestException);
+ });
+ });
+
describe('findByName', () => {
it('should return session by name', async () => {
const session = createMockSession();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 61ca9f5e6..b5e2b1b23 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -97,6 +97,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// awaits and destroys any engine it just created; start() clears it (intentional restart).
private stoppingSessions: Set<string> = new Set();
+ // Sessions whose engine is mid-initialization (a start() is in flight). Reserved synchronously
+ // in start() so a near-simultaneous second start() can't pass the engines.has() check during the
+ // awaited hook and orphan an engine the lifecycle could never destroy.
+ private initializingSessions: Set<string> = new Set();
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
@@ -346,30 +351,42 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async start(id: string): Promise<Session> {
const session = await this.findOne(id);
+ // Reserve the slot SYNCHRONOUSLY (same tick as the has() check) so two near-simultaneous
+ // start() calls can't both pass the check and orphan an engine — the has() -> engines.set()
+ // window spans the awaited hook below. The second caller is rejected; the finally clears the
+ // reservation on success AND failure so a failed start never wedges at "already starting".
if (this.engines.has(id)) {
throw new BadRequestException('Session is already started');
}
+ if (this.initializingSessions.has(id)) {
+ throw new BadRequestException('Session is already starting');
+ }
+ this.initializingSessions.add(id);
- // A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.
- this.stoppingSessions.delete(id);
+ try {
+ // A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.
+ this.stoppingSessions.delete(id);
- // Execute hook before starting
- await this.hookManager.execute(
- 'session:starting',
- { sessionId: id },
- {
- sessionId: id,
- source: 'SessionService',
- },
- );
+ // Execute hook before starting
+ await this.hookManager.execute(
+ 'session:starting',
+ { sessionId: id },
+ {
+ sessionId: id,
+ source: 'SessionService',
+ },
+ );
- // Initialize reconnect state from the (untrusted) opaque session.config — coerced + clamped
- // so a poisoned value can't drive a NaN/immediate-relaunch storm or an unbounded loop (F-03).
- const { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);
- this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });
+ // Initialize reconnect state from the (untrusted) opaque session.config — coerced + clamped
+ // so a poisoned value can't drive a NaN/immediate-relaunch storm or an unbounded loop.
+ const { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);
+ this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });
- await this.initializeEngine(id, session);
- return this.findOne(id);
+ await this.initializeEngine(id, session);
+ return this.findOne(id);
+ } finally {
+ this.initializingSessions.delete(id);
+ }
}
private async initializeEngine(id: string, session: Session): Promise<void> {