Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): release the ownership claim on every teardown path, and stop renewing dead ones
Yudhi Armyndharis2fc2a1d64ffc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9bea8599..dd040a1f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.+- **Multi-node: a session claim could outlive its engine and pin the session to one node forever.** A failed start, a logout, a force-kill or an exhausted reconnect kept the ownership claim, and the heartbeat renewed it indefinitely — the session could not be started on any peer and the takeover sweep never saw it. Claims are now released on every teardown path, and the heartbeat only renews claims that still cover a live engine, an in-flight start or a pending reconnect. Starting a nonexistent session also answers 404 again instead of a misleading 409 "running on another node".- Corrected column names in `docs/05-database-design.md`.### Securitydiff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 16b790af4..8cb7f42fe 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -401,6 +401,17 @@ export class SessionEngineLifecycle {this.fences.evictAndForceDestroy(id, engine);}+ /**+ * True while this process still has anything alive for the session: a registered engine, an+ * in-flight start(), or reconnect state whose armed/executing attempt will re-register one.+ * The ownership heartbeat consults this so a claim that no longer covers an engine stops being+ * renewed and can lapse for a peer to adopt; the service-level release paths consult it so an+ * "already starting/started" refusal never releases a session this node genuinely runs.+ */+ isEngineActive(id: string): boolean {+ return this.engines.has(id) || this.initializingSessions.has(id) || this.reconnectStates.has(id);+ }+// --- Leaf-event delegates (SessionEngineLeafEvents) ------------------------------------------// Same-named, same-signature forwarders onto the extracted unit, so handleEngineReady's call// site stays byte-identical (the wiring reaches the unit directly through host.leafEvents).@@ -768,6 +779,10 @@ export class SessionEngineLifecycle {if (deadEngine) {this.evictAndForceDestroy(id, deadEngine);}+ // Terminal: drop the reconnect state too. Nothing fires again for this episode, and a stale+ // entry would keep isEngineActive() true — the ownership heartbeat would renew the claim on+ // a session with no engine, pinning it to this node. start() builds fresh state anyway.+ this.cancelReconnect(id);return;}diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.tsindex cc527b988..e155d171d 100644--- a/src/modules/session/session-ownership.service.spec.ts+++ b/src/modules/session/session-ownership.service.spec.ts@@ -154,6 +154,45 @@ describe('SessionOwnershipService', () => {expect(renewed.getTime()).toBeGreaterThan(first.getTime());});+ /**+ * A claim whose engine is gone must be allowed to lapse: renewing it unconditionally pinned+ * the session to this node forever — unstartable on any peer, invisible to the takeover sweep.+ * The id stays tracked so the loss is still noticed when a peer takes the row.+ */+ it('skips renewal for a held claim the liveness probe reports dead, so the lease can lapse', async () => {+ const session = await seed();+ const nodeA = service('node-a', 5_000);+ await nodeA.claim(session.id);+ const first = (await sessions.findOneByOrFail({ id: session.id })).leaseExpiresAt!;++ nodeA.setEngineLiveness(() => false);+ await new Promise(resolve => setTimeout(resolve, 25));+ await nodeA.renew();++ const stored = await sessions.findOneByOrFail({ id: session.id });+ expect(stored.leaseExpiresAt!.getTime()).toBe(first.getTime());+ expect(nodeA.ownedIds()).toContain(session.id);+ });++ it('keeps renewing the claims the liveness probe reports alive', async () => {+ const liveSession = await seed();+ const deadSession = await seed();+ const nodeA = service('node-a', 5_000);+ await nodeA.claim(liveSession.id);+ await nodeA.claim(deadSession.id);+ const firstLive = (await sessions.findOneByOrFail({ id: liveSession.id })).leaseExpiresAt!;+ const firstDead = (await sessions.findOneByOrFail({ id: deadSession.id })).leaseExpiresAt!;++ nodeA.setEngineLiveness(id => id === liveSession.id);+ await new Promise(resolve => setTimeout(resolve, 25));+ await nodeA.renew();++ const live = (await sessions.findOneByOrFail({ id: liveSession.id })).leaseExpiresAt!;+ const dead = (await sessions.findOneByOrFail({ id: deadSession.id })).leaseExpiresAt!;+ expect(live.getTime()).toBeGreaterThan(firstLive.getTime());+ expect(dead.getTime()).toBe(firstDead.getTime());+ });+/*** A node that lost a session must stop extending it. Renewal only writes `leaseExpiresAt`, so* the evidence is that value staying put — a stale node refreshing a peer's lease would keepdiff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex fbac638eb..1843649dd 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -43,6 +43,8 @@ export class SessionOwnershipService {private readonly owned = new Set<string>();/** Notified when a renewal proves this process no longer holds sessions it thought it did. */private onLeaseLost?: (sessionIds: string[]) => Promise<void> | void;+ /** Answers "does anything still run for this id here?" — consulted by renew(). See setEngineLiveness. */+ private engineLiveness?: (sessionId: string) => boolean;constructor(@InjectRepository(Session, 'data')@@ -180,6 +182,15 @@ export class SessionOwnershipService {this.onLeaseLost = handler;}+ /**+ * Register the probe renew() consults before extending a lease. Wired by SessionService to the+ * engine lifecycle (engine registered, start in flight, or reconnect pending). Optional like the+ * lease-loss handler: without it every held claim renews unconditionally.+ */+ setEngineLiveness(probe: (sessionId: string) => boolean): void {+ this.engineLiveness = probe;+ }+/*** Push every held lease out by another TTL, and find out whether any were lost.*@@ -188,18 +199,27 @@ export class SessionOwnershipService {* moment to notice, because it is the only regular contact with the row.*/async renew(): Promise<void> {- const ids = [...this.owned];- if (ids.length === 0) return;+ const held = [...this.owned];+ if (held.length === 0) return;++ // Only claims that still cover something alive on this process are pushed out. A claim whose+ // engine is gone (a failed start, an exhausted reconnect) must be allowed to lapse — renewing+ // it unconditionally pinned such sessions to this node forever: unstartable on any peer and+ // invisible to the takeover sweep, which only sees lapsed leases. The id stays in `owned` so+ // the loss is still noticed below once a peer actually takes the row.+ const live = this.engineLiveness ? held.filter(id => this.engineLiveness!(id)) : held;let kept: Set<string>;try {- await this.sessions- .createQueryBuilder()- .update(Session)- .set({ leaseExpiresAt: new Date(Date.now() + this.leaseTtlMs) })- .where({ id: In(ids), nodeId: this.nodeId })- .execute();- const rows = await this.sessions.find({ where: { id: In(ids), nodeId: this.nodeId }, select: { id: true } });+ if (live.length > 0) {+ await this.sessions+ .createQueryBuilder()+ .update(Session)+ .set({ leaseExpiresAt: new Date(Date.now() + this.leaseTtlMs) })+ .where({ id: In(live), nodeId: this.nodeId })+ .execute();+ }+ const rows = await this.sessions.find({ where: { id: In(held), nodeId: this.nodeId }, select: { id: true } });kept = new Set(rows.map(row => row.id));} catch (error) {// A failed renewal is survivable — the next tick tries again, and the TTL is long enough to@@ -213,7 +233,7 @@ export class SessionOwnershipService {return;}- const lost = ids.filter(id => !kept.has(id));+ const lost = held.filter(id => !kept.has(id));if (lost.length === 0) return;for (const id of lost) this.owned.delete(id);this.logger.warn(`Lost the claim on ${lost.length} session(s); another node now holds them`, {diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 26766d627..c998c8719 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1030,6 +1030,112 @@ describe('SessionService', () => {});});+ // ── ownership claim lifecycle (multi-node) ────────────────────────++ describe('ownership release', () => {+ type OwnershipStub = { claim: jest.Mock; release: jest.Mock };++ // The trailing @Optional constructor dep the DI module deliberately omits; poked onto the+ // instance like the other white-box seams in this file.+ const withOwnership = (claimResult = true): OwnershipStub => {+ const ownership: OwnershipStub = {+ claim: jest.fn().mockResolvedValue(claimResult),+ release: jest.fn().mockResolvedValue(undefined),+ };+ Object.assign(service as unknown as Record<string, unknown>, { ownership });+ return ownership;+ };++ it('start() releases the claim when the launch fails and nothing stays alive here', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'start').mockRejectedValue(new Error('engine init failed'));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);++ await expect(service.start('sess-uuid-1')).rejects.toThrow('engine init failed');++ expect(ownership.claim).toHaveBeenCalledWith('sess-uuid-1');+ expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');+ });++ it('start() keeps the claim when the refusal means the engine genuinely runs here', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'start').mockRejectedValue(new BadRequestException('Session is already started'));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(true);++ await expect(service.start('sess-uuid-1')).rejects.toThrow(BadRequestException);++ // Releasing here would invite a peer to open a second connection to the account.+ expect(ownership.release).not.toHaveBeenCalled();+ });++ it('start() answers 404, not 409, when the claim matched nothing because the session does not exist', async () => {+ withOwnership(false);+ (repository.findOne as jest.Mock).mockResolvedValue(null);++ await expect(service.start('missing-uuid')).rejects.toThrow(NotFoundException);+ });++ it('start() answers 409 when a live peer really holds the session', async () => {+ withOwnership(false);+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ await expect(service.start('sess-uuid-1')).rejects.toThrow(ConflictException);+ });++ it('logout() hands the claim back once the engine is torn down', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'logout').mockResolvedValue(createMockSession());++ await service.logout('sess-uuid-1');++ expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');+ });++ it('logout() releases on the 502-incomplete path too — the engine is down either way', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'logout').mockRejectedValue(new BadGatewayException('incomplete'));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);++ await expect(service.logout('sess-uuid-1')).rejects.toThrow(BadGatewayException);++ expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');+ });++ it('forceKill() hands the claim back after the kill', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'forceKill').mockResolvedValue(createMockSession());++ await service.forceKill('sess-uuid-1');++ expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');+ });+ });++ describe('isEngineActive', () => {+ it('is live for a registered engine, an in-flight start, or reconnect state — dead otherwise', () => {+ const intern = lifecycle as unknown as {+ engines: { set: (id: string, e: unknown) => void; delete: (id: string) => void };+ initializingSessions: Set<string>;+ reconnectStates: Map<string, unknown>;+ };+ expect(lifecycle.isEngineActive('x')).toBe(false);++ intern.engines.set('x', {});+ expect(lifecycle.isEngineActive('x')).toBe(true);+ intern.engines.delete('x');++ intern.initializingSessions.add('x');+ expect(lifecycle.isEngineActive('x')).toBe(true);+ intern.initializingSessions.delete('x');++ intern.reconnectStates.set('x', { attempts: 1, timer: null });+ expect(lifecycle.isEngineActive('x')).toBe(true);+ intern.reconnectStates.delete('x');++ expect(lifecycle.isEngineActive('x')).toBe(false);+ });+ });+// ── engine onError / lastError surfacing (#219) ───────────────────describe('terminal-failure engine eviction', () => {@@ -1218,6 +1324,23 @@ describe('SessionService', () => {expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/reconnection failed after 2 attempts/i);});+ it('drops the reconnect state on exhaustion so the session no longer reads engine-active', async () => {+ // A stale entry would keep isEngineActive() true, and the ownership heartbeat would renew+ // the claim on a session with no engine — pinning a FAILED session to this node forever.+ const i = lifecycle as unknown as {+ reconnectStates: Map<string, { attempts: number; timer: null; maxAttempts: number; baseDelay: number }>;+ scheduleReconnect: (id: string, session: Session) => void;+ };+ i.reconnectStates.set('sess-uuid-1', { attempts: 2, timer: null, maxAttempts: 2, baseDelay: 5000 });+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ i.scheduleReconnect('sess-uuid-1', createMockSession());+ await new Promise(resolve => setImmediate(resolve));++ expect(i.reconnectStates.has('sess-uuid-1')).toBe(false);+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(false);+ });+it('does not throw when the engine was already evicted (executeReconnect-catch path)', () => {// executeReconnect evicts the half-built engine before scheduling a reconnect, so by the time// the maxAttempts branch runs there the engine is gone. The eviction guard must handle that.diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex b202cb4b3..e93583ae7 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -132,6 +132,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// The teardown report is not consulted here: losing a claim is not a request anyone is waiting// on, and stopOrphanEngines already logs what it could not stop.this.ownership?.onLeaseLoss(async ids => void (await this.engineLifecycle.stopOrphanEngines(ids)));+ // Claims are only renewed while something still runs for them here, so a claim left behind by+ // an untracked teardown path lapses instead of pinning the session to this node forever.+ this.ownership?.setEngineLiveness(id => this.engineLifecycle.isEngineActive(id));// Renewal runs regardless of auto-start: a session started through the API later is claimed the// same way and must keep its lease alive.this.ownership?.startHeartbeat();@@ -281,9 +284,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Claimed before the engine is launched, never after: launching first and discovering the// session belongs elsewhere would already have opened a second connection to the account.if (this.ownership && !(await this.ownership.claim(id))) {+ // The claim is a conditional UPDATE, so an id that does not exist also matches zero rows —+ // surface the route's documented 404 for that case instead of a misleading 409.+ await this.findOne(id);throw new ConflictException(`Session ${id} is running on another node`);}- return this.engineLifecycle.start(id);+ try {+ return await this.engineLifecycle.start(id);+ } catch (error) {+ // A failed or refused start must not leave the claim pinned here — the heartbeat would renew+ // it and the session could never be started anywhere else. Released only when nothing is+ // actually alive locally: an "already starting/started" refusal means this node genuinely+ // runs the engine, and releasing then would invite a peer to open a second connection.+ await this.releaseUnlessEngineActive(id);+ throw error;+ }}async stop(id: string): Promise<Session> {@@ -296,11 +311,36 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat/** See SessionEngineLifecycle.logout() for the full unlink/502 contract. */async logout(id: string): Promise<Session> {- return this.engineLifecycle.logout(id);+ try {+ const session = await this.engineLifecycle.logout(id);+ // Torn down locally on the 200 path — hand the claim back the way stop() does.+ await this.ownership?.release(id);+ return session;+ } catch (error) {+ // The 502-incomplete path tears the engine down too, and a "not started" refusal never had+ // one — either way a claim that no longer covers an engine must not survive the call.+ await this.releaseUnlessEngineActive(id);+ throw error;+ }}async forceKill(id: string): Promise<Session> {- return this.engineLifecycle.forceKill(id);+ try {+ const session = await this.engineLifecycle.forceKill(id);+ await this.ownership?.release(id);+ return session;+ } catch (error) {+ await this.releaseUnlessEngineActive(id);+ throw error;+ }+ }++ /** Hand the claim back unless something still runs here (engine, in-flight start, pending reconnect). */+ private async releaseUnlessEngineActive(id: string): Promise<void> {+ if (!this.ownership || this.engineLifecycle.isEngineActive(id)) {+ return;+ }+ await this.ownership.release(id);}async getQRCode(id: string): Promise<{ qrCode: string; status: SessionStatus }> {