Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): count a force-kill only when it has an engine to kill

Yudhi Armyndharisbbfa04b426b0
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 5afda0ddd..8b50d222f 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -72,6 +72,8 @@ export interface StopHooks {
afterRead?: () => Promise<void>;
/** Runs when the session read fails, after the stop mark is dropped: undoes the caller's request count. */
onReadFailed?: () => void;
+ /** forceKill() only: runs synchronously once there is an engine to kill; records the stop request. */
+ onEngineFound?: () => void;
}
/**
@@ -544,8 +546,12 @@ export class SessionEngineControls {
* engine is hung. Mirrors stop()'s lifecycle (stop-mark + cancel-reconnect + bounded, isolated
* teardown + Map reconciliation) but uses the engine's forceDestroy().
*/
- async forceKill(id: string): Promise<Session> {
- const session = await this.requireSession(id);
+ async forceKill(id: string, hooks: StopHooks = {}): Promise<Session> {
+ // No stop mark is set yet, so a failed read leaves a concurrent stop's mark alone.
+ const session = await this.requireSession(id).catch((error: unknown) => {
+ hooks.onReadFailed?.();
+ throw error;
+ });
const engine = this.engines.get(id);
// No live engine means there is nothing to SIGKILL. Resolving would let the controller write a
@@ -555,6 +561,8 @@ export class SessionEngineControls {
if (!engine) {
throw new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.');
}
+ // In the same synchronous step as the engine lookup: a refused or failed kill never gets here.
+ hooks.onEngineFound?.();
// Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
this.stoppingSessions.add(id);
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 2d28db742..e00a9c3c9 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -457,8 +457,8 @@ export class SessionEngineLifecycle {
}
/** Delegate: SessionEngineControls.forceKill. */
- forceKill(id: string): Promise<Session> {
- return this.controls.forceKill(id);
+ forceKill(id: string, hooks?: StopHooks): Promise<Session> {
+ return this.controls.forceKill(id, hooks);
}
/** Delegate: SessionEngineControls.delete. */
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 805e0c35c..681661f4b 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1524,6 +1524,75 @@ describe('SessionService', () => {
expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(true);
});
+ // The claim resolves while the force-kill is still reading the row, and the start's own read is
+ // held so no engine appears meanwhile: a kill that ends in a 400 (no engine) or in a failed read
+ // took nothing down, so the start must still launch.
+ type SettleRead = (resolveRead: (row: Session) => void, failRead: (error: Error) => void) => void;
+ it.each<[string, SettleRead]>([
+ ['refused with 400', resolveRead => resolveRead(createMockSession())],
+ ['whose row read fails', (_resolveRead, failRead) => failRead(new Error('connection terminated'))],
+ ])('start() still launches when a forceKill() %s overlaps its claim', async (_label, settleRead) => {
+ const ownership = withOwnership();
+ const desired = trackDesiredState();
+ let finishClaim: () => void = () => undefined;
+ ownership.claim.mockImplementationOnce(
+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(true))),
+ );
+ const starting = service.start('sess-uuid-1', { explicit: true });
+ await new Promise(resolve => setImmediate(resolve));
+
+ let resolveKillRead: (row: Session) => void = () => undefined;
+ let failKillRead: (error: Error) => void = () => undefined;
+ let resolveStartRead: (row: Session) => void = () => undefined;
+ (repository.findOne as jest.Mock)
+ .mockImplementationOnce(
+ () =>
+ new Promise<Session>((resolve, reject) => {
+ resolveKillRead = resolve;
+ failKillRead = reject;
+ }),
+ )
+ .mockImplementationOnce(() => new Promise<Session>(resolve => (resolveStartRead = resolve)));
+ const killing = service.forceKill('sess-uuid-1').catch((error: unknown) => error);
+ finishClaim();
+ await new Promise(resolve => setImmediate(resolve));
+ settleRead(resolveKillRead, failKillRead);
+ await killing;
+ resolveStartRead(createMockSession());
+ await starting;
+
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(true);
+ expect(desired()).not.toBe('stopped');
+ });
+
+ // An engine registered while the force-kill read the row is still killed, and still counted.
+ it('start() refuses with 409 when a forceKill() finds an engine only after its row read', async () => {
+ const ownership = withOwnership();
+ trackDesiredState();
+ let finishClaim: () => void = () => undefined;
+ ownership.claim.mockImplementationOnce(
+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(true))),
+ );
+ const starting = service.start('sess-uuid-1', { explicit: true });
+ const outcome = starting.catch((error: unknown) => error);
+ await new Promise(resolve => setImmediate(resolve));
+
+ let resolveKillRead: (row: Session) => void = () => undefined;
+ (repository.findOne as jest.Mock).mockImplementationOnce(
+ () => new Promise<Session>(resolve => (resolveKillRead = resolve)),
+ );
+ const killing = service.forceKill('sess-uuid-1');
+ (service as unknown as { engines: Map<string, unknown> }).engines.set('sess-uuid-1', {
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ });
+ resolveKillRead(createMockSession());
+ await killing;
+ finishClaim();
+
+ expect(await outcome).toBeInstanceOf(SessionStoppedException);
+ expect(mockEngine.initialize).not.toHaveBeenCalled();
+ });
+
// The teardown finished while a start sent after it still waited on its claim, and handed back
// the claim that start had just taken: the start then ran its engine on a row no node held.
it.each([
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index fd5e42677..031f3a869 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -771,17 +771,31 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async forceKill(id: string): Promise<Session> {
- // Counted like stop(), so a start still waiting on its claim yields rather than relaunching.
- this.countStopRequest(id);
+ // Counted like stop(), so a start still waiting on its claim yields rather than relaunching, but
+ // only while there is an engine to kill: at once if one runs, so a start sent after the kill keeps
+ // its place, otherwise once the kill finds one. A kill that took nothing down (a 400, a 404 or a
+ // failed row read) is uncounted, so it cannot retire a start that is still waiting on its claim.
+ let counted = false;
+ const count = (): void => {
+ if (counted) return;
+ counted = true;
+ this.countStopRequest(id);
+ };
+ const uncount = (): void => {
+ if (!counted) return;
+ counted = false;
+ this.uncountStopRequest(id);
+ };
+ if (this.engines.get(id)) count();
try {
// The engine kill records the stop itself, once it has an engine to kill.
- const session = await this.engineLifecycle.forceKill(id);
+ const session = await this.engineLifecycle.forceKill(id, { onReadFailed: uncount, onEngineFound: count });
await this.releaseAfterTeardown(id);
return session;
} catch (error) {
- // A 400 "not started" or a 404 took nothing down, so it is uncounted, and the 400 keeps its claim
- // as in logout(). The 502 did evict the engine: it stays counted and releases.
- if (error instanceof BadRequestException || error instanceof NotFoundException) this.uncountStopRequest(id);
+ // The 400 "not started" also keeps its claim as in logout(). The 502 did evict the engine: it
+ // stays counted and releases.
+ if (error instanceof BadRequestException) uncount();
if (!(error instanceof BadRequestException)) await this.releaseAfterTeardown(id);
throw error;
}