Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(session): extract lifecycle fences and status broadcaster
Yudhi Armyndharis0b565e82e997
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 282d38274..8b23b78fc 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -1,7 +1,6 @@import {Injectable,NotFoundException,- ConflictException,BadRequestException,BadGatewayException,HttpException,@@ -41,6 +40,8 @@ import {import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';+import { SessionLifecycleFences } from './session-lifecycle-fences';+import { SessionStatusBroadcaster } from './session-status-broadcaster';// Message types that carry downloadable media. Any persisted row of these types must have a media// marker in metadata — never NULL — or the dashboard renders an empty bubble (no placeholder) and the@@ -148,13 +149,21 @@ export class SessionEngineLifecycle {return this.engineRegistry;}+ // Extracted units (plain classes constructed in the constructor below — the TestingModule-frozen+ // provider list means they can't be NestJS providers). The same-named delegates further down+ // keep every call site and spec poke byte-identical (the baileys forwarder precedent).+ private readonly fences: SessionLifecycleFences;+ private readonly broadcaster: SessionStatusBroadcaster;+// Reconnection state per sessionprivate reconnectStates: Map<string, ReconnectState> = new Map();- // Last session.status value broadcast per session. Some engines signal one transition via BOTH- // onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards both the WS emit- // and the webhook POST against firing the same status twice. Cleared on delete().- private readonly lastDispatchedStatus = new Map<string, SessionStatus>();+ // The status de-dup map is OWNED by the broadcaster (its updateStatus reads/writes it); this+ // getter aliases that exact instance BY REFERENCE (the liveCalls precedent) so the spec's+ // `lastDispatchedStatus.set(...)` / `.get(...)` pokes land on the same Map.+ private get lastDispatchedStatus(): Map<string, SessionStatus> {+ return this.broadcaster.lastDispatchedStatus;+ }// Sessions currently being stopped/deleted. An in-flight executeReconnect awaits// engine init, so a stop/delete during that window could re-register an engine AFTER@@ -229,7 +238,22 @@ export class SessionEngineLifecycle {// service degrades to today's behaviour if it is ever constructed without the (global) LoggerModule.@Optional()private readonly shutdownService?: ShutdownService,- ) {}+ ) {+ // The fence Maps are handed over BY REFERENCE: they stay lifecycle fields (specs poke them+ // through the lifecycle), while the fence logic operates on the same instances.+ this.fences = new SessionLifecycleFences({+ engines: this.engineRegistry,+ pendingTeardowns: this.pendingTeardowns,+ pendingInitialStatuses: this.pendingInitialStatuses,+ logger: this.logger,+ });+ this.broadcaster = new SessionStatusBroadcaster({+ sessionRepository: this.sessionRepository,+ eventsGateway: this.eventsGateway,+ webhookService: this.webhookService,+ logger: this.logger,+ });+ }/** findOne-or-404 with the last-error projection, mirroring SessionService.findOne. */private async requireSession(id: string): Promise<Session> {@@ -260,164 +284,49 @@ export class SessionEngineLifecycle {this.engines.clear();}- /** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted.- * Resolves to whether the destroy actually completed (see teardownEngineSafely). */- private async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<boolean> {- this.logger.log(`Destroying engine for session ${sessionId}`, { sessionId, action: 'shutdown' });- return this.teardownEngineSafely(sessionId, engine, e => e.destroy(), 'destroy');+ // --- Fence delegates (SessionLifecycleFences) ------------------------------------------------+ // Same-named, same-signature forwarders onto the extracted unit, so every existing call site+ // below — and the spec invoking `trackPendingCredentialTeardown` by name — stays byte-identical.+ // The method contracts (docblocks) moved to session-lifecycle-fences.ts with the bodies.+ // These forwarders are deliberately NON-async: they return the unit's own promise object+ // untouched, so callers observe the exact microtask settlement profile the inline methods had+ // (an `async` wrapper would adopt the inner promise and add settlement hops, which the+ // pre-initialize retirement-race specs assert against).++ /** Delegate: SessionLifecycleFences.destroyEngineSafely. */+ private destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<boolean> {+ return this.fences.destroyEngineSafely(sessionId, engine);}- /**- * Run an engine teardown (destroy/disconnect), isolating + time-bounding failures so a stuck- * Chromium/socket can neither hang nor abort the caller. Always resolves — the caller is then free- * to reconcile the engines Map and proceed with DB cleanup regardless of teardown outcome.- * Resolves to whether the teardown actually completed: `false` means it threw or hit the 10s- * deadline, so the underlying Chromium/socket may still be alive (a caller with an operator-facing- * outcome, like stopOrphanEngines, must surface that instead of reporting a clean stop).- *- * A teardown that loses the deadline race keeps running past the caller's return. For 'logout'- * that leftover promise ends in an fs.rm of the session's on-disk profile — the same path a- * later start() re-creates — so the raw promise is registered in pendingTeardowns (keyed by the- * session NAME, which is the auth-dir key) and start()/delete() wait (bounded, fail-closed) for- * it to settle before touching that path.- */- private async teardownEngineSafely(+ /** Delegate: SessionLifecycleFences.teardownEngineSafely. */+ private teardownEngineSafely(sessionId: string,engine: IWhatsAppEngine,teardown: (e: IWhatsAppEngine) => Promise<void>,label: 'destroy' | 'disconnect' | 'force-destroy' | 'logout',sessionName?: string,): Promise<boolean> {- const raw = teardown(engine);- if (label === 'logout' && sessionName) {- this.trackPendingCredentialTeardown(sessionName, raw);- }- let timer: ReturnType<typeof setTimeout> | undefined;- try {- await Promise.race([- raw,- new Promise<never>((_, reject) => {- timer = setTimeout(() => reject(new Error(`engine.${label}() timed out`)), 10_000);- }),- ]);- return true;- } catch (err) {- this.logger.error(`Failed to ${label} engine for session ${sessionId}`, String(err), {- sessionId,- action: `engine_${label}_failed`,- });- return false;- } finally {- if (timer) clearTimeout(timer);- }+ return this.fences.teardownEngineSafely(sessionId, engine, teardown, label, sessionName);}- /**- * Track a destructive credential-teardown promise under the session NAME (the on-disk auth-dir- * key — NOT the UUID). A logout's `engine.logout()` ends in an `fs.rm` of the same directory a- * later start() under the same name re-creates, so start()/delete()/executeReconnect consult this- * map and wait (bounded, fail-closed) before touching that path.- *- * Settlement marker only — never rejects, so it can't drive a caller's deadline race to a false- * "completed". A concurrent teardown for the same name CHAINS onto the previous entry instead of- * overwriting it (Promise.allSettled), so callers keep waiting until EVERY in-flight teardown for- * that name has settled — otherwise a second logout's fast settlement would drop the entry while- * the first teardown's profile rm is still pending. Identity-checked on removal is the ONLY path- * that evicts the entry, so a newer teardown's entry is never dropped by an older one settling.- */+ /** Delegate: SessionLifecycleFences.trackPendingCredentialTeardown. */private trackPendingCredentialTeardown(sessionName: string, raw: Promise<void>): void {- const tracked = raw.catch(() => undefined);- const previous = this.pendingTeardowns.get(sessionName);- const entry: Promise<void> = previous ? Promise.allSettled([previous, tracked]).then(() => undefined) : tracked;- this.pendingTeardowns.set(sessionName, entry);- void entry.finally(() => {- if (this.pendingTeardowns.get(sessionName) === entry) {- this.pendingTeardowns.delete(sessionName);- }- });+ this.fences.trackPendingCredentialTeardown(sessionName, raw);}- /**- * Wait (bounded) for a teardown that lost its deadline race to settle. A losing logout() promise- * ends in an fs.rm of the on-disk profile — the same deterministic path start() re-creates and- * delete() purges — so those paths call this before touching disk. The fence is FAIL CLOSED: a- * teardown still wedged past the bound could still land its rm on credentials a (re)created session- * under the same name would write, so the operation refuses with a retryable 409- * (SESSION_NAME_TEARDOWN_PENDING) instead of proceeding. The entry is NOT dropped on timeout — a- * retry after the rm eventually settles will see it gone and proceed.- *- * Keyed by the session NAME: the auth directories are built from `Session.name`, so two sessions- * sharing a name (a deleted UUID recreated under the same name) share the credential path and must- * share the fence.- */- private async awaitPendingTeardown(sessionName: string): Promise<void> {- const pending = this.pendingTeardowns.get(sessionName);- if (!pending) return;-- let timer: ReturnType<typeof setTimeout> | undefined;- const settled = await Promise.race([- pending.then(() => true),- new Promise<boolean>(resolve => {- timer = setTimeout(() => resolve(false), 10_000);- }),- ]);- if (timer) clearTimeout(timer);- if (!settled) {- // Fail closed: do NOT proceed. The stale rm could still hit a fresh profile under this name.- // Message is operator-facing and retryable, with no internal path leak.- throw new ConflictException({- statusCode: HttpStatus.CONFLICT,- message:- `A credential teardown for session '${sessionName}' is still in flight. Wait for it to ` +- 'settle and retry.',- error: 'Conflict',- code: 'SESSION_NAME_TEARDOWN_PENDING',- });- }+ /** Delegate: SessionLifecycleFences.awaitPendingTeardown. */+ private awaitPendingTeardown(sessionName: string): Promise<void> {+ return this.fences.awaitPendingTeardown(sessionName);}- /**- * Wait for the captured `engine`'s exact in-flight `updateStatus(INITIALIZING)` write to settle.- * Called by every retiring lifecycle control (stop/logout/delete/forceKill) AFTER the stop mark is- * set and reconnect cancelled, and BEFORE teardown / the final DISCONNECTED write / parent-row- * deletion. This keeps the control action the final persisted owner: a delayed INITIALIZING write- * always settles first, so it can never land after the DISCONNECTED write or the row removal.- *- * Identity-checked on the engine object: a control action that captured engine A awaits ONLY A's- * pending promise, never a replacement B's entry (and never deletes it). A bounded wait mirrors- * awaitPendingTeardown — the INITIALIZING write is a single DB update, but a wedged DB must not- * block retirement indefinitely.- */- private async awaitInitialStatus(id: string, engine: IWhatsAppEngine): Promise<void> {- const pending = this.pendingInitialStatuses.get(id);- if (!pending || pending.engine !== engine) return;-- let timer: ReturnType<typeof setTimeout> | undefined;- const settled = await Promise.race([- pending.promise.then(() => true),- new Promise<boolean>(resolve => {- timer = setTimeout(() => resolve(false), 10_000);- }),- ]);- if (timer) clearTimeout(timer);- if (!settled) {- this.logger.warn(`Proceeding to retire session ${id} while its INITIALIZING status write is still wedged`, {- sessionId: id,- action: 'pending_initial_status_wait_exhausted',- });- }+ /** Delegate: SessionLifecycleFences.awaitInitialStatus. */+ private awaitInitialStatus(id: string, engine: IWhatsAppEngine): Promise<void> {+ return this.fences.awaitInitialStatus(id, engine);}- /**- * Evict a terminally-failed or abandoned engine from the map and SIGKILL its browser process- * (best-effort, time-bounded via teardownEngineSafely). An engine left in the map keeps holding a- * concurrency slot and makes a later start() see the session as "already started"; forceDestroy()- * (not the graceful destroy()) is used because such an engine's browser/CDP connection is typically- * already broken, so a graceful close would only time out before the process is reaped.- */+ /** Delegate: SessionLifecycleFences.evictAndForceDestroy. */private evictAndForceDestroy(id: string, engine: IWhatsAppEngine): void {- this.engines.delete(id);- void this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');+ this.fences.evictAndForceDestroy(id, engine);}async delete(id: string): Promise<void> {@@ -531,7 +440,7 @@ export class SessionEngineLifecycle {// state (those are gated on parentDeleted below).this.stoppingSessions.delete(id);if (parentDeleted) {- this.lastDispatchedStatus.delete(id);+ this.broadcaster.clear(id);// Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read// again, so leaving it would grow the map without bound across create/fail/delete churn.this.sessionErrors.clear(id);@@ -1639,21 +1548,12 @@ export class SessionEngineLifecycle {return this.requireSession(id);}- async updateStatus(id: string, status: SessionStatus): Promise<void> {- await this.sessionRepository.update(id, { status });- this.logger.debug(`Session status updated to ${status}`, {- sessionId: id,- status,- action: 'status_update',- });- // Mirror the status change to WS clients AND subscribed webhooks — both de-duped. Some engines signal- // one transition via both onStateChanged AND a dedicated callback (onQRCode/onDisconnected), which- // would otherwise emit/POST the same status twice; only act when it actually changed from the last one.- if (this.lastDispatchedStatus.get(id) !== status) {- this.lastDispatchedStatus.set(id, status);- this.eventsGateway.emitSessionStatus(id, status);- void this.webhookService.dispatch(id, 'session.status', { sessionId: id, status });- }+ // Public delegate: SessionStatusBroadcaster.updateStatus (persist + de-duped WS/webhook fan-out).+ // Deliberately NON-async: callers (initializeEngine's pending-initial-status fence above all)+ // must await the broadcaster's own promise object, keeping the exact settlement profile the+ // inline method had — an async wrapper would add adoption hops the retirement-race specs catch.+ updateStatus(id: string, status: SessionStatus): Promise<void> {+ return this.broadcaster.updateStatus(id, status);}/**diff --git a/src/modules/session/session-lifecycle-fences.ts b/src/modules/session/session-lifecycle-fences.tsnew file mode 100644index 000000000..7f8ad07ae--- /dev/null+++ b/src/modules/session/session-lifecycle-fences.ts@@ -0,0 +1,195 @@+import { ConflictException, HttpStatus } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { type createLogger } from '../../common/services/logger.service';++/**+ * The credential-teardown / initial-status fences extracted from SessionEngineLifecycle. Plain+ * class (NOT a NestJS provider — the lifecycle's constructor signature is frozen by specs), built+ * inside the lifecycle's constructor. The two fence Maps stay lifecycle FIELDS handed over by+ * reference, so this unit and the lifecycle (and every spec poking the maps through the lifecycle)+ * always observe the same instances; method bodies below moved verbatim, which is why they read+ * `this.pendingTeardowns` / `this.pendingInitialStatuses` / `this.engines` / `this.logger` against+ * the same-named fields assigned here. The lifecycle keeps same-named delegates for all six+ * methods (the baileys forwarder precedent), so every existing call site and spec poke+ * (`trackPendingCredentialTeardown` is invoked by name in logout-teardown-race.spec) stays+ * byte-identical.+ */+export class SessionLifecycleFences {+ private readonly engines: EngineRegistry;+ private readonly pendingTeardowns: Map<string, Promise<void>>;+ private readonly pendingInitialStatuses: Map<string, { engine: IWhatsAppEngine; promise: Promise<void> }>;+ private readonly logger: ReturnType<typeof createLogger>;++ constructor(deps: {+ engines: EngineRegistry;+ pendingTeardowns: Map<string, Promise<void>>;+ pendingInitialStatuses: Map<string, { engine: IWhatsAppEngine; promise: Promise<void> }>;+ logger: ReturnType<typeof createLogger>;+ }) {+ this.engines = deps.engines;+ this.pendingTeardowns = deps.pendingTeardowns;+ this.pendingInitialStatuses = deps.pendingInitialStatuses;+ this.logger = deps.logger;+ }++ /** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted.+ * Resolves to whether the destroy actually completed (see teardownEngineSafely). */+ async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<boolean> {+ this.logger.log(`Destroying engine for session ${sessionId}`, { sessionId, action: 'shutdown' });+ return this.teardownEngineSafely(sessionId, engine, e => e.destroy(), 'destroy');+ }++ /**+ * Run an engine teardown (destroy/disconnect), isolating + time-bounding failures so a stuck+ * Chromium/socket can neither hang nor abort the caller. Always resolves — the caller is then free+ * to reconcile the engines Map and proceed with DB cleanup regardless of teardown outcome.+ * Resolves to whether the teardown actually completed: `false` means it threw or hit the 10s+ * deadline, so the underlying Chromium/socket may still be alive (a caller with an operator-facing+ * outcome, like stopOrphanEngines, must surface that instead of reporting a clean stop).+ *+ * A teardown that loses the deadline race keeps running past the caller's return. For 'logout'+ * that leftover promise ends in an fs.rm of the session's on-disk profile — the same path a+ * later start() re-creates — so the raw promise is registered in pendingTeardowns (keyed by the+ * session NAME, which is the auth-dir key) and start()/delete() wait (bounded, fail-closed) for+ * it to settle before touching that path.+ */+ async teardownEngineSafely(+ sessionId: string,+ engine: IWhatsAppEngine,+ teardown: (e: IWhatsAppEngine) => Promise<void>,+ label: 'destroy' | 'disconnect' | 'force-destroy' | 'logout',+ sessionName?: string,+ ): Promise<boolean> {+ const raw = teardown(engine);+ if (label === 'logout' && sessionName) {+ this.trackPendingCredentialTeardown(sessionName, raw);+ }+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ raw,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(`engine.${label}() timed out`)), 10_000);+ }),+ ]);+ return true;+ } catch (err) {+ this.logger.error(`Failed to ${label} engine for session ${sessionId}`, String(err), {+ sessionId,+ action: `engine_${label}_failed`,+ });+ return false;+ } finally {+ if (timer) clearTimeout(timer);+ }+ }++ /**+ * Track a destructive credential-teardown promise under the session NAME (the on-disk auth-dir+ * key — NOT the UUID). A logout's `engine.logout()` ends in an `fs.rm` of the same directory a+ * later start() under the same name re-creates, so start()/delete()/executeReconnect consult this+ * map and wait (bounded, fail-closed) before touching that path.+ *+ * Settlement marker only — never rejects, so it can't drive a caller's deadline race to a false+ * "completed". A concurrent teardown for the same name CHAINS onto the previous entry instead of+ * overwriting it (Promise.allSettled), so callers keep waiting until EVERY in-flight teardown for+ * that name has settled — otherwise a second logout's fast settlement would drop the entry while+ * the first teardown's profile rm is still pending. Identity-checked on removal is the ONLY path+ * that evicts the entry, so a newer teardown's entry is never dropped by an older one settling.+ */+ trackPendingCredentialTeardown(sessionName: string, raw: Promise<void>): void {+ const tracked = raw.catch(() => undefined);+ const previous = this.pendingTeardowns.get(sessionName);+ const entry: Promise<void> = previous ? Promise.allSettled([previous, tracked]).then(() => undefined) : tracked;+ this.pendingTeardowns.set(sessionName, entry);+ void entry.finally(() => {+ if (this.pendingTeardowns.get(sessionName) === entry) {+ this.pendingTeardowns.delete(sessionName);+ }+ });+ }++ /**+ * Wait (bounded) for a teardown that lost its deadline race to settle. A losing logout() promise+ * ends in an fs.rm of the on-disk profile — the same deterministic path start() re-creates and+ * delete() purges — so those paths call this before touching disk. The fence is FAIL CLOSED: a+ * teardown still wedged past the bound could still land its rm on credentials a (re)created session+ * under the same name would write, so the operation refuses with a retryable 409+ * (SESSION_NAME_TEARDOWN_PENDING) instead of proceeding. The entry is NOT dropped on timeout — a+ * retry after the rm eventually settles will see it gone and proceed.+ *+ * Keyed by the session NAME: the auth directories are built from `Session.name`, so two sessions+ * sharing a name (a deleted UUID recreated under the same name) share the credential path and must+ * share the fence.+ */+ async awaitPendingTeardown(sessionName: string): Promise<void> {+ const pending = this.pendingTeardowns.get(sessionName);+ if (!pending) return;++ let timer: ReturnType<typeof setTimeout> | undefined;+ const settled = await Promise.race([+ pending.then(() => true),+ new Promise<boolean>(resolve => {+ timer = setTimeout(() => resolve(false), 10_000);+ }),+ ]);+ if (timer) clearTimeout(timer);+ if (!settled) {+ // Fail closed: do NOT proceed. The stale rm could still hit a fresh profile under this name.+ // Message is operator-facing and retryable, with no internal path leak.+ throw new ConflictException({+ statusCode: HttpStatus.CONFLICT,+ message:+ `A credential teardown for session '${sessionName}' is still in flight. Wait for it to ` ++ 'settle and retry.',+ error: 'Conflict',+ code: 'SESSION_NAME_TEARDOWN_PENDING',+ });+ }+ }++ /**+ * Wait for the captured `engine`'s exact in-flight `updateStatus(INITIALIZING)` write to settle.+ * Called by every retiring lifecycle control (stop/logout/delete/forceKill) AFTER the stop mark is+ * set and reconnect cancelled, and BEFORE teardown / the final DISCONNECTED write / parent-row+ * deletion. This keeps the control action the final persisted owner: a delayed INITIALIZING write+ * always settles first, so it can never land after the DISCONNECTED write or the row removal.+ *+ * Identity-checked on the engine object: a control action that captured engine A awaits ONLY A's+ * pending promise, never a replacement B's entry (and never deletes it). A bounded wait mirrors+ * awaitPendingTeardown — the INITIALIZING write is a single DB update, but a wedged DB must not+ * block retirement indefinitely.+ */+ async awaitInitialStatus(id: string, engine: IWhatsAppEngine): Promise<void> {+ const pending = this.pendingInitialStatuses.get(id);+ if (!pending || pending.engine !== engine) return;++ let timer: ReturnType<typeof setTimeout> | undefined;+ const settled = await Promise.race([+ pending.promise.then(() => true),+ new Promise<boolean>(resolve => {+ timer = setTimeout(() => resolve(false), 10_000);+ }),+ ]);+ if (timer) clearTimeout(timer);+ if (!settled) {+ this.logger.warn(`Proceeding to retire session ${id} while its INITIALIZING status write is still wedged`, {+ sessionId: id,+ action: 'pending_initial_status_wait_exhausted',+ });+ }+ }++ /**+ * Evict a terminally-failed or abandoned engine from the map and SIGKILL its browser process+ * (best-effort, time-bounded via teardownEngineSafely). An engine left in the map keeps holding a+ * concurrency slot and makes a later start() see the session as "already started"; forceDestroy()+ * (not the graceful destroy()) is used because such an engine's browser/CDP connection is typically+ * already broken, so a graceful close would only time out before the process is reaped.+ */+ evictAndForceDestroy(id: string, engine: IWhatsAppEngine): void {+ this.engines.delete(id);+ void this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');+ }+}diff --git a/src/modules/session/session-status-broadcaster.ts b/src/modules/session/session-status-broadcaster.tsnew file mode 100644index 000000000..d9604cda7--- /dev/null+++ b/src/modules/session/session-status-broadcaster.ts@@ -0,0 +1,62 @@+import { Repository } from 'typeorm';+import { Session, SessionStatus } from './entities/session.entity';+import { EventsGateway } from '../events/events.gateway';+import { WebhookService } from '../webhook/webhook.service';+import { type createLogger } from '../../common/services/logger.service';++/**+ * The session-status fan-out extracted from SessionEngineLifecycle: persist the status, then+ * mirror it to WS clients and subscribed webhooks, de-duped. Plain class (NOT a NestJS provider —+ * the lifecycle's constructor signature is frozen by specs), built inside the lifecycle's+ * constructor. The de-dup Map is OWNED here; the lifecycle exposes a `lastDispatchedStatus`+ * getter alias returning it by reference (the liveCalls precedent) so the spec's `.set()` pokes+ * land on this exact instance, and keeps `updateStatus` as a public delegate so its 9 call sites+ * stay byte-identical. The method body below moved verbatim, which is why it reads+ * `this.sessionRepository` / `this.eventsGateway` / `this.webhookService` / `this.logger` against+ * the same-named fields assigned here.+ */+export class SessionStatusBroadcaster {+ // Last session.status value broadcast per session. Some engines signal one transition via BOTH+ // onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards both the WS emit+ // and the webhook POST against firing the same status twice. Cleared on delete().+ readonly lastDispatchedStatus = new Map<string, SessionStatus>();++ private readonly sessionRepository: Repository<Session>;+ private readonly eventsGateway: EventsGateway;+ private readonly webhookService: WebhookService;+ private readonly logger: ReturnType<typeof createLogger>;++ constructor(deps: {+ sessionRepository: Repository<Session>;+ eventsGateway: EventsGateway;+ webhookService: WebhookService;+ logger: ReturnType<typeof createLogger>;+ }) {+ this.sessionRepository = deps.sessionRepository;+ this.eventsGateway = deps.eventsGateway;+ this.webhookService = deps.webhookService;+ this.logger = deps.logger;+ }++ async updateStatus(id: string, status: SessionStatus): Promise<void> {+ await this.sessionRepository.update(id, { status });+ this.logger.debug(`Session status updated to ${status}`, {+ sessionId: id,+ status,+ action: 'status_update',+ });+ // Mirror the status change to WS clients AND subscribed webhooks — both de-duped. Some engines signal+ // one transition via both onStateChanged AND a dedicated callback (onQRCode/onDisconnected), which+ // would otherwise emit/POST the same status twice; only act when it actually changed from the last one.+ if (this.lastDispatchedStatus.get(id) !== status) {+ this.lastDispatchedStatus.set(id, status);+ this.eventsGateway.emitSessionStatus(id, status);+ void this.webhookService.dispatch(id, 'session.status', { sessionId: id, status });+ }+ }++ /** Drop the de-dup entry for a session — called from delete()'s committed-delete cleanup. */+ clear(id: string): void {+ this.lastDispatchedStatus.delete(id);+ }+}