Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): time-bound + isolate engine teardown in delete()/stop() (#332)

Yudhi Armyndharis035e478e4087
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a0bbc172c..85fd66df6 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -146,6 +146,47 @@ describe('SessionService', () => {
});
});
+ // ── delete/stop teardown resilience ───────────────────────────────
+ describe('teardown resilience (F-10)', () => {
+ const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;
+ const stoppingOf = () => (service as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
+
+ it('delete() completes when engine.destroy() rejects — map reconciled, row removed, stop-mark cleared', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ const engine = { destroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };
+ enginesOf().set('sess-uuid-1', engine);
+
+ await expect(service.delete('sess-uuid-1')).resolves.toBeUndefined();
+
+ expect(engine.destroy).toHaveBeenCalledTimes(1);
+ expect(enginesOf().has('sess-uuid-1')).toBe(false); // Map reconciled despite the failure
+ expect(stoppingOf().has('sess-uuid-1')).toBe(false); // stop-mark cleared (no wedge)
+ expect(hookManager.execute).toHaveBeenCalledWith('session:deleted', expect.anything(), expect.anything());
+ expect(dataSource.transaction).toHaveBeenCalled(); // DB removal still ran
+ });
+
+ it('stop() completes when engine.disconnect() rejects — map reconciled, status updated', 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')) };
+ enginesOf().set('sess-uuid-1', engine);
+
+ await expect(service.stop('sess-uuid-1')).resolves.toBeDefined();
+
+ expect(engine.disconnect).toHaveBeenCalledTimes(1);
+ expect(enginesOf().has('sess-uuid-1')).toBe(false);
+ });
+
+ it('delete() still surfaces a real DB-removal failure (engine teardown is best-effort, DB is not)', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (dataSource.transaction as jest.Mock).mockRejectedValueOnce(new Error('db down'));
+ enginesOf().set('sess-uuid-1', { destroy: jest.fn().mockResolvedValue(undefined) });
+
+ await expect(service.delete('sess-uuid-1')).rejects.toThrow('db down');
+ expect(stoppingOf().has('sess-uuid-1')).toBe(false); // mark still cleared on failure
+ });
+ });
+
// ── create ────────────────────────────────────────────────────────
describe('create', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 569aa4473..e4ba09075 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -158,18 +158,32 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted. */
private async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<void> {
this.logger.log(`Destroying engine for session ${sessionId}`, { sessionId, action: 'shutdown' });
+ await this.teardownEngineSafely(sessionId, engine, e => e.destroy(), 'destroy');
+ }
+
+ /**
+ * Run an engine teardown (destroy/disconnect), isolating + time-bounding failures so a stuck
+ * Chromium/socket can neither hang nor abort the caller. Always resolves — the caller is then free
+ * to reconcile the engines Map and proceed with DB cleanup regardless of teardown outcome.
+ */
+ private async teardownEngineSafely(
+ sessionId: string,
+ engine: IWhatsAppEngine,
+ teardown: (e: IWhatsAppEngine) => Promise<void>,
+ label: 'destroy' | 'disconnect',
+ ): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
- engine.destroy(),
+ teardown(engine),
new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error('engine.destroy() timed out')), 10_000);
+ timer = setTimeout(() => reject(new Error(`engine.${label}() timed out`)), 10_000);
}),
]);
} catch (err) {
- this.logger.error(`Failed to destroy engine for session ${sessionId} during shutdown`, String(err), {
+ this.logger.error(`Failed to ${label} engine for session ${sessionId}`, String(err), {
sessionId,
- action: 'shutdown_destroy_failed',
+ action: `engine_${label}_failed`,
});
} finally {
if (timer) clearTimeout(timer);
@@ -257,35 +271,42 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Cancel any reconnection attempts
this.cancelReconnect(id);
- // Stop engine if running
- const engine = this.engines.get(id);
- if (engine) {
- await engine.destroy();
- this.engines.delete(id);
- }
+ try {
+ // Stop engine if running — time-bounded + isolated so a stuck Chromium destroy() can't wedge
+ // the delete; the Map is reconciled and the DB removal proceeds regardless of the outcome.
+ const engine = this.engines.get(id);
+ if (engine) {
+ await this.teardownEngineSafely(id, engine, e => e.destroy(), 'destroy');
+ this.engines.delete(id);
+ }
- // Execute hook BEFORE delete so plugins can access session data
- await this.hookManager.execute(
- 'session:deleted',
- {
- id: session.id,
- name: session.name,
- phone: session.phone,
- pushName: session.pushName,
- },
- {
- sessionId: id,
- source: 'SessionService',
- },
- );
+ // Execute hook BEFORE delete so plugins can access session data
+ await this.hookManager.execute(
+ 'session:deleted',
+ {
+ id: session.id,
+ name: session.name,
+ phone: session.phone,
+ pushName: session.pushName,
+ },
+ {
+ sessionId: id,
+ source: 'SessionService',
+ },
+ );
- await this.dataSource.transaction(async manager => {
- await manager.remove(session);
- });
- this.logger.log(`Session deleted: ${session.name}`, {
- sessionId: id,
- action: 'delete',
- });
+ // DB removal is NOT best-effort: a genuine failure must surface (500) rather than be swallowed.
+ await this.dataSource.transaction(async manager => {
+ await manager.remove(session);
+ });
+ this.logger.log(`Session deleted: ${session.name}`, {
+ sessionId: id,
+ action: 'delete',
+ });
+ } finally {
+ // Always clear the teardown mark so a later recreate/start with this id isn't suppressed.
+ this.stoppingSessions.delete(id);
+ }
}
async start(id: string): Promise<Session> {
@@ -776,10 +797,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Cancel any reconnection attempts
this.cancelReconnect(id);
+ // Disconnect the engine — time-bounded + isolated so a stuck socket can't wedge the stop; the
+ // Map is reconciled regardless. (The stop mark is intentionally left set, matching the prior
+ // behaviour: a later start() clears it; it guards against a late reconnect resurrecting the id.)
const engine = this.engines.get(id);
-
if (engine) {
- await engine.disconnect();
+ await this.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');
this.engines.delete(id);
}