Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: graceful termination-signal drain + boot-flag/import/crash hardening (#644)

Yudhi Armyndharisc6f6946bbe40
diff --git a/.env.example b/.env.example
index 17895b6bd..5c27d0214 100644
--- a/.env.example
+++ b/.env.example
@@ -14,12 +14,21 @@ LOG_LEVEL=info # error | warn | info | debug
# human-readable pretty otherwise. Force one with: json | pretty
# LOG_FORMAT=pretty
-# Auto-start previously authenticated sessions on server boot
+# Auto-start previously authenticated sessions on server boot. Recommended `true` for a SINGLE-instance
+# production deployment so a crash-restart self-heals authenticated sessions; keep `false` if you run
+# multiple replicas behind a scheduler (two replicas resurrecting one session risks a forced logout/ban —
+# see docs/13-horizontal-scaling.md).
AUTO_START_SESSIONS=false
# 0 = unlimited. Set a positive integer to cap concurrently running/initializing sessions.
# Failed sessions still hold a slot until stopped (their engine stays resident); stop them to free capacity.
MAX_CONCURRENT_SESSIONS=0
+# Graceful-shutdown drain: on SIGTERM/SIGINT the app flips readiness to 503 (so a load balancer stops
+# routing) and keeps serving in-flight requests for this many ms before teardown. Default 3000 in
+# production, 0 elsewhere (a dev hot-reload/Ctrl+C is not slowed). Capped at 30000. A second signal
+# forces an immediate exit. In Docker, keep `stop_grace_period` >= this + your worst-case teardown.
+# SHUTDOWN_DELAY_MS=3000
+
# Domain Configuration
DOMAIN=localhost
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12a331114..667d2b969 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+
+- **Graceful shutdown now drains on `SIGTERM`/`SIGINT`** (rolling deploys, `docker stop`, Ctrl+C), not just on the admin restart endpoint. On a termination signal the app flips readiness to `503` immediately so a load balancer/orchestrator stops routing, keeps serving in-flight requests for a bounded grace window, then tears down and exits deterministically. ⚠️ **Behavior change:** a `docker stop` / redeploy now takes up to the grace window (`SHUTDOWN_DELAY_MS`, default **3s** in production, **0** in dev) plus teardown instead of tearing down instantly, and the process now exits `0` on a clean signal. In Docker set `stop_grace_period` ≥ `SHUTDOWN_DELAY_MS` + your worst-case teardown (the bundled compose now sets `45s`); for Kubernetes set `terminationGracePeriodSeconds` accordingly. A second signal during the drain forces an immediate exit. The whatsapp-web.js engine no longer lets Puppeteer install its own signal handlers (which previously killed Chromium at signal time / `exit(130)` before the drain could run).
+
+### Fixed
+
+- **Boot now rejects a non-canonical boolean feature flag instead of silently disabling the feature.** `QUEUE_ENABLED`, `MCP_ENABLED`, and `SERVE_DASHBOARD` are read with an exact `=== 'true'` / `!== 'false'` comparison, so a typo (`True`, `1`, `yes`) or a stray trailing space/CR (a Windows-edited env file forwarded verbatim by `docker run --env-file`) silently (dis)abled the feature with zero diagnostics. These are now validated at startup and boot fails fast naming the offending key. ⚠️ **Behavior change:** a deployment currently booting with such a value (e.g. `QUEUE_ENABLED=1`) will now refuse to start until corrected to `true`/`false`/unset — including `SERVE_DASHBOARD=0`/`no`, which was silently serving the dashboard and will now correctly disable it once set to `false`.
+- **A fatal uncaught exception is now written to the structured log** (with its stack and origin) before the process exits, instead of only a raw stack on stderr that the log pipeline missed. This is observe-only: the crash-and-restart posture is unchanged (the container restart policy still fires and the process never continues on corrupted post-exception state).
+- **`POST /infra/import-data` no longer swallows a genuine database error while clearing tables.** The table-clearing step tolerated only a genuinely-absent table but previously used a blanket catch, so an I/O/lock error (or an aborted transaction) could let a restore commit a *merged* rather than *replaced* dataset on SQLite. Such errors now surface and roll the whole import back (a real fault returns a `500` carrying the actual cause); the intended tolerance for a missing table is preserved.
+- **A session no longer schedules a reconnect while the process is shutting down** — a disconnect during the drain window would otherwise launch a fresh Chromium racing the shutdown teardown. The session is left `DISCONNECTED` (a later start / auto-restore re-initializes it cleanly).
+
## [0.8.9] - 2026-07-06
### Changed
diff --git a/docker-compose.yml b/docker-compose.yml
index ef6c770a9..67bab54ec 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -34,6 +34,11 @@ services:
dockerfile: Dockerfile
container_name: openwa-api
restart: unless-stopped
+ # Give the graceful drain room to complete before Docker SIGKILLs the container: the shutdown
+ # grace (SHUTDOWN_DELAY_MS, default 3s) plus the worst-case per-engine teardown bound (~10s) can
+ # exceed Docker's 10s default, which would otherwise kill Chromium mid-teardown and orphan a
+ # session profile. Tune down if you raise neither SHUTDOWN_DELAY_MS nor run many sessions.
+ stop_grace_period: 45s
# App network for datastores + the isolated network to reach
# docker-proxy (DOCKER_HOST). createService() in docker.service.ts attaches
# orchestrated containers to the literal `openwa-network`, so its name is fixed.
diff --git a/src/common/services/shutdown.service.spec.ts b/src/common/services/shutdown.service.spec.ts
index d3c6618ee..07922684d 100644
--- a/src/common/services/shutdown.service.spec.ts
+++ b/src/common/services/shutdown.service.spec.ts
@@ -18,3 +18,95 @@ describe('ShutdownService (draining flag)', () => {
expect(svc.isShuttingDown()).toBe(true);
});
});
+
+describe('ShutdownService.shutdown (idempotent, bounded grace)', () => {
+ let exitSpy: jest.SpyInstance;
+ const ORIG_ENV = process.env.NODE_ENV;
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation((): never => undefined as never);
+ });
+
+ afterEach(() => {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ exitSpy.mockRestore();
+ delete process.env.SHUTDOWN_DELAY_MS;
+ if (ORIG_ENV === undefined) delete process.env.NODE_ENV;
+ else process.env.NODE_ENV = ORIG_ENV;
+ });
+
+ const svcWithCb = (): { svc: ShutdownService; cb: jest.Mock } => {
+ const svc = new ShutdownService();
+ const cb = jest.fn().mockResolvedValue(undefined);
+ svc.setShutdownCallback(cb);
+ return { svc, cb };
+ };
+
+ it('flips the draining flag synchronously, before the grace elapses', () => {
+ process.env.SHUTDOWN_DELAY_MS = '5000';
+ const { svc } = svcWithCb();
+ svc.shutdown();
+ expect(svc.isShuttingDown()).toBe(true);
+ expect(jest.getTimerCount()).toBe(1);
+ });
+
+ it('runs the teardown callback and exits exactly once even when called repeatedly', async () => {
+ process.env.SHUTDOWN_DELAY_MS = '0';
+ const { svc, cb } = svcWithCb();
+ svc.shutdown();
+ svc.shutdown(); // repeated signal / admin-restart overlap — must be a no-op
+ svc.shutdown();
+ expect(jest.getTimerCount()).toBe(1);
+ await jest.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ expect(exitSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('defaults the grace to 0 only for an explicit development/test env (fast dev hot-reload / Ctrl+C)', async () => {
+ for (const env of ['development', 'test']) {
+ process.env.NODE_ENV = env;
+ delete process.env.SHUTDOWN_DELAY_MS;
+ const { svc, cb } = svcWithCb();
+ svc.shutdown();
+ await jest.advanceTimersByTimeAsync(0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it('keeps the full 3s drain window in production', async () => {
+ process.env.NODE_ENV = 'production';
+ delete process.env.SHUTDOWN_DELAY_MS;
+ const { svc, cb } = svcWithCb();
+ svc.shutdown();
+ await jest.advanceTimersByTimeAsync(0);
+ expect(cb).not.toHaveBeenCalled(); // grace has not elapsed
+ await jest.advanceTimersByTimeAsync(3000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the 3s drain window when NODE_ENV is UNSET (a bare `docker run` / k8s pod)', async () => {
+ // Regression guard: the runtime image does not set NODE_ENV, so an unset env must NOT collapse the
+ // drain to 0 — only an explicit dev/test does. Otherwise a rolling deploy loses its readiness window.
+ delete process.env.NODE_ENV;
+ delete process.env.SHUTDOWN_DELAY_MS;
+ const { svc, cb } = svcWithCb();
+ svc.shutdown();
+ await jest.advanceTimersByTimeAsync(0);
+ expect(cb).not.toHaveBeenCalled();
+ await jest.advanceTimersByTimeAsync(3000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it('honours an explicit SHUTDOWN_DELAY_MS even outside production', async () => {
+ process.env.NODE_ENV = 'development';
+ process.env.SHUTDOWN_DELAY_MS = '2000';
+ const { svc, cb } = svcWithCb();
+ svc.shutdown();
+ await jest.advanceTimersByTimeAsync(0);
+ expect(cb).not.toHaveBeenCalled();
+ await jest.advanceTimersByTimeAsync(2000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/common/services/shutdown.service.ts b/src/common/services/shutdown.service.ts
index cde9d5f77..29b17e5ad 100644
--- a/src/common/services/shutdown.service.ts
+++ b/src/common/services/shutdown.service.ts
@@ -10,6 +10,7 @@ export class ShutdownService {
private readonly logger = createLogger('ShutdownService');
private destroyCallback: (() => Promise<void>) | null = null;
private shuttingDown = false;
+ private shutdownScheduled = false;
/**
* Set the shutdown callback (called from main.ts after app creation)
@@ -41,6 +42,11 @@ export class ShutdownService {
shutdown(delayMs?: number): void {
this.markShuttingDown();
+ // Idempotent: a repeated signal (double Ctrl+C, or a SIGTERM overlapping an admin restart) must not
+ // schedule a second grace timer / second app.close() / second process.exit. The first call wins.
+ if (this.shutdownScheduled) return;
+ this.shutdownScheduled = true;
+
const delay = Math.min(delayMs ?? this.resolveDelay(), MAX_SHUTDOWN_DELAY_MS);
this.logger.log('Graceful shutdown requested', { delayMs: delay });
@@ -61,10 +67,17 @@ export class ShutdownService {
}, delay);
}
- /** Bounded, configurable grace (SHUTDOWN_DELAY_MS); default 3s, capped at 30s. */
+ /**
+ * Bounded, configurable grace (SHUTDOWN_DELAY_MS), capped at 30s. An explicit value always wins.
+ * When unset, the default is the full 3s drain window (so a load balancer observes the 503 before
+ * teardown) for EVERY real deployment — including a bare `docker run` or a Kubernetes pod that never
+ * sets NODE_ENV. Only an explicit `development`/`test` skips the window (delay 0), so a
+ * `nest start --watch` hot reload or a dev Ctrl+C is not slowed by a grace it does not need.
+ */
private resolveDelay(): number {
const parsed = Number.parseInt(process.env.SHUTDOWN_DELAY_MS ?? '', 10);
- if (!Number.isInteger(parsed) || parsed < 0) return DEFAULT_SHUTDOWN_DELAY_MS;
- return parsed;
+ if (Number.isInteger(parsed) && parsed >= 0) return parsed;
+ const env = process.env.NODE_ENV;
+ return env === 'development' || env === 'test' ? 0 : DEFAULT_SHUTDOWN_DELAY_MS;
}
}
diff --git a/src/common/utils/db-errors.spec.ts b/src/common/utils/db-errors.spec.ts
new file mode 100644
index 000000000..c3a390df7
--- /dev/null
+++ b/src/common/utils/db-errors.spec.ts
@@ -0,0 +1,35 @@
+import { QueryFailedError } from 'typeorm';
+import { isUniqueViolation, isMissingTableError } from './db-errors';
+
+// Realistic driver errors: sqlite3 / pg both throw an Error carrying a `code` property, which TypeORM
+// wraps in QueryFailedError (message copied from the driver error).
+const driverErr = (message: string, code: string): Error => Object.assign(new Error(message), { code });
+const qfe = (message: string, code: string): QueryFailedError =>
+ new QueryFailedError('DELETE FROM x', [], driverErr(message, code));
+
+describe('isMissingTableError', () => {
+ it('recognizes a Postgres undefined_table by its precise code (42P01)', () => {
+ expect(isMissingTableError(qfe('relation "templates" does not exist', '42P01'))).toBe(true);
+ });
+
+ it('recognizes a SQLite missing table by MESSAGE, not by its generic code', () => {
+ expect(isMissingTableError(qfe('SQLITE_ERROR: no such table: templates', 'SQLITE_ERROR'))).toBe(true);
+ });
+
+ it('does NOT treat a genuine SQLite failure as missing-table (it must surface)', () => {
+ // A lock/IO error and a syntax error both need to propagate — swallowing them is the very bug this
+ // classifier exists to prevent. Note the syntax error shares the generic SQLITE_ERROR code.
+ expect(isMissingTableError(qfe('SQLITE_BUSY: database is locked', 'SQLITE_BUSY'))).toBe(false);
+ expect(isMissingTableError(qfe('SQLITE_ERROR: near "FROM": syntax error', 'SQLITE_ERROR'))).toBe(false);
+ });
+
+ it('does not classify a non-QueryFailedError (even if its text mentions a missing table)', () => {
+ expect(isMissingTableError(new Error('no such table: x'))).toBe(false);
+ expect(isMissingTableError(undefined)).toBe(false);
+ });
+
+ it('leaves isUniqueViolation behaviour intact (regression guard for the shared module)', () => {
+ expect(isUniqueViolation(qfe('duplicate key value violates unique constraint', '23505'))).toBe(true);
+ expect(isMissingTableError(qfe('duplicate key value violates unique constraint', '23505'))).toBe(false);
+ });
+});
diff --git a/src/common/utils/db-errors.ts b/src/common/utils/db-errors.ts
index 01c5657d0..b0e1f55ff 100644
--- a/src/common/utils/db-errors.ts
+++ b/src/common/utils/db-errors.ts
@@ -13,3 +13,19 @@ export function isUniqueViolation(err: unknown): boolean {
const message = driver?.message ?? err.message ?? '';
return code === '23505' /* postgres */ || /UNIQUE constraint failed|SQLITE_CONSTRAINT/i.test(message);
}
+
+/**
+ * Cross-dialect "the table does not exist" check. Used to keep a table-clearing DELETE tolerant of a
+ * genuinely-absent table while STILL surfacing every other failure (lock, I/O, syntax) — the opposite of
+ * a blind `.catch(() => {})`. Postgres has a precise code (42P01 undefined_table). SQLite is matched by
+ * MESSAGE only: its generic `SQLITE_ERROR` code (errno 1) is shared with syntax and other real errors, so
+ * a code check would over-swallow. The message is read from both the driver error and the wrapped
+ * QueryFailedError so a future TypeORM change to the nesting fails toward the regex still matching.
+ */
+export function isMissingTableError(err: unknown): boolean {
+ if (!(err instanceof QueryFailedError)) return false;
+ const driver = err.driverError as { code?: string; message?: string } | undefined;
+ if (driver?.code === '42P01') return true; // postgres undefined_table
+ const message = `${driver?.message ?? ''} ${err.message ?? ''}`;
+ return /no such table/i.test(message);
+}
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index 1a51627ae..30d55392b 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -75,6 +75,24 @@ describe('validateEnv', () => {
expect(() => validateEnv({ RATE_LIMIT_SHORT_LIMIT: '10', WEBHOOK_TIMEOUT: '10000' })).not.toThrow();
});
+ it('rejects a non-canonical boolean feature flag instead of silently disabling the feature', () => {
+ // QUEUE_ENABLED / MCP_ENABLED / SERVE_DASHBOARD are read at module-eval with `=== 'true'` /
+ // `!== 'false'`, so a typo silently (dis)ables the feature with zero diagnostics. Boot must reject it.
+ expect(() => validateEnv({ QUEUE_ENABLED: 'True' })).toThrow(/QUEUE_ENABLED/);
+ expect(() => validateEnv({ QUEUE_ENABLED: '1' })).toThrow(/QUEUE_ENABLED/);
+ expect(() => validateEnv({ MCP_ENABLED: 'yes' })).toThrow(/MCP_ENABLED/);
+ expect(() => validateEnv({ SERVE_DASHBOARD: 'no' })).toThrow(/SERVE_DASHBOARD/);
+ // The raw value is checked, NOT a trimmed one: a trailing space / CR (Windows-edited env file
+ // forwarded verbatim by `docker run --env-file`) must still be rejected — otherwise the flag reads
+ // false at every `=== 'true'` site while validation passes, giving false assurance.
+ expect(() => validateEnv({ QUEUE_ENABLED: 'true ' })).toThrow(/QUEUE_ENABLED/);
+ expect(() => validateEnv({ MCP_ENABLED: 'true\r' })).toThrow(/MCP_ENABLED/);
+ // Canonical values, unset, and blank (a compose `${KEY:-}` forward renders '') all pass.
+ expect(() => validateEnv({ QUEUE_ENABLED: 'true', MCP_ENABLED: 'false', SERVE_DASHBOARD: 'true' })).not.toThrow();
+ expect(() => validateEnv({ QUEUE_ENABLED: '', SERVE_DASHBOARD: '' })).not.toThrow();
+ expect(() => validateEnv({})).not.toThrow();
+ });
+
it('rejects a sqlite data DB path that collides with the internal main database file', () => {
// The 'main' (auth/audit) and 'data' connections must be separate SQLite files; sharing one
// file means two migration ledgers + synchronize policies on the same tables.
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index bb0ce7dd0..636df5b44 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -116,6 +116,28 @@ export function validateEnv(config: EnvConfig): EnvConfig {
checkPositiveInt(key);
}
+ // Boolean feature flags read at module-eval time (app.module.ts) with a bare `=== 'true'` /
+ // `!== 'false'` comparison: a typo (`True`, `1`, `yes`) or trailing whitespace/CR silently
+ // (dis)ables the feature. Validate the RAW value — NOT a trimmed one — so `'true '` / `'true\r'`
+ // (a Windows-edited env file forwarded verbatim by `docker run --env-file`) is rejected too rather
+ // than passing validation while every read site reads it as false. Blank (a compose `${KEY:-}`
+ // forward) stays legal: it behaves as unset at every read site.
+ const checkBool = (key: string): void => {
+ const raw = config[key];
+ if (raw === undefined) return;
+ if (typeof raw !== 'string') {
+ errors.push(`${key} must be "true" or "false"`);
+ return;
+ }
+ if (raw.trim() === '') return;
+ if (raw !== 'true' && raw !== 'false') {
+ errors.push(`${key} must be "true" or "false" (got ${JSON.stringify(raw)})`);
+ }
+ };
+ for (const key of ['QUEUE_ENABLED', 'MCP_ENABLED', 'SERVE_DASHBOARD']) {
+ checkBool(key);
+ }
+
if (errors.length > 0) {
throw new Error(`Invalid environment configuration:\n - ${errors.join('\n - ')}`);
}
diff --git a/src/config/process-error-monitor.spec.ts b/src/config/process-error-monitor.spec.ts
new file mode 100644
index 000000000..bd9b397d0
--- /dev/null
+++ b/src/config/process-error-monitor.spec.ts
@@ -0,0 +1,50 @@
+import { registerUncaughtExceptionMonitor } from './process-error-monitor';
+
+const EVENT = 'uncaughtExceptionMonitor';
+
+describe('registerUncaughtExceptionMonitor', () => {
+ const added: Array<(...args: unknown[]) => void> = [];
+
+ const register = (logger: { error: (m: string, d?: string) => void }): ((e: unknown, o: string) => void) => {
+ const before = process.listeners(EVENT);
+ registerUncaughtExceptionMonitor(logger);
+ const fresh = process.listeners(EVENT).filter(l => !before.includes(l)) as Array<(...a: unknown[]) => void>;
+ added.push(...fresh);
+ return fresh[fresh.length - 1];
+ };
+
+ afterEach(() => {
+ added.splice(0).forEach(l => process.removeListener(EVENT, l));
+ });
+
+ it('registers exactly one uncaughtExceptionMonitor listener', () => {
+ const before = process.listenerCount(EVENT);
+ register({ error: () => {} });
+ expect(process.listenerCount(EVENT)).toBe(before + 1);
+ });
+
+ it('routes the fatal error through the structured logger (stack included, origin named)', () => {
+ const calls: Array<[string, string | undefined]> = [];
+ const handler = register({ error: (m, d) => calls.push([m, d]) });
+ handler(new Error('boom'), 'uncaughtException');
+ expect(calls).toHaveLength(1);
+ expect(calls[0][0]).toMatch(/Uncaught exception \(uncaughtException\)/);
+ expect(calls[0][1]).toContain('boom'); // err.stack
+ });
+
+ it('never throws even if the logger throws — the original fatal must not be masked', () => {
+ const handler = register({
+ error: () => {
+ throw new Error('logger is down');
+ },
+ });
+ expect(() => handler(new Error('original fatal'), 'uncaughtException')).not.toThrow();
+ });
+
+ it('stringifies a non-Error thrown value without throwing', () => {
+ const calls: Array<[string, string | undefined]> = [];
+ const handler = register({ error: (m, d) => calls.push([m, d]) });
+ expect(() => handler('a bare string', 'uncaughtException')).not.toThrow();
+ expect(calls[0][1]).toContain('a bare string');
+ });
+});
diff --git a/src/config/process-error-monitor.ts b/src/config/process-error-monitor.ts
new file mode 100644
index 000000000..6c6f4d394
--- /dev/null
+++ b/src/config/process-error-monitor.ts
@@ -0,0 +1,32 @@
+/** Minimal structured-logger surface the monitor needs (satisfied by createLogger()'s result). */
+interface FatalLogger {
+ error: (message: string, detail?: string) => void;
+}
+
+/**
+ * Register an `uncaughtExceptionMonitor` that routes an otherwise-fatal uncaught exception through the
+ * structured logger BEFORE Node's default handling.
+ *
+ * `uncaughtExceptionMonitor` (unlike `uncaughtException`) does NOT install a swallowing handler: Node
+ * still prints its default message and exits with code 1. So the crash posture is unchanged — the
+ * container's restart policy still fires and we never continue running on corrupted post-exception
+ * in-memory state (the `engines`/`reconnectStates`/limiter maps could be mid-mutation) — we only add
+ * the fatal stack to the log pipeline, which `console.error`-to-stderr misses.
+ *
+ * The body is guarded so a throw inside the monitor (a poisoned error whose `.stack` getter throws, a
+ * `String()`-incompatible value, or a downed logger) can never mask the original fatal error or change
+ * the exit code — the worst case degrades to losing this one log line while Node's default print + exit
+ * proceed untouched.
+ */
+export function registerUncaughtExceptionMonitor(logger: FatalLogger): void {
+ process.on('uncaughtExceptionMonitor', (err: unknown, origin: string) => {
+ try {
+ logger.error(
+ `Uncaught exception (${origin}) — process will exit`,
+ err instanceof Error ? err.stack : String(err),
+ );
+ } catch {
+ /* never mask the original fatal error */
+ }
+ });
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index b126413e9..1625f818b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -395,6 +395,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
puppeteer: {
headless: this.config.puppeteer?.headless ?? true,
args: puppeteerArgs,
+ // Do NOT let Puppeteer install its own process signal handlers. By default it handles
+ // SIGINT (→ synchronous process.exit(130), which would skip the graceful drain entirely)
+ // and SIGTERM/SIGHUP (→ kills Chromium at signal time, defeating the drain window). We own
+ // signal handling in main.ts. Puppeteer's unconditional `exit` hook still SIGKILLs this
+ // browser when the process actually exits, so nothing is orphaned.
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ handleSIGHUP: false,
// Only override the executable when explicitly configured; otherwise let
// whatsapp-web.js fall back to Puppeteer's bundled Chromium.
...(this.config.puppeteer?.executablePath ? { executablePath: this.config.puppeteer.executablePath } : {}),
diff --git a/src/main.ts b/src/main.ts
index 610b90bd4..acf0a1990 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -3,7 +3,7 @@
// webhook Worker's @Processor connection) see the configured values rather than pre-dotenv defaults.
import './config/load-env';
import { NestFactory } from '@nestjs/core';
-import { ValidationPipe } from '@nestjs/common';
+import { ValidationPipe, ShutdownSignal } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger';
import helmet from 'helmet';
@@ -11,6 +11,7 @@ import { AppModule, DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPrese
import { ShutdownService } from './common/services/shutdown.service';
import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';
import { createSwaggerConfig } from './config/swagger.config';
+import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';
import {
resolveCorsPolicy,
isSwaggerEnabled,
@@ -38,6 +39,11 @@ async function bootstrap() {
bootstrapLogger.error('Unhandled promise rejection', reason instanceof Error ? reason.stack : String(reason));
});
+ // A synchronous throw from a non-promise context (e.g. a sync timer callback) is fatal — Node prints a
+ // raw stack to stderr, bypassing the structured log pipeline, and exits(1). Route the stack through the
+ // logger WITHOUT swallowing the exception, so the crash-and-restart posture is unchanged (see the helper).
+ registerUncaughtExceptionMonitor(bootstrapLogger);
+
// Fail fast: never start production with default/placeholder secrets.
assertNoDefaultSecretsInProduction({
nodeEnv: process.env.NODE_ENV,
@@ -85,8 +91,13 @@ async function bootstrap() {
);
app.use(urlencoded({ extended: true, limit: bodyLimit }));
- // Enable shutdown hooks for graceful shutdown
- app.enableShutdownHooks();
+ // Let Nest own every shutdown signal EXCEPT SIGTERM/SIGINT — those we route through the bounded
+ // drain below, so a load balancer / orchestrator observes readiness=503 and stops routing BEFORE
+ // teardown begins. (enableShutdownHooks with an EMPTY array registers ALL signals; this filtered
+ // list is non-empty, so the exclusion is honoured.)
+ app.enableShutdownHooks(
+ Object.values(ShutdownSignal).filter(s => s !== ShutdownSignal.SIGTERM && s !== ShutdownSignal.SIGINT),
+ );
// Wire up graceful shutdown service
const shutdownService = app.get(ShutdownService);
@@ -94,11 +105,22 @@ async function bootstrap() {
await app.close();
});
- // On a termination signal, flip readiness to 503 immediately so the load
- // balancer/orchestrator stops routing new traffic. This only sets a flag — NestJS's
- // own shutdown hooks (enabled above) still perform the actual app.close()/teardown.
+ // On SIGTERM/SIGINT: drain gracefully. shutdown() flips readiness to 503 immediately (the LB stops
+ // routing), keeps serving in-flight requests for a bounded grace, then runs app.close() (the SAME
+ // Nest lifecycle hooks Nest's own handler would run) and exits deterministically. A SECOND signal
+ // forces an immediate exit — a dev double-Ctrl+C, or an operator not willing to wait out a wedged
+ // teardown. The gate is a dedicated "a signal already arrived" flag, NOT isShuttingDown() (which an
+ // admin restart also sets) — so a first real signal during an admin-restart grace still drains
+ // gracefully instead of hard-exiting.
+ let signalReceived = false;
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
- process.on(signal, () => shutdownService.markShuttingDown());
+ process.on(signal, () => {
+ if (signalReceived) {
+ process.exit(130);
+ }
+ signalReceived = true;
+ shutdownService.shutdown();
+ });
}
// Enhanced Security Headers
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index 5a32fea14..d74591d53 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -26,7 +26,7 @@ jest.mock('fs', () => {
};
});
-import { DataSource } from 'typeorm';
+import { DataSource, QueryFailedError } from 'typeorm';
import { InfraController } from './infra.controller';
import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -527,6 +527,66 @@ describe('InfraController.importData round-trips export-data (no silent message/
expect(await ds.getRepository(Session).count()).toBe(1);
expect(await ds.getRepository(Message).count()).toBe(1);
});
+
+ it('propagates a genuine clear-table failure (lock/IO) instead of committing a merged restore', async () => {
+ // Pre-existing data that must survive if a clear step fails.
+ await seedSession('s1');
+ await ds.getRepository(Message).save(
+ ds.getRepository(Message).create({
+ id: 'm1',
+ sessionId: 's1',
+ chatId: 'c1',
+ from: 'a',
+ to: 'b',
+ body: 'keep me',
+ type: 'text',
+ direction: MessageDirection.INCOMING,
+ status: MessageStatus.DELIVERED,
+ }),
+ );
+
+ expect(await ds.getRepository(Message).count()).toBe(1); // sanity: seeded
+
+ // Make ONLY `DELETE FROM messages` fail with a genuine (non-missing-table) error. Previously a
+ // blind `.catch(() => {})` swallowed this and let a disjoint-id backup COMMIT a merged (not
+ // replaced) restore on SQLite; scoping the swallow to missing-table means the failure must now
+ // SURFACE (reaching the existing rollback-and-rethrow catch). A Proxy over the runner the
+ // controller creates intercepts just that one statement — no spy on `query`, so TypeORM's own
+ // internal `this.query` transaction control (BEGIN/ROLLBACK) is untouched.
+ const lockErr = new QueryFailedError(
+ 'DELETE FROM messages',
+ [],
+ Object.assign(new Error('SQLITE_BUSY: database is locked'), { code: 'SQLITE_BUSY' }),
+ );
+ let rolledBack = false;
+ const origCreate = ds.createQueryRunner.bind(ds);
+ jest.spyOn(ds, 'createQueryRunner').mockImplementation(() => {
+ const real = origCreate();
+ return new Proxy(real, {
+ get(target, prop) {
+ if (prop === 'query') {
+ return (sql: string, params?: unknown[]) =>
+ sql === 'DELETE FROM messages'
+ ? Promise.reject(lockErr)
+ : (target.query as (q: string, p?: unknown[]) => Promise<unknown>).call(target, sql, params);
+ }
+ if (prop === 'rollbackTransaction') {
+ return async () => {
+ rolledBack = true;
+ return target.rollbackTransaction.call(target);
+ };
+ }
+ const val = (target as unknown as Record<string, unknown>)[prop as string];
+ return typeof val === 'function' ? (val as (...a: unknown[]) => unknown).bind(target) : val;
+ },
+ });
+ });
+
+ await expect(controller.importData({ tables: { messages: [] } })).rejects.toThrow(/database is locked/);
+ expect(rolledBack).toBe(true);
+
+ jest.restoreAllMocks();
+ });
});
describe('InfraController.import/export preserves every data-DB table', () => {
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 1ee83f00c..8f22e3c45 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -17,6 +17,7 @@ import { CacheService } from '../../common/cache/cache.service';
import { StorageService } from '../../common/storage/storage.service';
import { ShutdownService } from '../../common/services/shutdown.service';
import { createLogger } from '../../common/services/logger.service';
+import { isMissingTableError } from '../../common/utils/db-errors';
import { ImportStorageDto } from './dto/import-storage.dto';
import * as fs from 'fs';
import * as path from 'path';
@@ -890,15 +891,26 @@ export class InfraController {
// Clear existing data (in correct order due to foreign keys). templates and
// baileys_stored_messages FK sessions ON DELETE CASCADE, so the sessions DELETE would clear
// them too; clearing them explicitly first keeps the order correct on engines where the
- // cascade is not enforced, and is a no-op when the table doesn't exist.
+ // cascade is not enforced. Tolerate a genuinely-absent table (isMissingTableError) but let any
+ // OTHER failure (lock, I/O, aborted tx) propagate to the transaction rollback below — a blind
+ // `.catch(() => {})` here could otherwise silently commit a MERGED (not replaced) restore on
+ // SQLite, violating the endpoint's "replaces existing data" contract.
+ const clearTable = async (table: string): Promise<void> => {
+ try {
+ await queryRunner.query(`DELETE FROM ${table}`);
+ } catch (err) {
+ if (!isMissingTableError(err)) throw err;
+ this.logger.debug('Skipped clearing a table that does not exist during import', { table });
+ }
+ };
await queryRunner.query('DELETE FROM webhooks');
- await queryRunner.query('DELETE FROM messages').catch(() => {});
- await queryRunner.query('DELETE FROM message_batches').catch(() => {});
- await queryRunner.query('DELETE FROM templates').catch(() => {});
- await queryRunner.query('DELETE FROM baileys_stored_messages').catch(() => {});
+ await clearTable('messages');
+ await clearTable('message_batches');
+ await clearTable('templates');
+ await clearTable('baileys_stored_messages');
// lid_mappings is not a FK to sessions, so the sessions DELETE below won't clear it; clear it
// explicitly so a restore replaces the cache rather than colliding on existing lid PKs.
- await queryRunner.query('DELETE FROM lid_mappings').catch(() => {});
+ await clearTable('lid_mappings');
await queryRunner.query('DELETE FROM sessions');
// Import sessions first
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 2519bc7ec..4f4c7963e 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -725,6 +725,58 @@ describe('SessionService', () => {
});
});
+ describe('scheduleReconnect during shutdown', () => {
+ type ReconnectInternals = {
+ reconnectStates: Map<
+ string,
+ { attempts: number; timer: NodeJS.Timeout | null; maxAttempts: number; baseDelay: number }
+ >;
+ scheduleReconnect: (id: string, s: Session) => void;
+ executeReconnect: (...args: unknown[]) => Promise<void>;
+ shutdownService?: { isShuttingDown: () => boolean };
+ };
+
+ it('does not spawn a fresh engine while the process is draining', () => {
+ jest.useFakeTimers();
+ try {
+ const i = service as unknown as ReconnectInternals;
+ i.reconnectStates.set('sess-uuid-1', { attempts: 0, timer: null, maxAttempts: 5, baseDelay: 5000 });
+ // Drain in progress: a disconnect during the shutdown window must NOT schedule a reconnect that
+ // would launch a fresh Chromium racing onModuleDestroy's teardown.
+ i.shutdownService = { isShuttingDown: () => true };
+ const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ jest.advanceTimersByTime(120000);
+
+ expect(exec).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ expect(i.reconnectStates.get('sess-uuid-1')!.attempts).toBe(0); // no attempt consumed
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('schedules a reconnect normally when not shutting down', () => {
+ jest.useFakeTimers();
+ try {
+ const i = service as unknown as ReconnectInternals;
+ i.reconnectStates.set('sess-uuid-2', { attempts: 0, timer: null, maxAttempts: 5, baseDelay: 5000 });
+ i.shutdownService = { isShuttingDown: () => false };
+ const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+
+ i.scheduleReconnect('sess-uuid-2', createMockSession());
+ expect(i.reconnectStates.get('sess-uuid-2')!.attempts).toBe(1); // an attempt was scheduled
+ jest.advanceTimersByTime(120000);
+ expect(exec).toHaveBeenCalled();
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('engine onError', () => {
type EngineCallbacks = { onError?: (reason: string) => void; onReady?: (phone: string, name: string) => void };
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index d89731223..f4378ffea 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -31,6 +31,7 @@ import {
ReactionEvent,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
+import { ShutdownService } from '../../common/services/shutdown.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
@@ -150,6 +151,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// an inbound-only migrated contact's `@lid` and `@c.us` rows bridge in the read-path (#583 R3 Ph2).
@Optional()
private readonly lidMappingStore?: LidMappingStoreService,
+ // Draining flag (set on a termination signal or an admin restart). Used to suppress a mid-shutdown
+ // reconnect that would launch a fresh Chromium racing onModuleDestroy's teardown. @Optional so the
+ // service degrades to today's behaviour if it is ever constructed without the (global) LoggerModule.
+ @Optional()
+ private readonly shutdownService?: ShutdownService,
) {}
/**
@@ -1101,6 +1107,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
private scheduleReconnect(id: string, session: Session): void {
+ // Don't launch a fresh engine (Chromium) mid-shutdown: a disconnect during the drain window would
+ // otherwise schedule a reconnect that races onModuleDestroy's teardown and could orphan a browser.
+ // Leaving the session DISCONNECTED is the correct end state — a later start()/auto-restore
+ // re-initializes it cleanly.
+ if (this.shutdownService?.isShuttingDown()) {
+ this.logger.log(`Skipping reconnect during shutdown for session: ${session.name}`, { sessionId: id });
+ return;
+ }
+
const state = this.reconnectStates.get(id);
if (!state) return;