Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(bootstrap): exit non-zero when the HTTP bind fails after full init (#949)

Yudhi Armyndharise1fd37675764
diff --git a/src/config/bootstrap-fatal.spec.ts b/src/config/bootstrap-fatal.spec.ts
new file mode 100644
index 000000000..eeeec9ff4
--- /dev/null
+++ b/src/config/bootstrap-fatal.spec.ts
@@ -0,0 +1,99 @@
+import { runBootstrapOrExit, BootstrapFatalDeps } from './bootstrap-fatal';
+
+describe('runBootstrapOrExit', () => {
+ const makeDeps = () => {
+ const logs: Array<[string, string | undefined]> = [];
+ const exitCalls: number[] = [];
+ const deps: BootstrapFatalDeps = {
+ logger: {
+ error: (m: string, d?: string) => {
+ logs.push([m, d]);
+ },
+ },
+ exit: (code: number) => {
+ exitCalls.push(code);
+ },
+ };
+ return { deps, logs, exitCalls };
+ };
+
+ it('logs and exits(1) when bootstrap rejects with a bind failure (EADDRINUSE from listen())', async () => {
+ const { deps, logs, exitCalls } = makeDeps();
+ const err = Object.assign(new Error('listen EADDRINUSE: address already in use 0.0.0.0:2785'), {
+ code: 'EADDRINUSE',
+ });
+ const closeApp = jest.fn().mockResolvedValue(undefined);
+
+ await runBootstrapOrExit(() => Promise.reject(err), { ...deps, closeApp });
+
+ expect(exitCalls).toEqual([1]);
+ expect(logs).toHaveLength(1);
+ expect(logs[0][0]).toMatch(/Fatal error during bootstrap/);
+ expect(logs[0][1]).toContain('EADDRINUSE'); // err.stack
+ // Teardown ran BEFORE the exit so sessions/connections don't outlive the process.
+ expect(closeApp).toHaveBeenCalledTimes(1);
+ });
+
+ it('never logs, tears down, or exits on a successful boot', async () => {
+ const { deps, logs, exitCalls } = makeDeps();
+ const closeApp = jest.fn().mockResolvedValue(undefined);
+
+ await runBootstrapOrExit(() => Promise.resolve(), { ...deps, closeApp });
+
+ expect(exitCalls).toEqual([]);
+ expect(logs).toEqual([]);
+ expect(closeApp).not.toHaveBeenCalled();
+ });
+
+ it('still exits(1) when the teardown rejects', async () => {
+ const { deps, exitCalls } = makeDeps();
+ const closeApp = jest.fn().mockRejectedValue(new Error('close wedged'));
+
+ await runBootstrapOrExit(() => Promise.reject(new Error('boom')), { ...deps, closeApp });
+
+ expect(exitCalls).toEqual([1]);
+ });
+
+ it('still exits(1) when the teardown hangs past the bound', async () => {
+ const { deps, exitCalls } = makeDeps();
+ const closeApp = jest.fn(() => new Promise<void>(resolve => setTimeout(resolve, 250)));
+
+ await runBootstrapOrExit(() => Promise.reject(new Error('boom')), { ...deps, closeApp, closeTimeoutMs: 5 });
+
+ expect(exitCalls).toEqual([1]);
+ expect(closeApp).toHaveBeenCalledTimes(1);
+ });
+
+ it('still exits(1) when the logger throws — the exit is the guarantee', async () => {
+ const { deps, exitCalls } = makeDeps();
+ deps.logger = {
+ error: () => {
+ throw new Error('logger is down');
+ },
+ };
+
+ await runBootstrapOrExit(() => Promise.reject(new Error('boom')), deps);
+
+ expect(exitCalls).toEqual([1]);
+ });
+
+ it('stringifies a non-Error rejection without throwing', async () => {
+ const { deps, logs, exitCalls } = makeDeps();
+
+ // Deliberately a non-Error rejection: the handler must stringify it and still exit.
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
+ await runBootstrapOrExit(() => Promise.reject('a bare string'), deps);
+
+ expect(exitCalls).toEqual([1]);
+ expect(logs[0][1]).toContain('a bare string');
+ });
+
+ it('skips teardown when no closeApp is provided (failure before app creation)', async () => {
+ const { deps, logs, exitCalls } = makeDeps();
+
+ await runBootstrapOrExit(() => Promise.reject(new Error('bad secrets')), deps);
+
+ expect(exitCalls).toEqual([1]);
+ expect(logs[0][1]).toContain('bad secrets');
+ });
+});
diff --git a/src/config/bootstrap-fatal.ts b/src/config/bootstrap-fatal.ts
new file mode 100644
index 000000000..e1f0e63c4
--- /dev/null
+++ b/src/config/bootstrap-fatal.ts
@@ -0,0 +1,73 @@
+/**
+ * Fatal-bootstrap handling: log, best-effort teardown, then a real exit.
+ *
+ * Extracted from `main.ts` so the failure contract is unit-tested without booting the app.
+ *
+ * Why a real `process.exit(1)` instead of only setting `process.exitCode`: Nest's `listen()` runs the
+ * FULL module init (sessions, Redis, Postgres, Chromium) before binding the port. If the bind then
+ * fails (EADDRINUSE), setting `exitCode` alone leaves the event loop held open by those very handles —
+ * the process becomes a zombie that serves no HTTP yet keeps the WhatsApp sessions running, and Docker's
+ * `restart: unless-stopped` never fires because the container stays "running". Exiting lets the
+ * orchestrator restart us onto a free port (or surface the conflict), and Puppeteer's own `exit`
+ * handlers kill the browser children as the process goes down.
+ */
+
+/** Minimal structured-logger surface (satisfied by createLogger()'s result). */
+export interface BootstrapFatalLogger {
+ error: (message: string, detail?: string) => void;
+}
+
+export interface BootstrapFatalDeps {
+ logger: BootstrapFatalLogger;
+ /**
+ * Best-effort teardown of whatever the app initialised before the failure (engine sessions, Redis/pg
+ * connections). Bounded by `closeTimeoutMs` — a wedged teardown must never block the exit.
+ */
+ closeApp?: () => Promise<unknown>;
+ /** Injectable for tests; defaults to `process.exit`. */
+ exit?: (code: number) => void;
+ /** Bound on `closeApp()`. Defaults to `DEFAULT_BOOTSTRAP_CLOSE_TIMEOUT_MS`. */
+ closeTimeoutMs?: number;
+}
+
+export const DEFAULT_BOOTSTRAP_CLOSE_TIMEOUT_MS = 5000;
+
+/**
+ * Run `bootstrap()`; on ANY rejection (e.g. `listen()` failing with EADDRINUSE after full init), log the
+ * fatal error, run the bounded best-effort teardown, and exit non-zero. A successful boot returns
+ * normally and never touches `exit`.
+ *
+ * Every step is guarded: a throwing logger or teardown degrades to losing that one step while the exit
+ * still proceeds — the exit is the guarantee the orchestrator relies on.
+ */
+export async function runBootstrapOrExit(bootstrap: () => Promise<unknown>, deps: BootstrapFatalDeps): Promise<void> {
+ try {
+ await bootstrap();
+ return;
+ } catch (err) {
+ try {
+ deps.logger.error(
+ 'Fatal error during bootstrap — process will exit',
+ err instanceof Error ? err.stack : String(err),
+ );
+ } catch {
+ /* never mask the original fatal error */
+ }
+ }
+
+ if (deps.closeApp) {
+ try {
+ const closeApp = deps.closeApp;
+ await Promise.race([
+ Promise.resolve().then(() => closeApp()),
+ new Promise<void>(resolve => {
+ setTimeout(resolve, deps.closeTimeoutMs ?? DEFAULT_BOOTSTRAP_CLOSE_TIMEOUT_MS).unref();
+ }),
+ ]);
+ } catch {
+ /* best-effort teardown — the exit below is what matters */
+ }
+ }
+
+ (deps.exit ?? ((code: number) => process.exit(code)))(1);
+}
diff --git a/src/main.ts b/src/main.ts
index 890f84f8d..56a4f0d67 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 { ShutdownSignal } from '@nestjs/common';
+import { INestApplication, ShutdownSignal } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger';
import helmet from 'helmet';
@@ -12,6 +12,7 @@ import { ShutdownService } from './common/services/shutdown.service';
import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';
import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';
+import { runBootstrapOrExit } from './config/bootstrap-fatal';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
import { applyGlobalValidation } from './config/app-validation';
@@ -33,6 +34,11 @@ import { randomBytes } from 'crypto';
import { readFileSync } from 'fs';
import { extname, join } from 'path';
+// The created app, exposed at module scope so the fatal handler below can run a best-effort teardown
+// (engine sessions, Redis/pg) when bootstrap fails AFTER NestFactory.create succeeded — notably a
+// listen() bind failure (EADDRINUSE), where full init already ran.
+let appInstance: INestApplication | undefined;
+
async function bootstrap() {
// Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset/invalid → INFO.
const requestedLevel = process.env.LOG_LEVEL?.trim().toLowerCase();
@@ -83,6 +89,7 @@ async function bootstrap() {
// Disable Nest's default body parser so we can set an explicit size cap below.
const app = await NestFactory.create(AppModule, { bodyParser: false });
+ appInstance = app;
// Aggregate in-flight body budget (DoS hardening): once too many body bytes are being buffered
// across ALL connections, new requests get 503 + Retry-After without their body being read.
@@ -348,7 +355,13 @@ async function bootstrap() {
}
}
-bootstrap().catch((err: unknown) => {
- createLogger('Bootstrap').error('Fatal error during bootstrap', err instanceof Error ? err.stack : String(err));
- process.exitCode = 1;
+// A failed bootstrap MUST terminate the process with a non-zero code, not just set `process.exitCode`:
+// listen() runs the FULL init (sessions, Redis, pg, Chromium) before binding the port, so a bind failure
+// (EADDRINUSE) would otherwise leave a zombie process — no HTTP port, yet still holding the event loop
+// open and running WhatsApp sessions, invisible to Docker's restart policy. runBootstrapOrExit logs the
+// failure, runs a bounded best-effort app.close() teardown, then exits(1); a successful boot returns
+// without touching exit. Puppeteer's own `exit` handlers kill any browser children still up.
+void runBootstrapOrExit(bootstrap, {
+ logger: createLogger('Bootstrap'),
+ closeApp: () => (appInstance ? appInstance.close() : Promise.resolve()),
});