Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): reset a status left behind by a node that never returned
Yudhi Armyndharis076baf2a3728
diff --git a/.env.example b/.env.exampleindex 7f8de026f..c0b59c3c6 100644--- a/.env.example+++ b/.env.example@@ -495,7 +495,9 @@ WEBHOOK_SSRF_PROTECT=true# renewal still lands inside the lease; boot FAILS otherwise# SESSION_TAKEOVER_SWEEP_MS=30000 # how often a node adopts sessions whose holder's lease# lapsed (crashed peer / this node's previous container- # identity); follows AUTO_START_SESSIONS+ # identity); adopting follows AUTO_START_SESSIONS, the+ # sweep itself always runs and also marks a vanished+ # node's leftover rows disconnected# NODE_URL= # where THIS node answers HTTP for its peers, e.g.# http://10.0.0.5:2785 — set on EVERY node to enable# forwarding of session requests to the owning node;diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee4b62bb4..c9899ec93 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The Sessions page reports a dead live-event feed and offers a retry, and re-reads the list once thefeed comes back. The socket gives up after five attempts, and the page kept rendering whateverstatus arrived last with no indication that it had stopped updating.+- A session left `ready` or `initializing` by a node that never came back is marked disconnected by+ the takeover sweep. The boot reset skips a row still claimed by another node id, and a container+ recreate changes that id by default, so with `AUTO_START_SESSIONS` off nothing revisited the row and+ it went on reporting an engine no process was running. The sweep now runs regardless of that flag;+ adopting a session still requires it.## [0.23.4] - 2026-09-05diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex edfb905f7..bd6083c7d 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -29,13 +29,16 @@> because another node is running them.>> **Failover now completes on its own.** A periodic takeover sweep (default every 30s,-> `SESSION_TAKEOVER_SWEEP_MS`, gated by the same `AUTO_START_SESSIONS` flag as boot-> auto-start) adopts sessions whose holder's lease lapsed — a crashed peer, or a recreated+> `SESSION_TAKEOVER_SWEEP_MS`) adopts sessions whose holder's lease lapsed — a crashed peer, or a recreated> container whose new identity boots before its old lease expires. Only authenticated> sessions in a running-or-should-be state are adopted; mid-pairing and operator-`failed`> ones are left alone, and a cleanly stopped session releases its claim so it is never> "lapsed". Adopting a session fails its stuck in-flight batches (no auto-resume — the dead-> node's already-sent messages are unknowable).+> node's already-sent messages are unknowable). Adopting is gated by the same+> `AUTO_START_SESSIONS` flag as boot auto-start; the sweep itself is not, because it also has a job+> that starts nothing: a row a vanished node left in a running status is marked disconnected once its+> lease has been silent for two TTLs. Nothing else revisits such a row, since the boot reset skips a+> foreign claim that is still live.>> **Request routing now exists, opt-in via `NODE_URL`.** When every node sets its own> reachable URL (e.g. `NODE_URL=http://10.0.0.5:2785`), a session-scoped request landing ondiff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 559db37b7..c4d218c0c 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -1174,4 +1174,9 @@ export class SessionEngineLifecycle {updateStatus(id: string, status: SessionStatus): Promise<void> {return this.broadcaster.updateStatus(id, status);}++ /** Public delegate: the fan-out half only, for a caller that wrote the row under its own predicate. */+ announceStatus(id: string, status: SessionStatus): void {+ this.broadcaster.announce(id, status);+ }}diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex 422c47336..c190c9ad8 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -75,7 +75,8 @@ export class SessionOwnershipService {return this.configService?.get<string>('session.nodeUrl') || process.env.NODE_URL || '';}- private get leaseTtlMs(): number {+ /** Public because the takeover sweep sizes its "this holder is really gone" cutoff against it. */+ get leaseTtlMs(): number {return this.configService?.get<number>('session.leaseTtlMs') ?? 60_000;}diff --git a/src/modules/session/session-status-broadcaster.ts b/src/modules/session/session-status-broadcaster.tsindex d9604cda7..48f836314 100644--- a/src/modules/session/session-status-broadcaster.ts+++ b/src/modules/session/session-status-broadcaster.ts@@ -45,6 +45,18 @@ export class SessionStatusBroadcaster {status,action: 'status_update',});+ this.announce(id, status);+ }++ /**+ * The fan-out half of updateStatus, for a caller that has ALREADY written the row itself.+ *+ * One caller needs that split: a row whose owning node is gone has to be corrected under a+ * predicate (still that node's, still lapsed, still claiming to run), never by id, because a peer+ * can claim and start it at any moment. Writing by id afterwards to get the fan-out would undo the+ * predicate. Everything else must keep using updateStatus.+ */+ announce(id: string, status: SessionStatus): void {// 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.diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 8d0f04f5a..929d0569a 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2451,6 +2451,84 @@ describe('SessionService', () => {});});+ // A row whose owning node never came back: the boot reset cannot touch it (it is fenced to what+ // this node may claim, and a foreign claim on an unexpired lease is not claimable), so without this+ // it reports READY for an engine no process runs.+ describe('markLapsedDisconnected', () => {+ const GONE_BEFORE = new Date('2026-01-01T00:00:00.000Z');+ const stranded = (over: Partial<Session> = {}): Session =>+ ({+ id: 'stranded-1',+ name: 'stranded',+ status: SessionStatus.READY,+ nodeId: 'dead-node',+ leaseExpiresAt: new Date('2025-12-31T23:00:00.000Z'),+ ...over,+ }) as Session;++ beforeEach(() => {+ (repository.update as jest.Mock).mockClear();+ (webhookService.dispatch as jest.Mock).mockClear();+ });++ it('writes under the predicate it read on, never by id alone', async () => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ const marked = await service.markLapsedDisconnected([stranded()], GONE_BEFORE);++ expect(marked).toEqual(['stranded-1']);+ const [where, patch] = (repository.update as jest.Mock).mock.calls[0] as [+ Record<string, unknown>,+ Record<string, unknown>,+ ];+ // A claim rewrites nodeId, so a row a peer took between the read and this write matches nothing.+ expect(where).toMatchObject({ id: 'stranded-1', nodeId: 'dead-node', status: SessionStatus.READY });+ expect(where.leaseExpiresAt).toBeDefined();+ expect(patch).toEqual({ status: SessionStatus.DISCONNECTED });+ });++ it('announces the correction so the dashboard and webhooks see it', async () => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.markLapsedDisconnected([stranded()], GONE_BEFORE);++ expect(webhookService.dispatch).toHaveBeenCalledWith('stranded-1', 'session.status', {+ sessionId: 'stranded-1',+ status: SessionStatus.DISCONNECTED,+ });+ });++ it('stays silent when the row was claimed between the read and the write', async () => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 0 });++ const marked = await service.markLapsedDisconnected([stranded()], GONE_BEFORE);++ expect(marked).toEqual([]);+ expect(webhookService.dispatch).not.toHaveBeenCalledWith('stranded-1', 'session.status', expect.anything());+ });++ it('leaves a holder that lapsed only recently alone: a live peer re-extends its lease', async () => {+ const recent = stranded({ leaseExpiresAt: new Date('2026-01-01T00:00:30.000Z') });++ const marked = await service.markLapsedDisconnected([recent], GONE_BEFORE);++ expect(marked).toEqual([]);+ expect(repository.update).not.toHaveBeenCalled();+ });++ it('leaves FAILED and DISCONNECTED rows alone: one needs a human, the other is already right', async () => {+ const rows = [+ stranded({ id: 'f', status: SessionStatus.FAILED }),+ stranded({ id: 'd', status: SessionStatus.DISCONNECTED }),+ ];++ const marked = await service.markLapsedDisconnected(rows, GONE_BEFORE);++ expect(marked).toEqual([]);+ expect(repository.update).not.toHaveBeenCalled();+ });+ });+// An engine that retries a dropped connection ON ITS OWN never reaches the service-level reconnect// loop, so before this wiring a Baileys session could sit at INITIALIZING for hours with no// webhook, no lastError and a flat reconnect counter. #1546 was reported with an empty logs box fordiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex c6800c2a4..3c8dd3ba1 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -11,7 +11,7 @@ import {} from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';-import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';+import { Repository, In, Not, IsNull, LessThan, DataSource, FindManyOptions } from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';import { setTimeout } from 'node:timers/promises';import { EngineTransportError } from '../../common/errors/engine-transport.error';@@ -79,6 +79,19 @@ function isTransientLaunchFailure(error: unknown): boolean {/** Pause between sequential auto-start launches so a burst of Chromium boots does not spike the host. */export const AUTOSTART_THROTTLE_MS = 2_000;+/**+ * Statuses that assert an engine is running somewhere. The boot reset clears them for every row this+ * node may claim; markLapsedDisconnected clears them for a row whose holder never came back. FAILED+ * and CREATED stay out of both: an operator has to see them.+ */+const ACTIVE_STATUSES = [+ SessionStatus.READY,+ SessionStatus.INITIALIZING,+ SessionStatus.QR_READY,+ SessionStatus.AUTHENTICATING,+ SessionStatus.ACTION_REQUIRED,+];+/*** The session-record API: CRUD over the sessions table, aggregate stats, and the thin engine query* proxies (QR/pairing/chats/groups/chat-state) behind the controller routes. Every engine LIFECYCLE@@ -134,17 +147,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* serving traffic. A row held by another node with an unexpired lease is therefore left alone.*/async onModuleInit(): Promise<void> {- const activeStatuses = [- SessionStatus.READY,- SessionStatus.INITIALIZING,- SessionStatus.QR_READY,- SessionStatus.AUTHENTICATING,- SessionStatus.ACTION_REQUIRED,- ];-const claimable = this.ownership?.claimableWhere() ?? [{}];const result = await this.sessionRepository.update(- claimable.map(clause => ({ ...clause, status: In(activeStatuses) })),+ claimable.map(clause => ({ ...clause, status: In(ACTIVE_STATUSES) })),{ status: SessionStatus.DISCONNECTED },);@@ -855,4 +860,55 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat): Promise<{ stopped: string[]; notRunning: string[]; failed: string[] }> {return this.engineLifecycle.stopOrphanEngines(sessionIds);}++ /**+ * Mark disconnected every session a vanished node left in a running status.+ *+ * A lapsed claim means no process hosts that engine any more: a crashed peer, or this container's+ * own previous identity after a recreate (the default nodeId is the hostname, which a recreate+ * changes). The boot reset cannot touch those rows because it is fenced to what this node may+ * claim, and a row still naming a foreign node on an unexpired lease is not one of them, so+ * without this the row goes on reporting READY for an engine nobody runs. The claim itself is+ * deliberately left in place, so the row stays the adoptable orphan the takeover sweep looks for.+ *+ * `goneBefore` is the caller's "really gone" cutoff, not simply now: a lease lapses while its+ * holder is perfectly healthy whenever a query runs long, and the next heartbeat re-extends it.+ * Acting on a single lapse would report a live peer's sessions as disconnected, and nothing would+ * correct it, because that peer's renewal still finds its own nodeId and detects no loss.+ */+ async markLapsedDisconnected(sessions: Session[], goneBefore: Date): Promise<string[]> {+ const marked: string[] = [];+ for (const session of sessions) {+ if (!ACTIVE_STATUSES.includes(session.status)) continue;+ // Both are guaranteed non-null by the lapsed-claim query that produced these rows, and both are+ // load-bearing in the predicate below: TypeORM drops an `undefined` value from a where clause+ // rather than matching on it, so a null here would silently widen the update.+ if (session.nodeId == null) continue;+ if (session.leaseExpiresAt == null || session.leaseExpiresAt >= goneBefore) continue;+ // Written on the same predicate the read used, never by id alone: a peer, or this node's own+ // adopt loop, can claim and start this row at any moment, and a claim rewrites `nodeId`, so a+ // row that was taken matches nothing here and keeps the status its start gave it.+ const { affected } = await this.sessionRepository.update(+ {+ id: session.id,+ nodeId: session.nodeId,+ leaseExpiresAt: LessThan(goneBefore),+ status: session.status,+ },+ { status: SessionStatus.DISCONNECTED },+ );+ if (!affected) continue;+ this.logger.warn(`Session ${session.name} was left ${session.status} by a node that never came back`, {+ sessionId: session.id,+ action: 'lapsed_claim_reset',+ fromNode: session.nodeId,+ });+ // Fan-out only. The row is already written above, under the predicate that makes it safe;+ // going back through updateStatus would re-write it by id and could land on a row a peer has+ // since claimed and started.+ this.engineLifecycle.announceStatus(session.id, SessionStatus.DISCONNECTED);+ marked.push(session.id);+ }+ return marked;+ }}diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.tsindex b1381cbb8..152f25652 100644--- a/src/modules/takeover/session-takeover.service.spec.ts+++ b/src/modules/takeover/session-takeover.service.spec.ts@@ -27,9 +27,15 @@ describe('SessionTakeoverService', () => {const build = (rows: Session[],opts: { autoStart?: boolean; startImpl?: jest.Mock } = {},- ): { svc: SessionTakeoverService; start: jest.Mock; reap: jest.Mock } => {+ ): {+ svc: SessionTakeoverService;+ start: jest.Mock;+ reap: jest.Mock;+ markLapsedDisconnected: jest.Mock;+ } => {const start = opts.startImpl ?? jest.fn().mockResolvedValue({});const reap = jest.fn().mockResolvedValue(0);+ const markLapsedDisconnected = jest.fn().mockResolvedValue([]);const config = {get: (key: string, def?: unknown) =>({@@ -38,12 +44,15 @@ describe('SessionTakeoverService', () => {})[key as 'features'] ?? def,} as unknown as ConfigService;const svc = new SessionTakeoverService(- { start } as unknown as SessionService,- { lapsedHeldByOthers: jest.fn().mockResolvedValue(rows) } as unknown as SessionOwnershipService,+ { start, markLapsedDisconnected } as unknown as SessionService,+ {+ lapsedHeldByOthers: jest.fn().mockResolvedValue(rows),+ leaseTtlMs: 60_000,+ } as unknown as SessionOwnershipService,{ reapProcessingBatches: reap } as unknown as BulkMessageService,config,);- return { svc, start, reap };+ return { svc, start, reap, markLapsedDisconnected };};afterEach(() => {@@ -139,13 +148,50 @@ describe('SessionTakeoverService', () => {expect(start).toHaveBeenCalledTimes(2);});- it('the AUTO_START_SESSIONS opt-out disables the sweep timer entirely', () => {+ it('the AUTO_START_SESSIONS opt-out arms the sweep but starts nothing', async () => {+ // The opt-out means "no spontaneous engine starts", not "leave a dead node's sessions reporting+ // READY forever". The sweep is the only thing that revisits those rows, so it has to keep+ // running; only the adopting half is gated.jest.useFakeTimers();- const { svc } = build([], { autoStart: false });+ const { svc, start, markLapsedDisconnected } = build([lapsed({ name: 'a' })], { autoStart: false });svc.onApplicationBootstrap();+ expect(jest.getTimerCount()).toBe(1);- expect(jest.getTimerCount()).toBe(0);+ jest.useRealTimers();+ await svc.sweep();++ expect(markLapsedDisconnected).toHaveBeenCalledTimes(1);+ expect(start).not.toHaveBeenCalled();+ });++ it('corrects stale statuses BEFORE adopting, so the write cannot land on a live engine', async () => {+ const order: string[] = [];+ const { svc, start, markLapsedDisconnected } = build([lapsed({ name: 'a' })]);+ markLapsedDisconnected.mockImplementation(() => {+ order.push('mark');+ return Promise.resolve([]);+ });+ start.mockImplementation(() => {+ order.push('start');+ return Promise.resolve({});+ });++ await svc.sweep();++ expect(order).toEqual(['mark', 'start']);+ });++ it('gives the reset a cutoff of two lease TTLs, so a healthy peer that lapsed once is left alone', async () => {+ const { svc, markLapsedDisconnected } = build([lapsed({ name: 'a' })]);+ const before = Date.now();++ await svc.sweep();++ const [, goneBefore] = markLapsedDisconnected.mock.calls[0] as [Session[], Date];+ // 60s TTL x 2: anything whose lease expired inside the last two minutes is still presumed alive.+ expect(before - goneBefore.getTime()).toBeGreaterThanOrEqual(120_000);+ expect(before - goneBefore.getTime()).toBeLessThan(121_000);});it('arms the timer when auto-start is on, and tears it down on destroy', () => {@@ -174,8 +220,8 @@ describe('SessionTakeoverService', () => {({ features: { autoStartSessions: true }, 'session.takeoverSweepMs': 1000 })[key as 'features'] ?? def,} as unknown as ConfigService;const svc = new SessionTakeoverService(- { start } as unknown as SessionService,- { lapsedHeldByOthers: ownershipCalls } as unknown as SessionOwnershipService,+ { start, markLapsedDisconnected: jest.fn().mockResolvedValue([]) } as unknown as SessionService,+ { lapsedHeldByOthers: ownershipCalls, leaseTtlMs: 60_000 } as unknown as SessionOwnershipService,{ reapProcessingBatches: jest.fn().mockResolvedValue(0) } as unknown as BulkMessageService,config,);diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.tsindex 8cc22cf3a..cde545f69 100644--- a/src/modules/takeover/session-takeover.service.ts+++ b/src/modules/takeover/session-takeover.service.ts@@ -26,6 +26,17 @@ const TAKEOVER_STATUSES = new Set<SessionStatus>([/** Pause between successive engine launches, matching the boot auto-start's Chromium stagger. */const TAKEOVER_START_STAGGER_MS = 2000;+/**+ * How many lease TTLs of silence make a holder "really gone".+ *+ * Two, not one. A lease lapses while its holder is perfectly healthy whenever a query runs long, and+ * the next heartbeat re-extends it; correcting a status on a single lapse would report a live peer's+ * sessions as disconnected, and nothing would put that right, because the peer's own renewal still+ * finds its nodeId and detects no loss. Adoption is unaffected and still acts on the first lapse: it+ * goes through claim(), which a live holder wins back.+ */+const STRANDED_LEASE_TTL_MULTIPLE = 2;+/*** Adopts sessions whose holder's lease has lapsed.*@@ -74,9 +85,12 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD}onApplicationBootstrap(): void {- // The same flag that governs boot auto-start: a deployment that opted out of automatic engine- // starts must not get spontaneous ones from the sweep either.- if (!resolveFeatureFlags(this.configService).autoStartSessions) return;+ // Deliberately NOT gated on auto-start any more. The sweep now has a second job that starts+ // nothing: correcting a status whose owner is gone. Nothing else revisits one, because the boot+ // reset skips a foreign claim that is still live and after a container recreate the previous+ // hostname IS foreign, so with auto-start off the row went on reporting a running engine no+ // process holds. The adopt loop below is still behind the flag: an operator who disabled+ // auto-start asked for no spontaneous engine starts, not for a dashboard that lies.const sweepMs = this.configService?.get<number>('session.takeoverSweepMs', 30_000) ?? 30_000;this.sweepTimer = setInterval(() => {// At most one sweep at a time: a slow start (Chromium launch) must not stack a second sweep@@ -104,10 +118,21 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD}}- /** One pass: adopt every eligible lapsed session. Exposed for the spec; the timer drives it. */+ /**+ * One pass: correct every stale status a vanished node left behind, then adopt every eligible+ * lapsed session. Exposed for the spec; the timer drives it.+ */async sweep(): Promise<void> {if (this.stopping) return;const lapsed = await this.ownership.lapsedHeldByOthers();++ // Correct the stale statuses BEFORE adopting: a row this pass goes on to start gets its+ // INITIALIZING written by start() afterwards, so the correction can never land on a live engine.+ // Idempotent, because DISCONNECTED is not one of the statuses it acts on.+ const goneBefore = new Date(Date.now() - this.ownership.leaseTtlMs * STRANDED_LEASE_TTL_MULTIPLE);+ await this.sessionService.markLapsedDisconnected(lapsed, goneBefore);++ if (!resolveFeatureFlags(this.configService).autoStartSessions) return;const eligible = lapsed.filter(session => this.isEligible(session));if (eligible.length === 0) return;