Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): escalate stop() to force-destroy when graceful disconnect fails

Yudhi Armyndharis9d177ebcc80c
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 451fc8e92..a187b4685 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -273,8 +273,35 @@ export class SessionEngineControls {
// write so a delayed pre-initialize status update can never settle after the retirement and
// become the last persisted status. Identity-checked: only the captured engine's promise.
await this.fences.awaitInitialStatus(id, engine);
- await this.fences.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');
+ let tornDown = await this.fences.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');
+ if (!tornDown) {
+ // The graceful disconnect threw or timed out, so the engine may be half-attached (a leaked
+ // Chromium process or a live socket). Escalate to the hard kill — the same forceDestroy()
+ // forceKill() uses for a wedged engine — before reporting the stop.
+ this.logger.warn(`Graceful disconnect failed for session ${session.name}; escalating to force-destroy`, {
+ sessionId: id,
+ action: 'stop_escalate_force_destroy',
+ });
+ tornDown = await this.fences.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
+ }
+ // Reconciled regardless of the outcome: a wedged engine must not keep holding a concurrency
+ // slot or read as "already started" to a later start().
this.engines.deleteIfLive(id, engine);
+ if (!tornDown) {
+ // The hard kill failed too, so the engine's process may still be alive. Local state is
+ // settled (Map reconciled, status DISCONNECTED — mirroring logout()'s incomplete path), but
+ // the stop is reported as incomplete instead of claimed clean: a retryable 502 with a stable
+ // code, and no success log (the controller audits SESSION_STOPPED only after this resolves).
+ await this.host.updateStatus(id, SessionStatus.DISCONNECTED);
+ throw new BadGatewayException({
+ statusCode: HttpStatus.BAD_GATEWAY,
+ message:
+ 'Session was stopped locally, but the engine teardown did not complete — the engine ' +
+ 'process may still be running. Retry the stop; restart the node to reap a leaked process.',
+ error: 'Bad Gateway',
+ code: 'SESSION_STOP_INCOMPLETE',
+ });
+ }
}
this.logger.log(`Session stopped: ${session.name}`, {
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a5826b0e4..11ed9c308 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -330,16 +330,50 @@ describe('SessionService', () => {
expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
});
- it('stop() completes when engine.disconnect() rejects — map reconciled, status updated', async () => {
+ it('stop() escalates to forceDestroy when engine.disconnect() rejects — stop completes with a warning', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- const engine = { disconnect: jest.fn().mockRejectedValue(new Error('stuck socket')) };
+ const engine = {
+ disconnect: jest.fn().mockRejectedValue(new Error('stuck socket')),
+ forceDestroy: jest.fn().mockResolvedValue(undefined),
+ };
enginesOf().set('sess-uuid-1', engine);
+ const warn = jest.spyOn((lifecycle as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger, 'warn');
await expect(service.stop('sess-uuid-1')).resolves.toBeDefined();
expect(engine.disconnect).toHaveBeenCalledTimes(1);
+ expect(engine.forceDestroy).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('escalating to force-destroy'),
+ expect.objectContaining({ sessionId: 'sess-uuid-1' }),
+ );
+ expect(enginesOf().has('sess-uuid-1')).toBe(false);
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });
+ warn.mockRestore();
+ });
+
+ it('stop() surfaces a retryable 502 when the graceful disconnect AND the force-destroy both fail', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ const engine = {
+ disconnect: jest.fn().mockRejectedValue(new Error('stuck socket')),
+ forceDestroy: jest.fn().mockRejectedValue(new Error('SIGKILL refused')),
+ };
+ enginesOf().set('sess-uuid-1', engine);
+
+ const thrown = await service.stop('sess-uuid-1').catch((e: unknown) => e);
+
+ expect(thrown).toBeInstanceOf(BadGatewayException);
+ const response = (thrown as BadGatewayException).getResponse() as { code?: string; message?: string };
+ expect(response.code).toBe('SESSION_STOP_INCOMPLETE');
+ expect(engine.disconnect).toHaveBeenCalledTimes(1);
+ expect(engine.forceDestroy).toHaveBeenCalledTimes(1);
+ // The engine leaves the map regardless — it must not hold a concurrency slot — but the stop is
+ // reported as incomplete rather than claimed clean for a process that may still be running.
expect(enginesOf().has('sess-uuid-1')).toBe(false);
+ // Local state is still settled, mirroring logout()'s incomplete path.
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });
});
it('delete() still surfaces a real DB-removal failure (engine teardown is best-effort, DB is not)', async () => {