Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): adopt sessions abandoned by a lapsed node

Yudhi Armyndharis4f09d2c7c8fc
diff --git a/.env.example b/.env.example
index 674d95efc..f9b273b16 100644
--- a/.env.example
+++ b/.env.example
@@ -392,6 +392,9 @@ WEBHOOK_SSRF_PROTECT=true
# SESSION_LEASE_TTL_MS=60000 # how long a claim survives unrenewed (default 60s) —
# # also the worst-case failover delay after an unclean exit
# SESSION_LEASE_HEARTBEAT_MS=20000 # renewal cadence (default 20s)
+# 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
# MEDIA_CONVERSION_ENABLED=false # default false
# FFMPEG_PATH=ffmpeg # absolute path, for a binary outside PATH
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 977145b91..79b6295b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
agent tools (`AutomationRuleFindAll`, `AutomationRuleFindOne`) expose the rules to MCP callers;
as operator-level configuration the module is not part of the SDK surface.
+### Added
+
+- **Sessions abandoned by a dead node are now adopted automatically.** The ownership lease made a
+ crashed node's sessions *claimable*, but nothing ever claimed them: boot auto-start runs exactly
+ once, so a peer that was already up — or a recreated container whose boot landed before its own
+ previous identity's lease expired — left the sessions sitting disconnected until someone called
+ `POST /start` (both cases observed live). A periodic takeover sweep (default every 30s,
+ `SESSION_TAKEOVER_SWEEP_MS`, gated by the same `AUTO_START_SESSIONS` flag as boot auto-start) now
+ finds lapsed-lease sessions and starts them through the ordinary race-safe claim path. Only
+ sessions worth resuming are adopted: authenticated ones in a running-or-should-be state — never
+ mid-pairing (`qr_ready`), never operator-flagged `failed`, and never deliberately released ones
+ (stop and graceful shutdown clear the holder, so they are not "lapsed"). Adopting a session also
+ fails its stuck in-flight bulk batches (same no-auto-resume policy as the boot reaper — the dead
+ node's already-sent messages are unknowable, so resuming would risk double-sends).
+
### Fixed
- **whatsapp-web.js sessions could come up "ready" with a dead inbound pipeline after a warm
diff --git a/src/app.module.ts b/src/app.module.ts
index 6ffea742f..339cb7fb7 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -36,6 +36,7 @@ import { MediaModule } from './modules/media/media.module';
import { StatusStoreModule } from './modules/status-store/status-store.module';
import { ChatMediaModule } from './modules/chat-media/chat-media.module';
import { AutomationModule } from './modules/automation/automation.module';
+import { TakeoverModule } from './modules/takeover/takeover.module';
import { CatalogModule } from './modules/catalog/catalog.module';
import { HooksModule } from './core/hooks';
import { PluginsModule } from './core/plugins';
@@ -300,6 +301,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
StatusStoreModule, // Phase 3: inbound status/story TTL store (24h purge + media persistence)
ChatMediaModule, // opt-in chat-media archive (retention purge + orphan sweep)
AutomationModule, // single-message autoreply rules, evaluated on the inbound dispatch
+ TakeoverModule, // adopts sessions whose holder's lease lapsed (crashed peer / recreated node)
CatalogModule, // Phase 3: Catalog API (WhatsApp Business)
PluginsApiModule, // Phase 5: Plugins API
AgentToolsModule, // Agent-invocable tool registry (protocol-neutral)
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 3aca09fd5..9d7ab60b1 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -417,6 +417,13 @@ export default () => ({
const n = parseInt(process.env.SESSION_LEASE_HEARTBEAT_MS ?? '', 10);
return Number.isFinite(n) && n > 0 ? n : 20_000;
})(),
+ // Takeover sweep cadence (default 30s): how often a node looks for sessions whose holder's
+ // lease has lapsed — a crashed peer, or this node's own previous identity after a container
+ // recreate — and starts them here. Gated by the AUTO_START_SESSIONS feature flag.
+ takeoverSweepMs: (() => {
+ const n = parseInt(process.env.SESSION_TAKEOVER_SWEEP_MS ?? '', 10);
+ return Number.isFinite(n) && n > 0 ? n : 30_000;
+ })(),
},
// Server-side media conversion (opt-in): transcodes caller-supplied audio and video into the
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index c7f075f20..df57f8437 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -108,6 +108,29 @@ describe('BulkMessageService.onApplicationBootstrap', () => {
expect(repo.save).not.toHaveBeenCalled();
});
+ /**
+ * The takeover path's reconcile: adopting a session from a lapsed node must fail THAT session's
+ * stuck batches (same no-auto-resume policy as boot — the dead node's already-sent messages are
+ * unknowable), scoped strictly to the one session, with inline media payloads stripped.
+ */
+ it('reapProcessingBatches fails only the given session’s PROCESSING batches and strips payloads', async () => {
+ const mine = {
+ id: 'b1',
+ sessionId: 'sess-a',
+ status: BatchStatus.PROCESSING,
+ messages: [{ content: { image: { base64: 'x'.repeat(64) } } }],
+ } as unknown as MessageBatch;
+ repo.find.mockResolvedValue([mine]);
+
+ const reaped = await service.reapProcessingBatches('sess-a', 'session adopted from a lapsed node');
+
+ expect(repo.find).toHaveBeenCalledWith({ where: { status: BatchStatus.PROCESSING, sessionId: 'sess-a' } });
+ expect(reaped).toBe(1);
+ expect(mine.status).toBe(BatchStatus.FAILED);
+ expect(repo.save).toHaveBeenCalledWith(mine);
+ expect(JSON.stringify(mine.messages)).not.toContain('x'.repeat(64));
+ });
+
/**
* A batch is only ever driven by the process holding its session's engine, so on a second replica
* "PROCESSING" does not mean "abandoned". Reaping a peer's batch tells the caller their send
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index ed91815a3..6fa64a7cb 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -123,9 +123,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
const processing = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING } });
const orphaned = await this.ownedByThisNode(processing);
for (const batch of orphaned) {
- batch.status = BatchStatus.FAILED;
- this.stripBatchMediaPayloads(batch.messages);
- await this.batchRepository.save(batch);
+ await this.failOrphanedBatch(batch);
}
if (orphaned.length > 0) {
this.logger.warn(
@@ -138,6 +136,29 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
}
+ private async failOrphanedBatch(batch: MessageBatch): Promise<void> {
+ batch.status = BatchStatus.FAILED;
+ this.stripBatchMediaPayloads(batch.messages);
+ await this.batchRepository.save(batch);
+ }
+
+ /**
+ * Fail a session's stuck PROCESSING batches after the session was adopted from a lapsed node.
+ * Same policy as the boot reaper and for the same reason: the dead node's already-sent messages
+ * are unknowable, so resuming risks double-sends — FAILED with the payloads stripped is the
+ * honest terminal state, and the caller can re-issue the batch knowingly.
+ */
+ async reapProcessingBatches(sessionId: string, reason: string): Promise<number> {
+ const processing = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING, sessionId } });
+ for (const batch of processing) {
+ await this.failOrphanedBatch(batch);
+ }
+ if (processing.length > 0) {
+ this.logger.warn(`Marked ${processing.length} PROCESSING batch(es) FAILED for session ${sessionId} (${reason})`);
+ }
+ return processing.length;
+ }
+
/**
* Narrow to the batches this process may act on. With no ownership service — a single-process
* deployment, or a directly-constructed unit test — every batch qualifies, which is the behaviour
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index fdf778b1a..cc527b988 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -303,6 +303,21 @@ describe('SessionOwnershipService', () => {
});
});
+ describe('lapsed sessions held by others (the takeover sweep feed)', () => {
+ it('returns only expired-lease rows held by ANOTHER node', async () => {
+ const past = new Date(Date.now() - 1000);
+ const future = new Date(Date.now() + 60_000);
+ const lapsedOther = await seed({ nodeId: 'dead-node', leaseExpiresAt: past });
+ await seed({ nodeId: 'live-node', leaseExpiresAt: future }); // live peer — not adoptable
+ await seed({ nodeId: 'me', leaseExpiresAt: past }); // own row — boot reset territory, not takeover
+ await seed({ nodeId: null }); // deliberately released (stop/shutdown) — not adoptable
+
+ const lapsed = await service('me').lapsedHeldByOthers();
+
+ expect(lapsed.map(s => s.id)).toEqual([lapsedOther.id]);
+ });
+ });
+
describe('node identity', () => {
it('falls back to the hostname when nothing is configured, and never to the pid', () => {
const bare = new SessionOwnershipService(sessions);
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index ca74a7bdd..376a03a14 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -231,6 +231,20 @@ export class SessionOwnershipService {
return session.leaseExpiresAt != null && session.leaseExpiresAt > now;
}
+ /**
+ * Sessions another node held whose lease has lapsed — a crashed peer, or this node's own
+ * previous identity after a container recreate (the default nodeId is the hostname, which a
+ * recreate changes). These are the adoptable orphans the takeover sweep starts here; a
+ * deliberately released session (stop, graceful shutdown) has `nodeId` NULL and is not one.
+ */
+ async lapsedHeldByOthers(now = new Date()): Promise<Session[]> {
+ return this.sessions
+ .createQueryBuilder('session')
+ .where('"nodeId" IS NOT NULL AND "nodeId" <> :me', { me: this.nodeId })
+ .andWhere('"leaseExpiresAt" < :now', { now: leaseParam(now) })
+ .getMany();
+ }
+
/**
* Session ids another node currently holds on a live lease.
*
diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.ts
new file mode 100644
index 000000000..234cb4757
--- /dev/null
+++ b/src/modules/takeover/session-takeover.service.spec.ts
@@ -0,0 +1,149 @@
+import { ConflictException } from '@nestjs/common';
+import { SessionTakeoverService } from './session-takeover.service';
+import { Session, SessionStatus } from '../session/entities/session.entity';
+import type { SessionService } from '../session/session.service';
+import type { SessionOwnershipService } from '../session/session-ownership.service';
+import type { BulkMessageService } from '../message/bulk-message.service';
+import type { ConfigService } from '@nestjs/config';
+
+/**
+ * The sweep is the retry that boot auto-start never had: both live incidents (a container recreate
+ * landing inside the old identity's lease, and a crashed peer) left sessions sitting disconnected
+ * until a manual POST /start. What has to hold: only lapsed-lease sessions worth resuming are
+ * started, a lost claim race is a non-event, and adopting a session reconciles its stuck batches.
+ */
+describe('SessionTakeoverService', () => {
+ const lapsed = (over: Partial<Session> = {}): Session =>
+ ({
+ id: `id-${over.name ?? 'x'}`,
+ name: 'x',
+ status: SessionStatus.READY,
+ phone: '628123',
+ nodeId: 'dead-node',
+ ...over,
+ }) as Session;
+
+ const build = (
+ rows: Session[],
+ opts: { autoStart?: boolean; startImpl?: jest.Mock } = {},
+ ): { svc: SessionTakeoverService; start: jest.Mock; reap: jest.Mock } => {
+ const start = opts.startImpl ?? jest.fn().mockResolvedValue({});
+ const reap = jest.fn().mockResolvedValue(0);
+ const config = {
+ get: (key: string, def?: unknown) =>
+ ({
+ features: { autoStartSessions: opts.autoStart ?? true },
+ 'session.takeoverSweepMs': 30_000,
+ })[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,
+ { reapProcessingBatches: reap } as unknown as BulkMessageService,
+ config,
+ );
+ return { svc, start, reap };
+ };
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('adopts a lapsed authenticated session and reconciles its stuck batches', async () => {
+ const { svc, start, reap } = build([lapsed({ name: 'a' })]);
+
+ await svc.sweep();
+
+ expect(start).toHaveBeenCalledWith('id-a');
+ expect(reap).toHaveBeenCalledWith('id-a', expect.stringContaining('lapsed'));
+ });
+
+ it('skips sessions not worth resuming: unauthenticated, mid-pairing, or operator-flagged failed', async () => {
+ const { svc, start } = build([
+ lapsed({ name: 'no-phone', phone: undefined as unknown as string }),
+ lapsed({ name: 'pairing', status: SessionStatus.QR_READY }),
+ lapsed({ name: 'failed', status: SessionStatus.FAILED }),
+ ]);
+
+ await svc.sweep();
+
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it('a lost claim race is a non-event: no batch reconcile, and the next candidate still starts', async () => {
+ jest.useFakeTimers();
+ const start = jest.fn().mockRejectedValueOnce(new ConflictException('held elsewhere')).mockResolvedValueOnce({});
+ const { svc, reap } = build([lapsed({ name: 'raced' }), lapsed({ name: 'ours' })], { startImpl: start });
+
+ const sweep = svc.sweep();
+ await jest.advanceTimersByTimeAsync(2100); // the inter-launch stagger
+ await sweep;
+
+ expect(start).toHaveBeenCalledTimes(2);
+ expect(reap).toHaveBeenCalledTimes(1);
+ expect(reap).toHaveBeenCalledWith('id-ours', expect.any(String));
+ });
+
+ it('a non-conflict start failure is logged and does not abort the rest of the sweep', async () => {
+ jest.useFakeTimers();
+ const start = jest.fn().mockRejectedValueOnce(new Error('chromium died')).mockResolvedValueOnce({});
+ const { svc } = build([lapsed({ name: 'boom' }), lapsed({ name: 'fine' })], { startImpl: start });
+
+ const sweep = svc.sweep();
+ await jest.advanceTimersByTimeAsync(2100);
+ await expect(sweep).resolves.toBeUndefined();
+
+ expect(start).toHaveBeenCalledTimes(2);
+ });
+
+ it('the AUTO_START_SESSIONS opt-out disables the sweep timer entirely', () => {
+ jest.useFakeTimers();
+ const { svc } = build([], { autoStart: false });
+
+ svc.onApplicationBootstrap();
+
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it('arms the timer when auto-start is on, and tears it down on destroy', () => {
+ jest.useFakeTimers();
+ const { svc } = build([]);
+
+ svc.onApplicationBootstrap();
+ expect(jest.getTimerCount()).toBe(1);
+
+ svc.onModuleDestroy();
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it('never stacks sweeps: a tick that fires while one is in flight is skipped', async () => {
+ jest.useFakeTimers();
+ let resolveFirst: () => void = () => undefined;
+ const start = jest.fn().mockImplementation(
+ () =>
+ new Promise<void>(resolve => {
+ resolveFirst = resolve;
+ }),
+ );
+ const ownershipCalls = jest.fn().mockResolvedValue([lapsed({ name: 'slow' })]);
+ const config = {
+ get: (key: string, def?: unknown) =>
+ ({ 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,
+ { reapProcessingBatches: jest.fn().mockResolvedValue(0) } as unknown as BulkMessageService,
+ config,
+ );
+
+ svc.onApplicationBootstrap();
+ await jest.advanceTimersByTimeAsync(1000); // tick 1: sweep starts, hangs in start()
+ await jest.advanceTimersByTimeAsync(2000); // ticks 2-3 fire while it is in flight
+
+ expect(ownershipCalls).toHaveBeenCalledTimes(1);
+
+ resolveFirst();
+ svc.onModuleDestroy();
+ });
+});
diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.ts
new file mode 100644
index 000000000..599b162a5
--- /dev/null
+++ b/src/modules/takeover/session-takeover.service.ts
@@ -0,0 +1,125 @@
+import { ConflictException, Injectable, OnApplicationBootstrap, OnModuleDestroy, Optional } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { createLogger } from '../../common/services/logger.service';
+import { resolveFeatureFlags } from '../../config/feature-flags';
+import { Session, SessionStatus } from '../session/entities/session.entity';
+import { SessionOwnershipService } from '../session/session-ownership.service';
+import { SessionService } from '../session/session.service';
+import { BulkMessageService } from '../message/bulk-message.service';
+
+/**
+ * Statuses worth adopting from a lapsed node. They all mean "an engine was (or should be) running".
+ * QR_READY is deliberately absent — an unpaired session on a dead node has nothing to resume, and
+ * restarting it elsewhere just renders a QR nobody asked for. FAILED is deliberately absent too:
+ * it marks a session an operator must look at, and silently relocating it would hide that.
+ */
+const TAKEOVER_STATUSES = new Set<SessionStatus>([
+ SessionStatus.READY,
+ SessionStatus.INITIALIZING,
+ SessionStatus.AUTHENTICATING,
+ SessionStatus.ACTION_REQUIRED,
+ SessionStatus.DISCONNECTED,
+]);
+
+/** Pause between successive engine launches, matching the boot auto-start's Chromium stagger. */
+const TAKEOVER_START_STAGGER_MS = 2000;
+
+/**
+ * Adopts sessions whose holder's lease has lapsed.
+ *
+ * Boot auto-start runs exactly once, so it misses two real cases, both observed live: a peer that
+ * crashes AFTER this node booted, and a container recreate whose new boot lands BEFORE the old
+ * identity's lease expires (the claim is correctly refused, and nothing ever retried — the session
+ * sat disconnected until someone called POST /start). This sweep is the retry: every tick it looks
+ * for lapsed-lease sessions and starts them here through the ordinary start path, so the claim
+ * stays race-safe against peers doing the same.
+ *
+ * Lives in its own module (not SessionModule) because adopting a session also reconciles its
+ * in-flight bulk batches via BulkMessageService — which sits in MessageModule, which imports
+ * SessionModule; importing it back from SessionModule would close the cycle.
+ */
+@Injectable()
+export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleDestroy {
+ private readonly logger = createLogger('SessionTakeoverService');
+ private sweepTimer?: ReturnType<typeof setInterval>;
+ private sweepInFlight = false;
+
+ constructor(
+ private readonly sessionService: SessionService,
+ private readonly ownership: SessionOwnershipService,
+ private readonly bulkMessages: BulkMessageService,
+ @Optional()
+ private readonly configService?: ConfigService,
+ ) {}
+
+ 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;
+ 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
+ // on top of the first — the claim would refuse, but the log noise and DB churn are pointless.
+ if (this.sweepInFlight) return;
+ this.sweepInFlight = true;
+ void this.sweep()
+ .catch(error =>
+ this.logger.warn('Takeover sweep failed', {
+ error: error instanceof Error ? error.message : String(error),
+ }),
+ )
+ .finally(() => {
+ this.sweepInFlight = false;
+ });
+ }, sweepMs);
+ this.sweepTimer.unref?.();
+ }
+
+ onModuleDestroy(): void {
+ if (this.sweepTimer) {
+ clearInterval(this.sweepTimer);
+ this.sweepTimer = undefined;
+ }
+ }
+
+ /** One pass: adopt every eligible lapsed session. Exposed for the spec; the timer drives it. */
+ async sweep(): Promise<void> {
+ const lapsed = await this.ownership.lapsedHeldByOthers();
+ const eligible = lapsed.filter(session => this.isEligible(session));
+ if (eligible.length === 0) return;
+
+ for (let i = 0; i < eligible.length; i++) {
+ const session = eligible[i];
+ try {
+ await this.sessionService.start(session.id);
+ this.logger.log(`Adopted session ${session.name} from lapsed node ${session.nodeId ?? '?'}`, {
+ sessionId: session.id,
+ fromNode: session.nodeId,
+ action: 'session_takeover',
+ });
+ // The dead node's in-flight batches can never complete; surface them as FAILED now rather
+ // than leaving them stuck in PROCESSING until some node happens to reboot.
+ await this.bulkMessages.reapProcessingBatches(session.id, 'session adopted from a lapsed node');
+ } catch (error) {
+ if (error instanceof ConflictException) {
+ // A peer won the race — exactly the claim doing its job.
+ this.logger.debug(`Session ${session.name} was adopted by another node first`, { sessionId: session.id });
+ } else {
+ this.logger.warn(`Takeover start failed for session ${session.name}`, {
+ sessionId: session.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (i < eligible.length - 1) {
+ await new Promise(resolve => setTimeout(resolve, TAKEOVER_START_STAGGER_MS));
+ }
+ }
+ }
+
+ private isEligible(session: Session): boolean {
+ // Only authenticated sessions (phone set): an engine is worth relaunching exactly when the
+ // saved credentials can restore the link without a human scanning anything.
+ return Boolean(session.phone) && TAKEOVER_STATUSES.has(session.status);
+ }
+}
diff --git a/src/modules/takeover/takeover.module.ts b/src/modules/takeover/takeover.module.ts
new file mode 100644
index 000000000..d8a73d584
--- /dev/null
+++ b/src/modules/takeover/takeover.module.ts
@@ -0,0 +1,15 @@
+import { Module } from '@nestjs/common';
+import { SessionModule } from '../session/session.module';
+import { MessageModule } from '../message/message.module';
+import { SessionTakeoverService } from './session-takeover.service';
+
+/**
+ * Sits ABOVE both SessionModule and MessageModule on purpose: the takeover sweep starts sessions
+ * (SessionService) and reconciles their bulk batches (BulkMessageService), and MessageModule
+ * already imports SessionModule — so this is the lowest place both are reachable without a cycle.
+ */
+@Module({
+ imports: [SessionModule, MessageModule],
+ providers: [SessionTakeoverService],
+})
+export class TakeoverModule {}