Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): report engineLoaded for a session a live peer runs
Yudhi Armyndharisf8d3eb816f96
diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 397e6127c..3029887f9 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -93,7 +93,8 @@ export class SessionResponseDto {'session keeps its engine for the duration of an automatic reconnect backoff, while a session ' +'stopped through `POST /sessions/:sessionId/stop` carries the same status with no engine. When `true`, ' +'`stop`, `logout` and `force-kill` can act and `start` answers 400; when `false`, the reverse. ' +- 'Derived per request from live process state, so it is never persisted and never historical.',+ 'Derived per request from live state, so it is never persisted and never historical: an engine in ' ++ 'the answering process or, in a multi-node deployment, a live claim by the node running the session.',example: true,})engineLoaded!: boolean;@@ -103,7 +104,7 @@ export class SessionResponseDto {* engine config fields (`config`, `proxyUrl`, `proxyType`) that must not* appear in any API response.*- * `engineLoaded` is not on the entity — it is live process state owned by the session service, so+ * `engineLoaded` is not on the entity — it is live state owned by the session service, so* every caller must pass it in rather than letting it default. A required parameter is deliberate:* a default of `false` would silently tell clients "no engine" for whole surfaces (the MCP tools,* any future caller) and the dashboard would then offer Start to a running session.diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.tsindex 278346a93..fe236eac6 100644--- a/src/modules/session/session-ownership.service.spec.ts+++ b/src/modules/session/session-ownership.service.spec.ts@@ -478,6 +478,20 @@ describe('SessionOwnershipService', () => {await expect(nodeA.isHeldByOtherNode(mine.id)).resolves.toBe(false);await expect(nodeA.isHeldByOtherNode(free.id)).resolves.toBe(false);});++ it('answers the same for a row already loaded, without a query', async () => {+ const live = await seed({ nodeId: 'peer', leaseExpiresAt: new Date(Date.now() + 60_000) });+ const lapsed = await seed({ nodeId: 'peer', leaseExpiresAt: new Date(Date.now() - 1000) });+ const mine = await seed({ nodeId: 'node-a', leaseExpiresAt: new Date(Date.now() + 60_000) });+ const free = await seed();+ const nodeA = service('node-a');+ const loaded = (id: string): Promise<Session> => sessions.findOneByOrFail({ id });++ expect(nodeA.heldByOtherLiveNode(await loaded(live.id))).toBe(true);+ expect(nodeA.heldByOtherLiveNode(await loaded(lapsed.id))).toBe(false);+ expect(nodeA.heldByOtherLiveNode(await loaded(mine.id))).toBe(false);+ expect(nodeA.heldByOtherLiveNode(await loaded(free.id))).toBe(false);+ });});describe('sessions held elsewhere', () => {diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex c190c9ad8..1b10619d8 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -343,6 +343,16 @@ export class SessionOwnershipService {return count > 0;}+ /** {@link isHeldByOtherNode} for a row already loaded, so a list can answer it without a query per row. */+ heldByOtherLiveNode(session: Pick<Session, 'nodeId' | 'leaseExpiresAt'>, now = new Date()): boolean {+ return (+ session.nodeId != null &&+ session.nodeId !== this.nodeId &&+ session.leaseExpiresAt != null &&+ session.leaseExpiresAt > now+ );+ }+async heldByOtherNodes(now = new Date()): Promise<string[]> {const rows = await this.sessions.createQueryBuilder('session')diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 856d6c42c..2ef5f2068 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -34,14 +34,17 @@ describe('SessionController — create() response contract', () => {updatedAt: new Date('2026-01-01T00:00:00Z'),};- let sessionService: { create: jest.Mock; isActive: jest.Mock };+ let sessionService: { create: jest.Mock; engineLoaded: jest.Mock };let auditService: { logInfo: jest.Mock };let controller: SessionController;beforeEach(() => {// transformSession reads live engine state for `engineLoaded`; a freshly created session has no// engine yet, which is what the response must say.- sessionService = { create: jest.fn().mockResolvedValue({ ...entity }), isActive: jest.fn().mockReturnValue(false) };+ sessionService = {+ create: jest.fn().mockResolvedValue({ ...entity }),+ engineLoaded: jest.fn().mockReturnValue(false),+ };auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };controller = new SessionControllerClass(sessionService as unknown as SessionService,@@ -77,15 +80,15 @@ describe('SessionController — create() response contract', () => {});});- // engineLoaded is live process state, not an entity column, so the only thing that can get it wrong+ // engineLoaded is live state, not an entity column, so the only thing that can get it wrong// is the wiring. Assert both answers come from the service rather than from the row's status.it('reports engineLoaded from the live engine map, not from the row status', async () => {- sessionService.isActive.mockReturnValue(true);+ sessionService.engineLoaded.mockReturnValue(true);const result = await controller.create({ name: 'test-session' });expect(result.engineLoaded).toBe(true);- expect(sessionService.isActive).toHaveBeenCalledWith(entity.id);+ expect(sessionService.engineLoaded).toHaveBeenCalledWith(expect.objectContaining({ id: entity.id }));});it('still audits the creation with the session id and name', async () => {@@ -121,12 +124,12 @@ describe('SessionController — logout() audit + error forwarding contract', ()updatedAt: new Date('2026-01-01T00:00:00Z'),};- let sessionService: { logout: jest.Mock; isActive: jest.Mock };+ let sessionService: { logout: jest.Mock; engineLoaded: jest.Mock };let auditService: { logInfo: jest.Mock };let controller: SessionController;beforeEach(() => {- sessionService = { logout: jest.fn(), isActive: jest.fn().mockReturnValue(false) };+ sessionService = { logout: jest.fn(), engineLoaded: jest.fn().mockReturnValue(false) };auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };controller = new SessionControllerClass(sessionService as unknown as SessionService,@@ -186,7 +189,7 @@ describe('SessionController — start/stop lifecycle', () => {updatedAt: new Date('2026-01-01T01:00:00Z'),};- let sessionService: { start: jest.Mock; stop: jest.Mock; forceKill: jest.Mock; isActive: jest.Mock };+ let sessionService: { start: jest.Mock; stop: jest.Mock; forceKill: jest.Mock; engineLoaded: jest.Mock };let auditService: { logInfo: jest.Mock };let controller: SessionController;@@ -195,7 +198,7 @@ describe('SessionController — start/stop lifecycle', () => {start: jest.fn(),stop: jest.fn(),forceKill: jest.fn(),- isActive: jest.fn().mockReturnValue(false),+ engineLoaded: jest.fn().mockReturnValue(false),};auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };controller = new SessionControllerClass(@@ -207,13 +210,13 @@ describe('SessionController — start/stop lifecycle', () => {it('start returns the session with engineLoaded read from the live engine map', async () => {sessionService.start.mockResolvedValue({ ...runningEntity });- sessionService.isActive.mockReturnValue(true);+ sessionService.engineLoaded.mockReturnValue(true);const result = await controller.start('sess-uuid-1');expect(result.status).toBe(SessionStatus.READY);expect(result.engineLoaded).toBe(true);- expect(sessionService.isActive).toHaveBeenCalledWith('sess-uuid-1');+ expect(sessionService.engineLoaded).toHaveBeenCalledWith(expect.objectContaining({ id: 'sess-uuid-1' }));});it('start audits SESSION_STARTED once the service has resolved', async () => {@@ -312,11 +315,11 @@ describe('SessionController — muteChat', () => {describe('SessionController findAll name filter', () => {const apiKey = { allowedSessions: ['sess-uuid-1'] } as unknown as ApiKey;- let sessionService: { findAll: jest.Mock; isActive: jest.Mock };+ let sessionService: { findAll: jest.Mock; engineLoaded: jest.Mock };let controller: SessionController;beforeEach(() => {- sessionService = { findAll: jest.fn().mockResolvedValue([]), isActive: jest.fn().mockReturnValue(false) };+ sessionService = { findAll: jest.fn().mockResolvedValue([]), engineLoaded: jest.fn().mockReturnValue(false) };controller = new SessionControllerClass(sessionService as unknown as SessionService,{ logInfo: jest.fn() } as unknown as AuditService,diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex fd47dc326..6deadddc0 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -75,9 +75,9 @@ export class SessionController {) {}private transformSession(session: Session): SessionResponseDto {- // isActive() is the engine map itself, so this is read at response time — a session that just+ // engineLoaded() reads the engine map itself, so this is read at response time: a session that just// finished reconnecting reports the engine in the same response that reports its status.- return SessionResponseDto.fromEntity(session, this.sessionService.isActive(session.id));+ return SessionResponseDto.fromEntity(session, this.sessionService.engineLoaded(session));}@Post()diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex ba8e7b653..669e5e688 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2025,7 +2025,7 @@ describe('SessionService', () => {i.reconnectStates.set('sess-uuid-1', state);const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);- // Twelve consecutive failed attempts (each timer fires, and its failure schedules the next) —+ // Twelve consecutive failed attempts (each timer fires, and its failure schedules the next):// the pre-fix default (5) would have wedged FAILED at the 6th; with the unlimited default// every one schedules another attempt.for (let k = 0; k < 12; k++) {@@ -2405,7 +2405,7 @@ describe('SessionService', () => {i.reconnectStates.set('sess-uuid-1', { attempts: 0, timer: null, maxAttempts: 5, baseDelay: 5000 });// Two disconnect events in a row each schedule a reconnect. The second must leave the first- // timer as the only one pending — otherwise both fire and double-init the engine.+ // timer as the only one pending; otherwise both fire and double-init the engine.i.scheduleReconnect('sess-uuid-1', createMockSession());i.scheduleReconnect('sess-uuid-1', createMockSession());@@ -7223,6 +7223,41 @@ describe('SessionService', () => {});});+ // A list or stats read is answered by whichever node the load balancer picked, while the lifecycle+ // routes are forwarded to the owner: a session a live peer runs is loaded as far as a client can act.+ describe('engineLoaded', () => {+ const withOwnership = (): void => {+ const ownership = new SessionOwnershipService(+ {} as Repository<Session>,+ {+ get: (key: string) => ({ 'session.nodeId': 'node-a' })[key],+ } as unknown as ConfigService,+ );+ Object.assign(service as unknown as Record<string, unknown>, { ownership });+ };+ const live = new Date(Date.now() + 60_000);++ it('is true for a session a peer node holds on a live lease, with no engine here', () => {+ withOwnership();+ const row = createMockSession({ nodeId: 'node-b', leaseExpiresAt: live });+ expect(service.isActive(row.id)).toBe(false);+ expect(service.engineLoaded(row)).toBe(true);+ });++ it('is false for a lapsed peer claim, and for this node’s own claim without an engine', () => {+ withOwnership();+ expect(service.engineLoaded(createMockSession({ nodeId: 'node-b', leaseExpiresAt: new Date(0) }))).toBe(false);+ expect(service.engineLoaded(createMockSession({ nodeId: 'node-a', leaseExpiresAt: live }))).toBe(false);+ });++ it('is true for this process’s own engine', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ expect(service.engineLoaded(createMockSession())).toBe(true);+ });+ });+// ── onModuleInit ──────────────────────────────────────────────────describe('onModuleInit', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 344612057..a0ac4d0cb 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -925,6 +925,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.has(id);}+ /**+ * The response's `engineLoaded`: an engine in this process, or a live claim by a peer node. A list+ * is answered by whichever node the request landed on, while the lifecycle routes are forwarded to+ * the owner, so a session a peer runs must not read as stopped. The local precondition checks keep+ * using {@link isActive}.+ */+ engineLoaded(session: Session): boolean {+ return this.isActive(session.id) || !!this.ownership?.heldByOtherLiveNode(session);+ }+/*** 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