Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(takeover): stop the sweep during the drain, not only at module destruction
Yudhi Armyndharis5ba9ba5e5703
diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.tsindex f7d915234..b1381cbb8 100644--- a/src/modules/takeover/session-takeover.service.spec.ts+++ b/src/modules/takeover/session-takeover.service.spec.ts@@ -5,6 +5,7 @@ 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';+import type { ShutdownService } from '../../common/services/shutdown.service';/*** The sweep is the retry that boot auto-start never had: both live incidents (a container recreate@@ -198,6 +199,37 @@ describe('SessionTakeoverService', () => {* that never queries proves the entry guard fired. That also matters on its own — a sweep entered* during shutdown otherwise still hits the database on every remaining tick.*/+ /**+ * `onModuleDestroy` runs at `app.close()` — AFTER the bounded drain. On SIGTERM main.ts flips+ * readiness to 503 and waits SHUTDOWN_DELAY_MS first, and throughout that window the sweep timer is+ * still armed while the local flag is still false: a tick can launch Chromium and claim an+ * ownership lease for a process that is about to exit, which is the rolling-restart case this+ * guard exists for. Two siblings in this repo already consult ShutdownService for exactly that —+ * session-engine-lifecycle and the liveness watchdog.+ */+ it('does not adopt during the drain window, before onModuleDestroy runs', async () => {+ const ownershipCalls = jest.fn().mockResolvedValue([lapsed({ name: 'any' })]);+ const start = jest.fn().mockResolvedValue(undefined);+ 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,+ { isShuttingDown: () => true } as unknown as ShutdownService,+ );++ // Deliberately NOT calling onModuleDestroy: this is the drain window, where the signal has+ // arrived but Nest has not torn the module down yet.+ await svc.sweep();++ expect(ownershipCalls).not.toHaveBeenCalled();+ expect(start).not.toHaveBeenCalled();+ });+it('a sweep entered during shutdown does not even query ownership', async () => {const ownershipCalls = jest.fn().mockResolvedValue([lapsed({ name: 'any' })]);const config = {diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.tsindex eda8dbd86..be8625db0 100644--- a/src/modules/takeover/session-takeover.service.ts+++ b/src/modules/takeover/session-takeover.service.ts@@ -4,6 +4,7 @@ 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 { ShutdownService } from '../../common/services/shutdown.service';import { SessionService } from '../session/session.service';import { BulkMessageService } from '../message/bulk-message.service';@@ -58,8 +59,19 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleDprivate readonly bulkMessages: BulkMessageService,@Optional()private readonly configService?: ConfigService,+ // The drain signal, not module destruction. `onModuleDestroy` runs at app.close(), AFTER the+ // bounded shutdown delay — throughout that window the timer is still armed, so without this a+ // tick could launch an engine and claim an ownership lease for a process about to exit. Same+ // source session-engine-lifecycle and the liveness watchdog already consult.+ @Optional()+ private readonly shutdownService?: ShutdownService,) {}+ /** True once EITHER the drain has begun or Nest has torn this module down. */+ private get stopping(): boolean {+ return this.shuttingDown || this.shutdownService?.isShuttingDown() === true;+ }+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.@@ -93,7 +105,7 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD/** One pass: adopt every eligible lapsed session. Exposed for the spec; the timer drives it. */async sweep(): Promise<void> {- if (this.shuttingDown) return;+ if (this.stopping) return;const lapsed = await this.ownership.lapsedHeldByOthers();const eligible = lapsed.filter(session => this.isEligible(session));if (eligible.length === 0) return;@@ -103,7 +115,7 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD// Re-checked per iteration, not just at entry: each adoption costs a browser launch plus a// stagger, so the loop spans a large part of the sweep interval and shutdown can begin partway// through. Everything already adopted is left to the normal teardown; nothing further starts.- if (this.shuttingDown) return;+ if (this.stopping) return;try {await this.sessionService.start(session.id);this.logger.log(`Adopted session ${session.name} from lapsed node ${session.nodeId ?? '?'}`, {