Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(session): extract SessionLivenessWatchdog

Yudhi Armyndharise18d174f6908
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index 8833a5f92..ad63ac92a 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -9,6 +9,7 @@ import { Message } from '../message/entities/message.entity';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { SessionLidResolver } from './session-lid-resolver.service';
+import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
@@ -94,6 +95,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {
// Real registry: this suite asserts on engine map state across the teardown fence.
EngineRegistry,
SessionLidResolver,
+ SessionLivenessWatchdog,
{
provide: EventsGateway,
useValue: { emitSessionStatus: jest.fn(), emitSessionDisconnected: jest.fn(), emitQRCode: jest.fn() },
diff --git a/src/modules/session/session-liveness-watchdog.service.spec.ts b/src/modules/session/session-liveness-watchdog.service.spec.ts
new file mode 100644
index 000000000..cecd4cc51
--- /dev/null
+++ b/src/modules/session/session-liveness-watchdog.service.spec.ts
@@ -0,0 +1,292 @@
+import {
+ SessionLivenessWatchdog,
+ SESSION_WATCHDOG_INTERVAL_MS,
+ SESSION_WATCHDOG_MAX_FAILURES,
+ SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
+} from './session-liveness-watchdog.service';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { EngineStatus, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { ShutdownService } from '../../common/services/shutdown.service';
+
+type FakeEngine = {
+ getStatus: jest.Mock;
+ probeLiveness?: jest.Mock;
+};
+
+const engineOf = (status: EngineStatus, probe?: jest.Mock): FakeEngine => ({
+ getStatus: jest.fn().mockReturnValue(status),
+ ...(probe ? { probeLiveness: probe } : {}),
+});
+
+describe('SessionLivenessWatchdog', () => {
+ let engines: EngineRegistry;
+ let onDead: jest.Mock;
+ let watchdog: SessionLivenessWatchdog;
+
+ const failuresOf = (w: SessionLivenessWatchdog): Map<string, number> =>
+ (w as unknown as { failures: Map<string, number> }).failures;
+
+ beforeEach(() => {
+ engines = new EngineRegistry();
+ onDead = jest.fn().mockResolvedValue(undefined);
+ watchdog = new SessionLivenessWatchdog(engines);
+ });
+
+ afterEach(() => {
+ watchdog.stop();
+ });
+
+ describe('probe eligibility', () => {
+ it('treats a READY engine that answers as alive', async () => {
+ const probe = jest.fn().mockResolvedValue(true);
+ const engine = engineOf(EngineStatus.READY, probe);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(probe).toHaveBeenCalled();
+ expect(onDead).not.toHaveBeenCalled();
+ });
+
+ it('skips a non-READY engine entirely (owned by the QR/reconnect flows)', async () => {
+ const probe = jest.fn().mockResolvedValue(false);
+ const engine = engineOf(EngineStatus.INITIALIZING, probe);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(probe).not.toHaveBeenCalled();
+ });
+
+ it('clears failures accrued in a previous READY stretch when the status leaves READY', async () => {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ expect(failuresOf(watchdog).get('s1')).toBe(1);
+
+ engine.getStatus.mockReturnValue(EngineStatus.DISCONNECTED);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(failuresOf(watchdog).has('s1')).toBe(false);
+ });
+
+ it('skips an engine without probeLiveness (relies on engine events alone)', async () => {
+ const engine = engineOf(EngineStatus.READY);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(onDead).not.toHaveBeenCalled();
+ expect(failuresOf(watchdog).has('s1')).toBe(false);
+ });
+ });
+
+ describe('failure threshold', () => {
+ it(`treats the session as dead after ${SESSION_WATCHDOG_MAX_FAILURES} consecutive failures`, async () => {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ for (let i = 0; i < SESSION_WATCHDOG_MAX_FAILURES; i++) {
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ }
+
+ expect(onDead).toHaveBeenCalledTimes(1);
+ expect(onDead).toHaveBeenCalledWith('s1', engine, 'liveness probe failed (watchdog)');
+ });
+
+ it('does not act on a single failure', async () => {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(onDead).not.toHaveBeenCalled();
+ expect(failuresOf(watchdog).get('s1')).toBe(1);
+ });
+
+ it('resets the streak on a successful probe, so failures must be CONSECUTIVE', async () => {
+ const probe = jest.fn().mockResolvedValue(false);
+ const engine = engineOf(EngineStatus.READY, probe);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ probe.mockResolvedValue(true);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ probe.mockResolvedValue(false);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(onDead).not.toHaveBeenCalled();
+ });
+
+ it('counts a probe that rejects as a failure', async () => {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockRejectedValue(new Error('socket gone')));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(failuresOf(watchdog).get('s1')).toBe(1);
+ });
+
+ it('counts a hung probe as a failure once the deadline passes', async () => {
+ jest.useFakeTimers();
+ try {
+ // A wedged connection can hang the probe itself; without the race the tick would stall.
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockReturnValue(new Promise<boolean>(() => {})));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ const pending = watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_PROBE_TIMEOUT_MS);
+ await pending;
+
+ expect(failuresOf(watchdog).get('s1')).toBe(1);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+ });
+
+ describe('ACTION_REQUIRED is observe-only', () => {
+ it('probes the engine but never acts on a failure (the status is operator-owned)', async () => {
+ const probe = jest.fn().mockResolvedValue(false);
+ const engine = engineOf(EngineStatus.ACTION_REQUIRED, probe);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ for (let i = 0; i < SESSION_WATCHDOG_MAX_FAILURES + 3; i++) {
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ }
+
+ expect(probe).toHaveBeenCalled();
+ // Acting here would silently drop the very status asking for attention.
+ expect(onDead).not.toHaveBeenCalled();
+ expect(failuresOf(watchdog).get('s1')).toBeGreaterThan(SESSION_WATCHDOG_MAX_FAILURES);
+ });
+
+ it('clears the observe-only count when the probe answers again', async () => {
+ const probe = jest.fn().mockResolvedValue(false);
+ const engine = engineOf(EngineStatus.ACTION_REQUIRED, probe);
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+ probe.mockResolvedValue(true);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(failuresOf(watchdog).has('s1')).toBe(false);
+ });
+ });
+
+ describe('stale results', () => {
+ it('ignores a probe result for an engine superseded while it was in flight', async () => {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+ failuresOf(watchdog).set('s1', SESSION_WATCHDOG_MAX_FAILURES - 1);
+
+ // A stop()/restart replaces the engine before the probe settles.
+ engines.set('s1', engineOf(EngineStatus.READY) as unknown as IWhatsAppEngine);
+ await watchdog.probe('s1', engine as unknown as IWhatsAppEngine);
+
+ expect(onDead).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('lifecycle', () => {
+ it('probes every live engine on each tick', async () => {
+ jest.useFakeTimers();
+ try {
+ const a = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(true));
+ const b = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(true));
+ engines.set('a', a as unknown as IWhatsAppEngine);
+ engines.set('b', b as unknown as IWhatsAppEngine);
+ watchdog.start(onDead);
+
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS);
+
+ expect(a.probeLiveness).toHaveBeenCalled();
+ expect(b.probeLiveness).toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('is idempotent: a second start does not add a second interval', () => {
+ jest.useFakeTimers();
+ try {
+ watchdog.start(onDead);
+ watchdog.start(onDead);
+
+ expect(jest.getTimerCount()).toBe(1);
+ } finally {
+ watchdog.stop();
+ jest.useRealTimers();
+ }
+ });
+
+ it('stop() clears the interval and the accrued failures, and is safe to call twice', () => {
+ jest.useFakeTimers();
+ try {
+ watchdog.start(onDead);
+ failuresOf(watchdog).set('s1', 1);
+
+ watchdog.stop();
+ watchdog.stop();
+
+ expect(jest.getTimerCount()).toBe(0);
+ expect(failuresOf(watchdog).size).toBe(0);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('skips the whole tick while shutting down (a reconnect would race teardown)', async () => {
+ jest.useFakeTimers();
+ const shutdown = { isShuttingDown: () => true } as unknown as ShutdownService;
+ const draining = new SessionLivenessWatchdog(engines, shutdown);
+ try {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ draining.start(onDead);
+
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS);
+
+ expect(engine.probeLiveness).not.toHaveBeenCalled();
+ } finally {
+ draining.stop();
+ jest.useRealTimers();
+ }
+ });
+
+ it('clear() forgets one session without disturbing another', () => {
+ failuresOf(watchdog).set('s1', 1);
+ failuresOf(watchdog).set('s2', 1);
+
+ watchdog.clear('s1');
+
+ expect(failuresOf(watchdog).has('s1')).toBe(false);
+ expect(failuresOf(watchdog).get('s2')).toBe(1);
+ });
+
+ it('a failing probe never throws into the timer', async () => {
+ jest.useFakeTimers();
+ try {
+ const engine = engineOf(EngineStatus.READY, jest.fn().mockResolvedValue(false));
+ engines.set('s1', engine as unknown as IWhatsAppEngine);
+ watchdog.start(() => Promise.reject(new Error('disconnect handler blew up')));
+
+ await expect(
+ jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * (SESSION_WATCHDOG_MAX_FAILURES + 1)),
+ ).resolves.not.toThrow();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+ });
+});
diff --git a/src/modules/session/session-liveness-watchdog.service.ts b/src/modules/session/session-liveness-watchdog.service.ts
new file mode 100644
index 000000000..00e69d485
--- /dev/null
+++ b/src/modules/session/session-liveness-watchdog.service.ts
@@ -0,0 +1,190 @@
+import { Injectable, Optional } from '@nestjs/common';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { EngineStatus, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import { createLogger } from '../../common/services/logger.service';
+import { ShutdownService } from '../../common/services/shutdown.service';
+
+/**
+ * Session liveness watchdog. The engine layer is event-driven, so an engine that dies WITHOUT
+ * emitting a disconnect (a killed Chromium, a silently wedged socket) would otherwise sit READY
+ * forever. This actively probes every live engine on an interval and, after repeated failures,
+ * hands the session to the caller's disconnect path.
+ *
+ * Split out of SessionService because it is a self-contained supervisor: one timer, one failure
+ * counter, and exactly one outward effect (`onDead`). Keeping it separate means the probe timeout,
+ * the failure threshold, and the observe-only ACTION_REQUIRED rules are testable with a fake clock
+ * instead of a live engine.
+ */
+@Injectable()
+export class SessionLivenessWatchdog {
+ private readonly logger = createLogger('SessionLivenessWatchdog');
+
+ /** Consecutive failed liveness probes per session id. Cleared on recovery or on a status change. */
+ private readonly failures = new Map<string, number>();
+ private timer: NodeJS.Timeout | null = null;
+
+ /** Invoked when a session has failed enough consecutive probes to be treated as disconnected. */
+ private onDead: (id: string, engine: IWhatsAppEngine, reason: string) => Promise<void> = () => Promise.resolve();
+
+ constructor(
+ private readonly engines: EngineRegistry,
+ @Optional()
+ private readonly shutdownService?: ShutdownService,
+ ) {}
+
+ /**
+ * Start the watchdog (idempotent). One unref'd interval probes every registered engine.
+ *
+ * @param onDead Called after MAX_FAILURES consecutive failures, to treat the session exactly like
+ * an engine-reported disconnect.
+ */
+ start(
+ onDead: (id: string, engine: IWhatsAppEngine, reason: string) => Promise<void>,
+ intervalMs = SESSION_WATCHDOG_INTERVAL_MS,
+ ): void {
+ this.onDead = onDead;
+ if (this.timer) return;
+ this.timer = setInterval(() => {
+ // allSettled inside the tick keeps a failing session from ever throwing into the timer.
+ void this.tick();
+ }, intervalMs);
+ // The watchdog must never keep the process alive on its own.
+ this.timer.unref();
+ }
+
+ /** Stop the watchdog and forget all accrued failures. */
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ this.failures.clear();
+ }
+
+ /** Forget a session's accrued failures (e.g. it just reported ready). */
+ clear(id: string): void {
+ this.failures.delete(id);
+ }
+
+ /** Probe all live engines in parallel; a slow/failed probe must not delay or abort the others. */
+ async tick(): Promise<void> {
+ // Mid-shutdown the disconnect path would schedule a reconnect racing onModuleDestroy's teardown
+ // (same guard as scheduleReconnect) — leave the sessions to the drain instead.
+ if (this.shutdownService?.isShuttingDown()) {
+ return;
+ }
+ await Promise.allSettled([...this.engines].map(([id, engine]) => this.probe(id, engine)));
+ }
+
+ /**
+ * Actively probe one engine. Only READY sessions are expected to answer (anything else is owned by
+ * the QR/reconnect flows); engines without `probeLiveness` keep relying on engine events alone.
+ * MAX_FAILURES consecutive failures treat the session exactly like an engine-reported disconnect.
+ *
+ * ACTION_REQUIRED is probed too, but OBSERVE-ONLY: the engine is still running and a human has to
+ * act, and clearing that status is theirs to do (stop, then start). Acting on a failed probe would
+ * hand the session to the reconnect path and silently drop the very status that asked for
+ * attention — so the probe result only reaches the log. Without probing at all, a page that dies
+ * while waiting for the operator left no trace anywhere, which is what this closes.
+ */
+ async probe(id: string, engine: IWhatsAppEngine): Promise<void> {
+ const status = engine.getStatus();
+ const observeOnly = status === EngineStatus.ACTION_REQUIRED;
+ if (status !== EngineStatus.READY && !observeOnly) {
+ // Not expected to answer right now — and any accrued failures belong to a previous READY
+ // stretch, so the next one starts clean. This also self-cleans the observe-only counter below:
+ // every path out of ACTION_REQUIRED passes through a status that lands here (or through
+ // onReady, which clears it), so an observe-only count can never be inherited by a READY
+ // stretch and push it over MAX_FAILURES early.
+ this.failures.delete(id);
+ return;
+ }
+ // Feature-detect: an engine whose transport already self-detects death may skip the probe.
+ if (typeof engine.probeLiveness !== 'function') {
+ return;
+ }
+
+ // A wedged connection can hang the probe itself, so race it against a timeout; a timeout or a
+ // probe error both count as "not proven alive".
+ let alive: boolean;
+ let probeTimer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ alive = await Promise.race([
+ engine.probeLiveness(),
+ new Promise<never>((_, reject) => {
+ probeTimer = setTimeout(
+ () => reject(new Error('liveness probe timed out')),
+ SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } catch {
+ alive = false;
+ } finally {
+ if (probeTimer) clearTimeout(probeTimer);
+ }
+
+ // The session may have been stopped/restarted (engine superseded) while the probe was in flight;
+ // a stale result must not touch it (mirrors the isLive gate on engine callbacks).
+ if (!this.engines.isLive(id, engine)) {
+ return;
+ }
+
+ if (alive) {
+ // Note a recovery on the observe-only path, so the log shows the page came back rather than
+ // leaving the earlier warning as the last word.
+ if (observeOnly && this.failures.has(id)) {
+ this.logger.log('Liveness probe answering again while the session awaits operator action', {
+ sessionId: id,
+ action: 'watchdog_probe_recovered',
+ });
+ }
+ this.failures.delete(id);
+ return;
+ }
+
+ const failures = (this.failures.get(id) ?? 0) + 1;
+ if (observeOnly) {
+ this.failures.set(id, failures);
+ // One warning per unresponsive stretch, not one per tick: a session can sit in
+ // ACTION_REQUIRED until a human gets to it, and at a 60s interval an unbounded log would bury
+ // everything else. The count keeps rising so the recovery branch above can tell it happened.
+ if (failures === 1) {
+ this.logger.warn(
+ 'Liveness probe failed while the session awaits operator action; not reconnecting it — ' +
+ 'the status is operator-owned. If the page is gone, stop and start the session.',
+ { sessionId: id, action: 'watchdog_probe_failed_observe_only' },
+ );
+ }
+ return;
+ }
+
+ if (failures < SESSION_WATCHDOG_MAX_FAILURES) {
+ this.failures.set(id, failures);
+ this.logger.warn('Liveness probe failed; will treat the session as dead after repeated failures', {
+ sessionId: id,
+ failures,
+ action: 'watchdog_probe_failed',
+ });
+ return;
+ }
+
+ this.failures.delete(id);
+ this.logger.warn('Liveness probe failed repeatedly; handling the session as disconnected', {
+ sessionId: id,
+ failures,
+ action: 'watchdog_disconnect',
+ });
+ await this.onDead(id, engine, 'liveness probe failed (watchdog)');
+ }
+}
+
+/**
+ * Session liveness watchdog cadence. The engine layer is event-driven, so an engine that dies
+ * WITHOUT emitting a disconnect would otherwise sit READY forever.
+ */
+export const SESSION_WATCHDOG_INTERVAL_MS = 60_000;
+/** A wedged connection can hang the probe itself, so each probe is raced against this deadline. */
+export const SESSION_WATCHDOG_PROBE_TIMEOUT_MS = 15_000;
+/** Consecutive failed probes before a session is treated as disconnected. */
+export const SESSION_WATCHDOG_MAX_FAILURES = 2;
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 063217211..2ad74532c 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -4,6 +4,7 @@ import { Session } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { SessionService } from './session.service';
import { SessionLidResolver } from './session-lid-resolver.service';
+import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { SessionController } from './session.controller';
import { WebhookModule } from '../webhook/webhook.module';
import { StatusStoreModule } from '../status-store/status-store.module';
@@ -13,7 +14,7 @@ import { StatusStoreModule } from '../status-store/status-store.module';
// one-directional — no forwardRef() needed.
imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule],
controllers: [SessionController],
- providers: [SessionService, SessionLidResolver],
+ providers: [SessionService, SessionLidResolver, SessionLivenessWatchdog],
exports: [SessionService],
})
export class SessionModule {}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index d532d4185..6c291d674 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -27,6 +27,7 @@ import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
import type { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import { SessionLidResolver } from './session-lid-resolver.service';
+import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
@@ -205,6 +206,7 @@ describe('SessionService', () => {
// exactly what the stale-callback tests below exercise. Its own unit tests cover it directly.
EngineRegistry,
SessionLidResolver,
+ SessionLivenessWatchdog,
{ provide: EventsGateway, useValue: eventsGateway },
{ provide: WebhookService, useValue: webhookService },
{ provide: HookManager, useValue: hookManager },
@@ -1637,11 +1639,14 @@ describe('SessionService', () => {
string,
{ attempts: number; timer: NodeJS.Timeout | null; maxAttempts: number; baseDelay: number }
>;
- livenessFailures: Map<string, number>;
- watchdogTimer: NodeJS.Timeout | null;
+ // The probe cadence and failure counting now live in SessionLivenessWatchdog; these tests
+ // still drive them end-to-end through SessionService, so they reach the collaborator's state
+ // rather than the service's own.
+ watchdog: { failures: Map<string, number>; timer: NodeJS.Timeout | null };
scheduleReconnect: (id: string, session: Session) => void;
};
const internals = (): WatchdogInternals => service as unknown as WatchdogInternals;
+ const livenessFailures = (): Map<string, number> => internals().watchdog.failures;
// Auto-start is OFF in these tests — the watchdog must start regardless.
const originalFlag = process.env.AUTO_START_SESSIONS;
@@ -1790,7 +1795,7 @@ describe('SessionService', () => {
expect.objectContaining({ status: SessionStatus.DISCONNECTED }),
);
// The count keeps rising so a later recovery can be distinguished from "never failed".
- expect(internals().livenessFailures.get('sess-uuid-1')).toBeGreaterThan(SESSION_WATCHDOG_MAX_FAILURES);
+ expect(livenessFailures().get('sess-uuid-1')).toBeGreaterThan(SESSION_WATCHDOG_MAX_FAILURES);
} finally {
jest.clearAllTimers();
jest.useRealTimers();
@@ -1807,8 +1812,10 @@ describe('SessionService', () => {
probeLiveness: jest.fn().mockResolvedValue(false),
};
seedReadySession(engine);
+ // The observe-only warning is emitted by the watchdog collaborator, which carries its own
+ // logger; the behaviour under test (one warning per stretch) is unchanged.
const warnSpy = jest.spyOn(
- (service as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger,
+ (internals().watchdog as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger,
'warn',
);
@@ -1839,12 +1846,12 @@ describe('SessionService', () => {
await service.onApplicationBootstrap();
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS); // tick 1: probe hangs
- expect(internals().livenessFailures.get('sess-uuid-1')).toBeUndefined(); // not counted yet
+ expect(livenessFailures().get('sess-uuid-1')).toBeUndefined(); // not counted yet
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_PROBE_TIMEOUT_MS); // 15s → timeout failure
- expect(internals().livenessFailures.get('sess-uuid-1')).toBe(1);
+ expect(livenessFailures().get('sess-uuid-1')).toBe(1);
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS); // tick 2: success
- expect(internals().livenessFailures.get('sess-uuid-1')).toBeUndefined(); // counter reset
+ expect(livenessFailures().get('sess-uuid-1')).toBeUndefined(); // counter reset
} finally {
jest.clearAllTimers();
jest.useRealTimers();
@@ -1855,11 +1862,11 @@ describe('SessionService', () => {
jest.useFakeTimers();
try {
await service.onApplicationBootstrap();
- expect(internals().watchdogTimer).not.toBeNull();
+ expect(internals().watchdog.timer).not.toBeNull();
expect(jest.getTimerCount()).toBe(1); // the interval itself
await service.onModuleDestroy();
- expect(internals().watchdogTimer).toBeNull();
+ expect(internals().watchdog.timer).toBeNull();
expect(jest.getTimerCount()).toBe(0);
await expect(service.onModuleDestroy()).resolves.toBeUndefined(); // safe to call twice
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 5c271e905..6be3ff59b 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -27,6 +27,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';
import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import { decideReconnect, clampReconnectDelay, type ReconnectAttemptState } from './reconnect-policy';
import { SessionLidResolver } from './session-lid-resolver.service';
+import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
@@ -84,16 +85,6 @@ interface ReconnectState extends ReconnectAttemptState {
const RECONNECT_BASE_DELAY_MIN_MS = 1000;
const RECONNECT_BASE_DELAY_MAX_MS = 300_000;
const RECONNECT_MAX_ATTEMPTS_CAP = 20;
-/**
- * Session liveness watchdog. The engine layer is event-driven, so an engine that dies WITHOUT
- * firing an event (a silent Chromium crash) is never noticed: the row sits READY forever and never
- * reconnects. Every INTERVAL the watchdog actively probes each READY engine (feature-detected
- * `probeLiveness`, raced against TIMEOUT); MAX_FAILURES consecutive failures route the session
- * through the exact engine-disconnect path.
- */
-export const SESSION_WATCHDOG_INTERVAL_MS = 60_000;
-export const SESSION_WATCHDOG_PROBE_TIMEOUT_MS = 15_000;
-export const SESSION_WATCHDOG_MAX_FAILURES = 2;
/**
* Delay before retrying an ack UPDATE that matched 0 rows. A fast delivered/read ack can arrive before
* the send's 2nd save (which writes waMessageId) has committed, so the first UPDATE finds no row. One
@@ -124,6 +115,11 @@ export function resolveReconnectConfig(
}
export { clampReconnectDelay };
+export {
+ SESSION_WATCHDOG_INTERVAL_MS,
+ SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
+ SESSION_WATCHDOG_MAX_FAILURES,
+} from './session-liveness-watchdog.service';
export function resolveMaxConcurrentSessions(configService?: Pick<ConfigService, 'get'>): number | null {
const configured = configService?.get<number>('sessions.maxConcurrent', 0) ?? 0;
@@ -182,14 +178,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Reconnection state per session
private reconnectStates: Map<string, ReconnectState> = new Map();
- // Consecutive liveness-probe failures per session (watchdog). Reset on a successful probe, on a
- // non-READY tick, on onReady, and when the threshold routes the session to the disconnect path.
- private readonly livenessFailures = new Map<string, number>();
-
- // The single watchdog interval handle. Unref'd so it never keeps the process alive on its own;
- // cleared (and nulled) in onModuleDestroy, so teardown stays idempotent.
- private watchdogTimer: NodeJS.Timeout | null = null;
-
// 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().
@@ -265,6 +253,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly engineFactory: EngineFactory,
private readonly engineRegistry: EngineRegistry,
private readonly lidResolver: SessionLidResolver,
+ private readonly watchdog: SessionLivenessWatchdog,
private readonly eventsGateway: EventsGateway,
private readonly webhookService: WebhookService,
private readonly hookManager: HookManager,
@@ -307,7 +296,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async onApplicationBootstrap(): Promise<void> {
// Start the liveness watchdog FIRST: it must run even when auto-start is disabled (sessions can
// be started via the API at any time), so it can't sit behind the auto-start early-return below.
- this.startWatchdog();
+ // The watchdog owns the probe cadence and failure counting; a session it proves dead comes
+ // back through the same disconnect path an engine-reported drop uses.
+ this.watchdog.start((id, engine, reason) => this.handleEngineDisconnected(id, engine, reason));
if (!resolveFeatureFlags(this.configService).autoStartSessions) return;
@@ -346,12 +337,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async onModuleDestroy(): Promise<void> {
// Stop the watchdog FIRST (before any teardown below can hang): no new probe/disconnect handling
- // may start mid-shutdown. Nulling the handle keeps a second onModuleDestroy call safe.
- if (this.watchdogTimer) {
- clearInterval(this.watchdogTimer);
- this.watchdogTimer = null;
- }
- this.livenessFailures.clear();
+ // may start mid-shutdown. stop() is idempotent, so a second onModuleDestroy call stays safe.
+ this.watchdog.stop();
// Stop reconnect timers FIRST so nothing reschedules mid-teardown, and so this always runs even
// if an engine.destroy() below hangs or throws.
@@ -1187,7 +1174,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
reconnectState.attempts = 0;
}
// A fresh READY stretch starts the watchdog's failure budget clean too.
- this.livenessFailures.delete(id);
+ this.watchdog.clear(id);
this.sessionErrors.delete(id);
// READY proves any in-flight stuck-auth recovery succeeded (or none was needed), so the
// one-shot recovery budget is re-armed for a future episode.
@@ -2109,129 +2096,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.scheduleReconnect(id, session);
}
- /** Start the liveness watchdog (idempotent). One unref'd interval probes every registered engine. */
- private startWatchdog(): void {
- if (this.watchdogTimer) return;
- this.watchdogTimer = setInterval(() => {
- // allSettled inside the tick keeps a failing session from ever throwing into the timer.
- void this.runWatchdogTick();
- }, SESSION_WATCHDOG_INTERVAL_MS);
- // The watchdog must never keep the process alive on its own.
- this.watchdogTimer.unref();
- }
-
- /** Probe all live engines in parallel; a slow/failed probe must not delay or abort the others. */
- private async runWatchdogTick(): Promise<void> {
- // Mid-shutdown the disconnect path would schedule a reconnect racing onModuleDestroy's teardown
- // (same guard as scheduleReconnect) — leave the sessions to the drain instead.
- if (this.shutdownService?.isShuttingDown()) {
- return;
- }
- await Promise.allSettled([...this.engines].map(([id, engine]) => this.probeSessionLiveness(id, engine)));
- }
-
- /**
- * Actively probe one engine. Only READY sessions are expected to answer (anything else is owned by
- * the QR/reconnect flows); engines without `probeLiveness` keep relying on engine events alone.
- * MAX_FAILURES consecutive failures treat the session exactly like an engine-reported disconnect.
- *
- * ACTION_REQUIRED is probed too, but OBSERVE-ONLY: the engine is still running and a human has to
- * act, and clearing that status is theirs to do (stop, then start). Acting on a failed probe would
- * hand the session to the reconnect path and silently drop the very status that asked for
- * attention — so the probe result only reaches the log. Without probing at all, a page that dies
- * while waiting for the operator left no trace anywhere, which is what this closes.
- */
- private async probeSessionLiveness(id: string, engine: IWhatsAppEngine): Promise<void> {
- const status = engine.getStatus();
- const observeOnly = status === EngineStatus.ACTION_REQUIRED;
- if (status !== EngineStatus.READY && !observeOnly) {
- // Not expected to answer right now — and any accrued failures belong to a previous READY
- // stretch, so the next one starts clean. This also self-cleans the observe-only counter below:
- // every path out of ACTION_REQUIRED passes through a status that lands here (or through
- // onReady, which clears it), so an observe-only count can never be inherited by a READY
- // stretch and push it over MAX_FAILURES early.
- this.livenessFailures.delete(id);
- return;
- }
- // Feature-detect: an engine whose transport already self-detects death may skip the probe.
- if (typeof engine.probeLiveness !== 'function') {
- return;
- }
-
- // A wedged connection can hang the probe itself, so race it against a timeout; a timeout or a
- // probe error both count as "not proven alive".
- let alive: boolean;
- let probeTimer: ReturnType<typeof setTimeout> | undefined;
- try {
- alive = await Promise.race([
- engine.probeLiveness(),
- new Promise<never>((_, reject) => {
- probeTimer = setTimeout(
- () => reject(new Error('liveness probe timed out')),
- SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
- );
- }),
- ]);
- } catch {
- alive = false;
- } finally {
- if (probeTimer) clearTimeout(probeTimer);
- }
-
- // The session may have been stopped/restarted (engine superseded) while the probe was in flight;
- // a stale result must not touch it (mirrors the isLiveEngine gate on engine callbacks).
- if (!this.isLiveEngine(id, engine)) {
- return;
- }
-
- if (alive) {
- // Note a recovery on the observe-only path, so the log shows the page came back rather than
- // leaving the earlier warning as the last word.
- if (observeOnly && this.livenessFailures.has(id)) {
- this.logger.log('Liveness probe answering again while the session awaits operator action', {
- sessionId: id,
- action: 'watchdog_probe_recovered',
- });
- }
- this.livenessFailures.delete(id);
- return;
- }
-
- const failures = (this.livenessFailures.get(id) ?? 0) + 1;
- if (observeOnly) {
- this.livenessFailures.set(id, failures);
- // One warning per unresponsive stretch, not one per tick: a session can sit in
- // ACTION_REQUIRED until a human gets to it, and at a 60s interval an unbounded log would bury
- // everything else. The count keeps rising so the recovery branch above can tell it happened.
- if (failures === 1) {
- this.logger.warn(
- 'Liveness probe failed while the session awaits operator action; not reconnecting it — ' +
- 'the status is operator-owned. If the page is gone, stop and start the session.',
- { sessionId: id, action: 'watchdog_probe_failed_observe_only' },
- );
- }
- return;
- }
-
- if (failures < SESSION_WATCHDOG_MAX_FAILURES) {
- this.livenessFailures.set(id, failures);
- this.logger.warn('Liveness probe failed; will treat the session as dead after repeated failures', {
- sessionId: id,
- failures,
- action: 'watchdog_probe_failed',
- });
- return;
- }
-
- this.livenessFailures.delete(id);
- this.logger.warn('Liveness probe failed repeatedly; handling the session as disconnected', {
- sessionId: id,
- failures,
- action: 'watchdog_disconnect',
- });
- await this.handleEngineDisconnected(id, engine, 'liveness probe failed (watchdog)');
- }
-
private scheduleReconnect(id: string, session: Session): void {
// Don't launch a fresh engine (Chromium) mid-shutdown: a disconnect during the drain window would
// otherwise schedule a reconnect that races onModuleDestroy's teardown and could orphan a browser.