Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(engine): extract EngineRegistry as the live-engine port
Yudhi Armyndharis1144aea39133
diff --git a/src/engine/engine-registry.service.spec.ts b/src/engine/engine-registry.service.spec.tsnew file mode 100644index 000000000..9be6efc75--- /dev/null+++ b/src/engine/engine-registry.service.spec.ts@@ -0,0 +1,166 @@+import { BadRequestException, NotFoundException } from '@nestjs/common';+import { EngineRegistry } from './engine-registry.service';+import type { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';++const engineStub = (tag: string): IWhatsAppEngine => ({ tag }) as unknown as IWhatsAppEngine;++describe('EngineRegistry', () => {+ let registry: EngineRegistry;++ beforeEach(() => {+ registry = new EngineRegistry();+ });++ describe('registration', () => {+ it('stores and returns the engine registered for a session', () => {+ const engine = engineStub('a');+ registry.set('s1', engine);++ expect(registry.get('s1')).toBe(engine);+ expect(registry.has('s1')).toBe(true);+ expect(registry.size).toBe(1);+ });++ it('reports an unregistered session as absent', () => {+ expect(registry.get('missing')).toBeUndefined();+ expect(registry.has('missing')).toBe(false);+ });++ it('replaces the engine on re-registration (reconnect installs a new generation)', () => {+ const first = engineStub('first');+ const second = engineStub('second');+ registry.set('s1', first);+ registry.set('s1', second);++ expect(registry.get('s1')).toBe(second);+ expect(registry.size).toBe(1);+ });++ it('clear() drops every engine', () => {+ registry.set('s1', engineStub('a'));+ registry.set('s2', engineStub('b'));++ registry.clear();++ expect(registry.size).toBe(0);+ expect(registry.entries()).toEqual([]);+ });++ it('entries() snapshots the map so callers can tear down while it mutates', () => {+ const a = engineStub('a');+ registry.set('s1', a);++ const snapshot = registry.entries();+ registry.delete('s1');++ expect(snapshot).toEqual([['s1', a]]);+ expect(registry.size).toBe(0);+ });+ });++ describe('liveness by identity', () => {+ it('isLive() is true only for the currently registered instance', () => {+ const engine = engineStub('a');+ registry.set('s1', engine);++ expect(registry.isLive('s1', engine)).toBe(true);+ });++ it('isLive() is false for a superseded generation (reconnect replaced it)', () => {+ const stale = engineStub('stale');+ const fresh = engineStub('fresh');+ registry.set('s1', stale);+ registry.set('s1', fresh);++ expect(registry.isLive('s1', stale)).toBe(false);+ expect(registry.isLive('s1', fresh)).toBe(true);+ });++ it('isLive() is false after the session is stopped', () => {+ const engine = engineStub('a');+ registry.set('s1', engine);+ registry.delete('s1');++ expect(registry.isLive('s1', engine)).toBe(false);+ });++ it('deleteIfLive() reconciles the map for the live engine', () => {+ const engine = engineStub('a');+ registry.set('s1', engine);++ expect(registry.deleteIfLive('s1', engine)).toBe(true);+ expect(registry.has('s1')).toBe(false);+ });++ it('deleteIfLive() refuses to evict a live replacement on behalf of a stale engine', () => {+ const stale = engineStub('stale');+ const fresh = engineStub('fresh');+ registry.set('s1', stale);+ registry.set('s1', fresh);++ expect(registry.deleteIfLive('s1', stale)).toBe(false);+ expect(registry.get('s1')).toBe(fresh);+ });+ });++ describe('require()', () => {+ it('returns the engine when the session is started', () => {+ const engine = engineStub('a');+ registry.set('s1', engine);++ expect(registry.require('s1')).toBe(engine);+ });++ it('throws a 400 "not started" by default', () => {+ expect(() => registry.require('s1')).toThrow(BadRequestException);+ expect(() => registry.require('s1')).toThrow('Session is not started');+ });++ it('throws the caller-supplied error so each API keeps its documented status', () => {+ expect(() => registry.require('s1', () => new NotFoundException('Session s1 not found or not connected'))).toThrow(+ NotFoundException,+ );+ });++ it('does not build the error when the engine is present', () => {+ const onMissing = jest.fn(() => new BadRequestException('nope'));+ registry.set('s1', engineStub('a'));++ registry.require('s1', onMissing);++ expect(onMissing).not.toHaveBeenCalled();+ });+ });++ describe('initialization reservations', () => {+ it('counts a reserved-but-unregistered session as active', () => {+ registry.initializing.add('s1');++ expect(registry.activeIds()).toEqual(['s1']);+ // Not yet a live engine: only the reservation exists.+ expect(registry.has('s1')).toBe(false);+ expect(registry.size).toBe(0);+ });++ it('does not double-count a session that is both reserved and registered', () => {+ registry.initializing.add('s1');+ registry.set('s1', engineStub('a'));++ expect(registry.activeIds()).toEqual(['s1']);+ });++ it('releases the reservation', () => {+ registry.initializing.add('s1');+ registry.initializing.delete('s1');++ expect(registry.activeIds()).toEqual([]);+ });++ it('reports registered and initializing sessions together', () => {+ registry.set('running', engineStub('a'));+ registry.initializing.add('starting');++ expect(registry.activeIds().sort()).toEqual(['running', 'starting']);+ });+ });+});diff --git a/src/engine/engine-registry.service.ts b/src/engine/engine-registry.service.tsnew file mode 100644index 000000000..071f295b8--- /dev/null+++ b/src/engine/engine-registry.service.ts@@ -0,0 +1,128 @@+import { BadRequestException, Injectable } from '@nestjs/common';+import type { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';++/**+ * The single source of truth for which engine instance is live for a session.+ *+ * This is the narrow port between session *lifecycle* (SessionService, which creates, retires and+ * reconnects engines) and the ~10 feature services that only ever need "give me the running engine+ * for this session". Those consumers previously injected the whole SessionService — a 2.9k-line+ * lifecycle owner — purely to reach its private `engines` map, which coupled every feature module to+ * start/stop/delete/reconnect semantics they never call.+ *+ * Identity, not just presence, is the invariant that matters. Each engine callback captures its own+ * engine instance; once a session is stopped (engine removed) or restarted/reconnected (engine+ * replaced), a late callback from the superseded engine must not mutate the session that now belongs+ * to a different — or no — engine. `isLive`/`deleteIfLive` exist so that check is written once here+ * rather than re-derived at each of its ~20 call sites.+ */+@Injectable()+export class EngineRegistry {+ /** Live engines by session (DB) id. Presence here means "started"; identity means "not superseded". */+ private readonly engines = new Map<string, IWhatsAppEngine>();++ /**+ * Sessions whose engine is being constructed but is not in `engines` yet. Held so concurrency+ * accounting and the infra import pre-flight can see a session that is starting but not yet+ * registered, which would otherwise look idle and be orphaned or double-started.+ *+ * Exposed directly (rather than behind add/remove wrappers) because the lifecycle owner needs the+ * full Set surface — including `clear()` — and this is a reservation ledger, not an invariant that+ * benefits from being funnelled through methods the way engine identity is.+ */+ readonly initializing = new Set<string>();++ // ── Map-compatible surface (used by the lifecycle owner) ──────────────++ get(id: string): IWhatsAppEngine | undefined {+ return this.engines.get(id);+ }++ set(id: string, engine: IWhatsAppEngine): void {+ this.engines.set(id, engine);+ }++ has(id: string): boolean {+ return this.engines.has(id);+ }++ delete(id: string): boolean {+ return this.engines.delete(id);+ }++ clear(): void {+ this.engines.clear();+ }++ get size(): number {+ return this.engines.size;+ }++ keys(): IterableIterator<string> {+ return this.engines.keys();+ }++ entries(): Array<[string, IWhatsAppEngine]> {+ return [...this.engines];+ }++ /**+ * Iterates a *snapshot* of the live entries. Every caller here tears engines down while iterating,+ * which would otherwise mutate the map mid-iteration.+ */+ [Symbol.iterator](): IterableIterator<[string, IWhatsAppEngine]> {+ return this.entries()[Symbol.iterator]();+ }++ // ── Liveness (identity) ───────────────────────────────────────────────++ /**+ * True only while `engine` is still the live engine registered for `id`. Identity comparison closes+ * both the post-stop and the stale-generation (stop→start / reconnect-replace) windows that a bare+ * presence check does not cover.+ */+ isLive(id: string, engine: IWhatsAppEngine): boolean {+ return this.engines.get(id) === engine;+ }++ /**+ * Reconcile the map only if `engine` is still the registered one. Guards against a teardown of a+ * superseded engine evicting its live replacement — the single most repeated invariant in the+ * lifecycle paths.+ */+ deleteIfLive(id: string, engine: IWhatsAppEngine): boolean {+ if (!this.isLive(id, engine)) {+ return false;+ }+ return this.engines.delete(id);+ }++ // ── Consumer-facing accessor ──────────────────────────────────────────++ /**+ * The running engine for `id`, or throw. Callers pass their own error so each API surface keeps the+ * exact status/message it already documented (some report 400 "not started", others 404 "not+ * connected"); the default matches the most common existing guard.+ */+ require(+ id: string,+ onMissing: () => Error = () => new BadRequestException('Session is not started'),+ ): IWhatsAppEngine {+ const engine = this.engines.get(id);+ if (!engine) {+ throw onMissing();+ }+ return engine;+ }++ // ── Initialization reservations ───────────────────────────────────────++ /**+ * Ids of every session with a live engine — including ones mid-initialization (their engine is not+ * in `engines` yet but will register when start() completes). The infra import pre-flight uses this+ * to refuse a full-replace restore that would orphan a running engine.+ */+ activeIds(): string[] {+ return [...new Set([...this.engines.keys(), ...this.initializing])];+ }+}diff --git a/src/engine/engine.module.ts b/src/engine/engine.module.tsindex a20aaedbd..57bd674c7 100644--- a/src/engine/engine.module.ts+++ b/src/engine/engine.module.ts@@ -5,11 +5,15 @@ import { BaileysStoredMessage } from './adapters/baileys-stored-message.entity';import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';import { LidMapping } from './identity/lid-mapping.entity';import { LidMappingStoreService } from './identity/lid-mapping-store.service';+import { EngineRegistry } from './engine-registry.service';@Global()@Module({imports: [TypeOrmModule.forFeature([BaileysStoredMessage, LidMapping], 'data')],- providers: [EngineFactory, BaileysMessageStoreService, LidMappingStoreService],- exports: [EngineFactory, LidMappingStoreService],+ // EngineRegistry is exported from this @Global module so the feature services that only need a+ // live engine can inject it directly, instead of importing SessionModule to reach the lifecycle+ // owner. It is a singleton by DI, which is what makes it a safe single source of truth.+ providers: [EngineFactory, BaileysMessageStoreService, LidMappingStoreService, EngineRegistry],+ exports: [EngineFactory, LidMappingStoreService, EngineRegistry],})export class EngineModule {}diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex a712b803d..0efc13704 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -7,6 +7,7 @@ import { SessionService } from './session.service';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { EngineFactory } from '../../engine/engine.factory';+import { EngineRegistry } from '../../engine/engine-registry.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';@@ -89,6 +90,8 @@ describe('SessionService logout() name-scoped teardown fence', () => {{ provide: getRepositoryToken(Message, 'data'), useValue: messageRepository },{ provide: getDataSourceToken('data'), useValue: dataSource },{ provide: EngineFactory, useValue: engineFactory },+ // Real registry: this suite asserts on engine map state across the teardown fence.+ EngineRegistry,{provide: EventsGateway,useValue: { emitSessionStatus: jest.fn(), emitSessionDisconnected: jest.fn(), emitQRCode: jest.fn() },diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex c2b61bbdd..001e92698 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -24,6 +24,7 @@ import { Webhook } from '../webhook/entities/webhook.entity';import { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { EngineFactory } from '../../engine/engine.factory';+import { EngineRegistry } from '../../engine/engine-registry.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';@@ -197,6 +198,10 @@ describe('SessionService', () => {useValue: dataSource,},{ provide: EngineFactory, useValue: engineFactory },+ // Real EngineRegistry, not a mock: it is the live-engine source of truth this service reads+ // and writes on every lifecycle path, and the identity semantics (isLive/deleteIfLive) are+ // exactly what the stale-callback tests below exercise. Its own unit tests cover it directly.+ EngineRegistry,{ provide: EventsGateway, useValue: eventsGateway },{ provide: WebhookService, useValue: webhookService },{ provide: HookManager, useValue: hookManager },diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 8df4b912c..14938abcc 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -23,6 +23,7 @@ import { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { CreateSessionDto } from './dto';import { EngineFactory } from '../../engine/engine.factory';+import { EngineRegistry } from '../../engine/engine-registry.service';import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { userPart } from '../../engine/identity/wa-id';@@ -189,8 +190,12 @@ function isAuthTimeoutRejection(err: unknown): boolean {export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicationBootstrap {private readonly logger = createLogger('SessionService');- // In-memory map of active engine instances- private engines: Map<string, IWhatsAppEngine> = new Map();+ // Live engine instances, owned by the shared EngineRegistry (the narrow port feature modules+ // inject instead of this whole service). This service is the only writer: it creates, replaces and+ // retires engines. `engines` remains a local alias so the lifecycle code below reads unchanged.+ private get engines(): EngineRegistry {+ return this.engineRegistry;+ }// Bounded cache for inline @lid -> phone resolution (#263), keyed `${sessionId}:${lid}`. Caches// misses (null) too, so a chatty unmapped sender isn't re-queried on every message (which also// reduces engine rate-limit pressure). Best-effort feature, so staleness is acceptable.@@ -225,8 +230,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// 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();+ // awaited hook and orphan an engine the lifecycle could never destroy. Backed by the registry so+ // the infra import pre-flight sees starting sessions through the same port.+ private get initializingSessions(): Set<string> {+ return this.engineRegistry.initializing;+ }// Serializes stored-message mutations per `${sessionId}:${waMessageId}`. Reactions perform a// read-modify-write and rapid edits must remain latest-write-wins; sharing one chain also preserves@@ -277,6 +285,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat@InjectDataSource('data')private readonly dataSource: DataSource,private readonly engineFactory: EngineFactory,+ private readonly engineRegistry: EngineRegistry,private readonly eventsGateway: EventsGateway,private readonly webhookService: WebhookService,private readonly hookManager: HookManager,@@ -669,7 +678,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// is gone (delete cannot be followed by a late status write). Identity-checked.await this.awaitInitialStatus(id, engine);await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);}// FENCE #2 — immediately after the current engine is evicted, BEFORE the session:deleted hook@@ -788,7 +797,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// start()'s finally), so summing the two sizes would double-count it; and `id` itself is// already reserved in `initializingSessions` (added at entry), so it must not count// against the cap it is being checked against.- const activeIds = new Set<string>([...this.engines.keys(), ...this.initializingSessions]);+ const activeIds = new Set<string>(this.engines.activeIds());activeIds.delete(id);if (activeIds.size >= maxConcurrentSessions) {throw new BadRequestException(`Maximum concurrent sessions reached (${maxConcurrentSessions})`);@@ -872,7 +881,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');- if (this.isLiveEngine(id, resurrected)) this.engines.delete(id);+ this.engines.deleteIfLive(id, resurrected);}// A delete() that raced this start purged the on-disk auth dirs BEFORE this init re-created// them — purge again so the window leaves no credential residue behind (no-op for a stop()).@@ -888,13 +897,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* True only while `engine` is still the live engine registered for `id`. Each callback below* captures its own engine instance; once the session is stopped (engine removed from the map) or* restarted/reconnected (engine replaced), a late callback from the superseded engine must not- * mutate the session that now belongs to a different — or no — engine. `this.engines` is the+ * mutate the session that now belongs to a different — or no — engine. The registry is the* single source of truth for the active engine, so identity comparison closes both the* post-stop and the stale-generation (stop→start / reconnect-replace) windows the one-shot* post-init guard does not cover.*/private isLiveEngine(id: string, engine: IWhatsAppEngine): boolean {- return this.engines.get(id) === engine;+ return this.engines.isLive(id, engine);}/**@@ -2417,7 +2426,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst oldEngine = this.engines.get(id);if (oldEngine) {await this.teardownEngineSafely(id, oldEngine, e => e.destroy(), 'destroy');- if (this.isLiveEngine(id, oldEngine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, oldEngine);}// Credential-teardown fence — BEFORE engineFactory.create (inside initializeEngine). A logout@@ -2448,7 +2457,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');- if (this.isLiveEngine(id, resurrected)) this.engines.delete(id);+ this.engines.deleteIfLive(id, resurrected);}// Same start/delete window as start()'s post-init guard: this re-init re-created auth dirs// delete() had already purged — purge again so no credentials outlive the row.@@ -2501,7 +2510,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// become the last persisted status. Identity-checked: only the captured engine's promise.await this.awaitInitialStatus(id, engine);await this.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);}this.logger.log(`Session stopped: ${session.name}`, {@@ -2565,7 +2574,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// raw logout that outlives its deadline race is tracked under the right name even if the row is// later deleted/recreated.const unlinked = await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout', session.name);- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);await this.updateStatus(id, SessionStatus.DISCONNECTED);if (!unlinked) {@@ -2629,7 +2638,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// write so a delayed pre-initialize status update can never settle after the retirement.await this.awaitInitialStatus(id, engine);await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);this.logger.warn(`Session force-killed: ${session.name}`, {sessionId: id,@@ -2886,7 +2895,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* to refuse a full-replace restore that would orphan a running engine.*/getActiveSessionIds(): string[] {- return [...new Set([...this.engines.keys(), ...this.initializingSessions])];+ return this.engines.activeIds();}/**@@ -2934,7 +2943,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// means the Chromium/socket may still be alive and writing, so the id lands in `failed`// and the caller (the infra import) can flag restartRequired instead of reporting a// clean stop for a wedged engine.- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);if (tornDown) {stopped.push(id);} else {@@ -2947,7 +2956,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: id,action: 'stop_orphan_failed',});- if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ this.engines.deleteIfLive(id, engine);failed.push(id);}}),