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 adopting sessions during shutdown
Yudhi Armyndharis967f30ab8a94
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ed83969c..816388658 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The cross-node takeover sweep no longer adopts sessions while the process is shutting down. `onModuleDestroy` cleared the interval, which stops the next sweep but does nothing about one already running — it is neither aborted nor awaited, and nothing on the start path consulted a shutting-down signal. On a rolling restart a sweep mid-flight could construct and register an engine after the shutdown path had emptied the registry, and claim the ownership lease for a process about to exit, pinning that session to a dead node until the lease lapsed. The signal is re-checked per adoption, because each one costs a browser launch and the loop spans much of the sweep interval.+- `GET /infra/storage/export` now enumerates the whole store. It listed with `listFiles()`, which stops at `STORAGE_LIST_MAX_FILES` and returns without logging or throwing, so an operator following the documented local→S3 migration — export, repoint `STORAGE_TYPE`, import — silently left media behind on the backend they were about to decommission, and the `files/count` pre-check was truncated by the same code path, so their own consistency check could not reveal it. The export now walks the uncapped `iterateFiles()`, which exists for exactly this: the cap is a per-call guard, not a completeness contract.- An ingress route whose manifest omits `maxBodyBytes` is no longer unbounded by its own cap. The check compared a byte length against `undefined`, which is always false, so the per-route 413 the published contract promises was silently inert — and every accepted delivery is persisted with the body stored twice and carried into the queue, turning one forgotten manifest field into a write amplifier with no load-time error and no runtime signal. A route with no usable value now falls back to the process-wide body limit (what it was already bounded by in practice, so nothing accepted today starts failing) and the gap is logged once per route instead of passing in silence.diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.tsindex 234cb4757..a78fcfde1 100644--- a/src/modules/takeover/session-takeover.service.spec.ts+++ b/src/modules/takeover/session-takeover.service.spec.ts@@ -49,6 +49,48 @@ describe('SessionTakeoverService', () => {jest.useRealTimers();});+ // onModuleDestroy only cleared the interval. A sweep already in flight was neither aborted nor+ // awaited, and neither sweep() nor the start path consulted any shutting-down signal — so on a+ // rolling restart an engine could be constructed and registered AFTER the shutdown path had torn+ // the registry down, and ownership.claim() could pin a session to a process that was exiting,+ // leaving it unclaimable by any peer until the lease lapsed.+ describe('a sweep racing shutdown', () => {+ it('adopts nothing once the module is being destroyed', async () => {+ const { svc, start, reap } = build([lapsed({ name: 'a' }), lapsed({ name: 'b' })]);++ svc.onModuleDestroy();+ await svc.sweep();++ expect(start).not.toHaveBeenCalled();+ expect(reap).not.toHaveBeenCalled();+ });++ it('stops adopting the rest of the batch when shutdown begins mid-sweep', async () => {+ const svcRef: { current?: { onModuleDestroy: () => void } } = {};+ const startImpl = jest.fn().mockImplementation(() => {+ svcRef.current?.onModuleDestroy(); // shutdown starts while the first adoption is in flight+ return Promise.resolve({});+ });+ const { svc, start } = build([lapsed({ name: 'a' }), lapsed({ name: 'b' }), lapsed({ name: 'c' })], {+ startImpl,+ });+ svcRef.current = svc;++ await svc.sweep();++ expect(start).toHaveBeenCalledTimes(1);+ });++ // Negative twin: an ordinary sweep must still adopt everything eligible.+ it('still adopts the whole batch when no shutdown is in progress', async () => {+ const { svc, start } = build([lapsed({ name: 'a' }), lapsed({ name: 'b' })]);++ await svc.sweep();++ expect(start).toHaveBeenCalledTimes(2);+ });+ });+it('adopts a lapsed authenticated session and reconciles its stuck batches', async () => {const { svc, start, reap } = build([lapsed({ name: 'a' })]);diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.tsindex 599b162a5..eda8dbd86 100644--- a/src/modules/takeover/session-takeover.service.ts+++ b/src/modules/takeover/session-takeover.service.ts@@ -43,6 +43,14 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleDprivate readonly logger = createLogger('SessionTakeoverService');private sweepTimer?: ReturnType<typeof setInterval>;private sweepInFlight = false;+ /**+ * Set by onModuleDestroy. Clearing the interval stops the NEXT sweep; it does nothing about one+ * already running, which is neither aborted nor awaited. Without this signal a sweep mid-flight+ * during a rolling restart could construct and register an engine after the shutdown path had+ * already emptied the registry — nothing would tear it down — and claim the ownership lease for a+ * process about to exit, pinning the session to a dead node until the lease lapsed.+ */+ private shuttingDown = false;constructor(private readonly sessionService: SessionService,@@ -76,6 +84,7 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD}onModuleDestroy(): void {+ this.shuttingDown = true;if (this.sweepTimer) {clearInterval(this.sweepTimer);this.sweepTimer = undefined;@@ -84,12 +93,17 @@ 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;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];+ // 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;try {await this.sessionService.start(session.id);this.logger.log(`Adopted session ${session.name} from lapsed node ${session.nodeId ?? '?'}`, {