Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(takeover): count pending relaunches against the session cap

Yudhi Armyndharis6fa447bb69f0
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 1299869b5..79a558a0d 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -33,9 +33,9 @@ import { SessionStatusBroadcaster } from './session-status-broadcaster';
// resulting import cycle is deferred-usage only — the bindings are read inside method bodies,
// never at module-eval time — which the CommonJS loader resolves safely.
import {
- isReconnectPending,
resolveMaxConcurrentSessions,
resolveReconnectConfig,
+ startSlotHolders,
type ReconnectState,
} from './session-engine-lifecycle.service';
@@ -211,8 +211,7 @@ export class SessionEngineControls {
// against the cap it is being checked against. A session waiting out a failed relaunch holds
// no engine (the attempt evicted it) but re-registers one when its timer fires, without a cap
// check of its own, so it keeps its slot here.
- const activeIds = new Set<string>(this.engines.activeIds());
- for (const [rid, state] of this.reconnectStates) if (isReconnectPending(state)) activeIds.add(rid);
+ const activeIds = startSlotHolders(this.engines, this.reconnectStates);
activeIds.delete(id);
if (activeIds.size >= maxConcurrentSessions) {
throw new BadRequestException(`Maximum concurrent sessions reached (${maxConcurrentSessions})`);
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 851dec115..f3e1484cd 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -107,6 +107,17 @@ export function isReconnectPending(state: ReconnectState): boolean {
return state.timer !== null || (state.attempts > 0 && state.readyAt === undefined);
}
+/**
+ * Sessions holding a MAX_CONCURRENT_SESSIONS slot: engines, init reservations and pending relaunches. A
+ * session waiting out a failed relaunch holds no engine, but re-registers one when its timer fires without
+ * a cap check of its own, so it keeps its slot.
+ */
+export function startSlotHolders(engines: EngineRegistry, reconnectStates: Map<string, ReconnectState>): Set<string> {
+ const ids = new Set<string>(engines.activeIds());
+ for (const [rid, state] of reconnectStates) if (isReconnectPending(state)) ids.add(rid);
+ return ids;
+}
+
export function resolveMaxConcurrentSessions(configService?: Pick<ConfigService, 'get'>): number | null {
const configured = configService?.get<number>('sessions.maxConcurrent', 0) ?? 0;
if (!Number.isFinite(configured) || configured <= 0) return null;
@@ -547,6 +558,11 @@ export class SessionEngineLifecycle {
return reconnect != null && isReconnectPending(reconnect);
}
+ /** Sessions holding a MAX_CONCURRENT_SESSIONS slot: engines, init reservations and pending relaunches. */
+ startSlotHolders(): Set<string> {
+ return startSlotHolders(this.engines, this.reconnectStates);
+ }
+
/** Whether the last READY stretch lasted STABLE_READY_MS, measured to where it ended (or to now). */
private readyStretchHeld(state: ReconnectState): boolean {
return state.readyAt !== undefined && (state.readyEndedAt ?? Date.now()) - state.readyAt >= STABLE_READY_MS;
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 06be02841..9c2a970a4 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1910,6 +1910,41 @@ describe('SessionService', () => {
expect(lifecycle.isEngineActive('x')).toBe(false);
});
+ it('a session waiting out a relaunch holds a start slot; a dormant reconnect entry does not', () => {
+ const intern = lifecycle as unknown as { reconnectStates: Map<string, unknown> };
+ const timer = setTimeout(() => undefined, 60_000);
+ try {
+ intern.reconnectStates.set('waiting', { attempts: 1, timer });
+ intern.reconnectStates.set('dormant', { attempts: 0, timer: null });
+
+ expect([...lifecycle.startSlotHolders()]).toEqual(['waiting']);
+ } finally {
+ clearTimeout(timer);
+ intern.reconnectStates.clear();
+ }
+ });
+
+ // The takeover sweep asks this before adopting a lapsed session: counting engines alone let it
+ // call start() at the cap, and the refused start released the claimed lease to no node.
+ it('hasStartCapacity counts a pending relaunch with no engine against the cap', () => {
+ const intern = lifecycle as unknown as {
+ engines: { set: (id: string, e: unknown) => void; delete: (id: string) => void };
+ reconnectStates: Map<string, unknown>;
+ };
+ const timer = setTimeout(() => undefined, 60_000);
+ try {
+ intern.engines.set('running', {});
+ intern.reconnectStates.set('waiting', { attempts: 1, timer });
+
+ expect(service.hasStartCapacity(2)).toBe(false);
+ expect(service.hasStartCapacity(3)).toBe(true);
+ } finally {
+ clearTimeout(timer);
+ intern.engines.delete('running');
+ intern.reconnectStates.clear();
+ }
+ });
+
it('a failed start leaves no reconnect state behind', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 8e0ee3097..9adb698e4 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1104,6 +1104,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engines.activeIds();
}
+ /** Whether this node has a MAX_CONCURRENT_SESSIONS slot free, counted exactly as the start path counts it. */
+ hasStartCapacity(max: number): boolean {
+ return this.engineLifecycle.startSlotHolders().size < max;
+ }
+
/**
* Stop engines for session ids whose DB row is about to be replaced by an infra import.
* Owned by the lifecycle service; see SessionEngineLifecycle.stopOrphanEngines().
diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.ts
index 5abcf101d..04129d2a0 100644
--- a/src/modules/takeover/session-takeover.service.spec.ts
+++ b/src/modules/takeover/session-takeover.service.spec.ts
@@ -6,7 +6,6 @@ import type { SessionService } from '../session/session.service';
import type { SessionOwnershipService } from '../session/session-ownership.service';
import type { ConfigService } from '@nestjs/config';
import type { ShutdownService } from '../../common/services/shutdown.service';
-import type { EngineRegistry } from '../../engine/engine-registry.service';
/**
* The sweep is the retry that boot auto-start never had: both live incidents (a container recreate
@@ -28,7 +27,7 @@ describe('SessionTakeoverService', () => {
const build = (
rows: Session[],
- opts: { autoStart?: boolean; startImpl?: jest.Mock; maxConcurrent?: number; activeIds?: string[] } = {},
+ opts: { autoStart?: boolean; startImpl?: jest.Mock; maxConcurrent?: number; slotHolders?: number } = {},
): {
svc: SessionTakeoverService;
start: jest.Mock;
@@ -44,15 +43,14 @@ describe('SessionTakeoverService', () => {
'sessions.maxConcurrent': opts.maxConcurrent,
})[key as 'features'] ?? def,
} as unknown as ConfigService;
+ const hasStartCapacity = jest.fn((max: number) => (opts.slotHolders ?? 0) < max);
const svc = new SessionTakeoverService(
- { start, markLapsedDisconnected } as unknown as SessionService,
+ { start, markLapsedDisconnected, hasStartCapacity } as unknown as SessionService,
{
lapsedHeldByOthers: jest.fn().mockResolvedValue(rows),
leaseTtlMs: 60_000,
} as unknown as SessionOwnershipService,
config,
- undefined,
- { activeIds: () => opts.activeIds ?? [] } as unknown as EngineRegistry,
);
return { svc, start, markLapsedDisconnected };
};
@@ -153,7 +151,7 @@ describe('SessionTakeoverService', () => {
// nobody: no peer adopts a row without a holder, so the session would stay down. A node at its cap
// leaves the lease alone for a peer with room.
it('adopts nothing while this node is at MAX_CONCURRENT_SESSIONS', async () => {
- const { svc, start } = build([lapsed({ name: 'a' })], { maxConcurrent: 1, activeIds: ['busy'] });
+ const { svc, start } = build([lapsed({ name: 'a' })], { maxConcurrent: 1, slotHolders: 1 });
await svc.sweep();
@@ -161,7 +159,7 @@ describe('SessionTakeoverService', () => {
});
it('adopts while this node is still below MAX_CONCURRENT_SESSIONS', async () => {
- const { svc, start } = build([lapsed({ name: 'a' })], { maxConcurrent: 2, activeIds: ['busy'] });
+ const { svc, start } = build([lapsed({ name: 'a' })], { maxConcurrent: 2, slotHolders: 1 });
await svc.sweep();
diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.ts
index 00eb7f53c..28d846218 100644
--- a/src/modules/takeover/session-takeover.service.ts
+++ b/src/modules/takeover/session-takeover.service.ts
@@ -8,7 +8,6 @@ import { ShutdownService } from '../../common/services/shutdown.service';
import { SessionService } from '../session/session.service';
import { SessionStoppedException } from '../session/session-engine-controls';
import { resolveMaxConcurrentSessions } from '../session/session-engine-lifecycle.service';
-import { EngineRegistry } from '../../engine/engine-registry.service';
/**
* Statuses worth adopting from a lapsed node. They all mean "an engine was (or should be) running".
@@ -87,8 +86,6 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD
// source session-engine-lifecycle and the liveness watchdog already consult.
@Optional()
private readonly shutdownService?: ShutdownService,
- @Optional()
- private readonly engines?: EngineRegistry,
) {}
/** True once EITHER the drain has begun or Nest has torn this module down. */
@@ -202,7 +199,7 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD
/** The same count the start path's MAX_CONCURRENT_SESSIONS check uses. */
private hasStartCapacity(): boolean {
const max = resolveMaxConcurrentSessions(this.configService);
- return max === null || !this.engines || this.engines.activeIds().length < max;
+ return max === null || this.sessionService.hasStartCapacity(max);
}
private isEligible(session: Session): boolean {