Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(takeover): leave a lapsed session to a peer when at the start cap

Yudhi Armyndharisa8382f6625fd
diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.ts
index 80c311454..5abcf101d 100644
--- a/src/modules/takeover/session-takeover.service.spec.ts
+++ b/src/modules/takeover/session-takeover.service.spec.ts
@@ -6,6 +6,7 @@ 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
@@ -27,7 +28,7 @@ describe('SessionTakeoverService', () => {
const build = (
rows: Session[],
- opts: { autoStart?: boolean; startImpl?: jest.Mock } = {},
+ opts: { autoStart?: boolean; startImpl?: jest.Mock; maxConcurrent?: number; activeIds?: string[] } = {},
): {
svc: SessionTakeoverService;
start: jest.Mock;
@@ -40,6 +41,7 @@ describe('SessionTakeoverService', () => {
({
features: { autoStartSessions: opts.autoStart ?? true },
'session.takeoverSweepMs': 30_000,
+ 'sessions.maxConcurrent': opts.maxConcurrent,
})[key as 'features'] ?? def,
} as unknown as ConfigService;
const svc = new SessionTakeoverService(
@@ -49,6 +51,8 @@ describe('SessionTakeoverService', () => {
leaseTtlMs: 60_000,
} as unknown as SessionOwnershipService,
config,
+ undefined,
+ { activeIds: () => opts.activeIds ?? [] } as unknown as EngineRegistry,
);
return { svc, start, markLapsedDisconnected };
};
@@ -145,6 +149,25 @@ describe('SessionTakeoverService', () => {
expect(start.mock.calls).toEqual([['id-raced'], ['id-ours']]);
});
+ // A start the cap refuses still claims the lapsed lease first, and the refusal then releases it to
+ // 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'] });
+
+ await svc.sweep();
+
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it('adopts while this node is still below MAX_CONCURRENT_SESSIONS', async () => {
+ const { svc, start } = build([lapsed({ name: 'a' })], { maxConcurrent: 2, activeIds: ['busy'] });
+
+ await svc.sweep();
+
+ expect(start).toHaveBeenCalledWith('id-a');
+ });
+
it('a session stopped after the sweep read it is logged as skipped, not as a lost claim race', async () => {
const start = jest.fn().mockRejectedValueOnce(new SessionStoppedException('Session id-halted was stopped'));
const { svc } = build([lapsed({ name: 'halted' })], { startImpl: start });
diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.ts
index f0e6b1557..00eb7f53c 100644
--- a/src/modules/takeover/session-takeover.service.ts
+++ b/src/modules/takeover/session-takeover.service.ts
@@ -7,6 +7,8 @@ import { SessionOwnershipService } from '../session/session-ownership.service';
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".
@@ -85,6 +87,8 @@ 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. */
@@ -159,6 +163,15 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD
// 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.stopping) return;
+ // start() claims the lapsed lease before the cap check refuses the launch, and that refusal
+ // releases the claim to nobody: a row with no holder is never adopted again, by this node or a
+ // peer. A node at its cap therefore leaves the lease where it is, for a peer with room.
+ if (!this.hasStartCapacity()) {
+ this.logger.debug('Takeover paused: this node is at MAX_CONCURRENT_SESSIONS', {
+ pending: eligible.length - i,
+ });
+ return;
+ }
try {
await this.sessionService.start(session.id);
this.logger.log(`Adopted session ${session.name} from lapsed node ${session.nodeId ?? '?'}`, {
@@ -186,6 +199,12 @@ 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;
+ }
+
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. A session an