From e5d5fb801a1b34c1447f806b8098b7a2c5f14507 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 09:06:06 -0500 Subject: [PATCH] feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals }) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README promised shutdown was *"an extension point, not a SIGTERM handler you write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the *content* of teardown, but nothing called `close()`, so every application still wrote the handler — and wrote it three times, because the spelling is per runtime. Forget it and the container is SIGKILLed after its grace period, every `dispose()` the registry so carefully ordered never runs, and nothing reports it. `createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit. Off by default, and that is the design rather than caution: a library that installs process-wide handlers behind your back is worse than one that installs none, because when the process exits is the application's call. Both halves are now supported and documented — keep the handler, or hand it over. What is not optional either way is that *something* calls `close()`, and the README now says so instead of implying the framework already had it covered. Declared once on `createApp`, wired per runtime by whichever boot call runs: `listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their* server to `app.handleSignals`, which returns a close that also unregisters. On Deno that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener` holds the process open, so an app that closed itself would otherwise hang. Unregistering first also means a *second* signal falls through to the platform default and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a teardown that is stuck, and swallowing it for the length of a 10s budget would read as a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there. Tested against real processes, because a handler whose job is to exit its own process cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`, which is the API that actually differs. Bun shares Node's `process` path. Closes #70. Signed-off-by: Diego Resendez --- README.md | 3 +- src/app/index.ts | 61 ++++++++++++++- src/app/types.ts | 9 +++ src/bun.ts | 6 +- src/deno.ts | 6 +- src/http/signals-shutdown.ts | 125 +++++++++++++++++++++++++++++++ test/deno-adapter.test.ts | 5 +- test/deno/signals.test.ts | 53 +++++++++++++ test/interop/_signal-app-deno.ts | 29 +++++++ test/interop/_signal-app.ts | 41 ++++++++++ test/shutdown-signals.test.ts | 112 +++++++++++++++++++++++++++ tsconfig.json | 2 +- 12 files changed, 445 insertions(+), 7 deletions(-) create mode 100644 src/http/signals-shutdown.ts create mode 100644 test/deno/signals.test.ts create mode 100644 test/interop/_signal-app-deno.ts create mode 100644 test/interop/_signal-app.ts create mode 100644 test/shutdown-signals.test.ts diff --git a/README.md b/README.md index c54acaa..9dfcc8e 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,8 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. -- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. +- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. +- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. diff --git a/src/app/index.ts b/src/app/index.ts index 3a9e3e4..9e69c3e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -13,6 +13,7 @@ import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { TeardownRegistry } from '../lifecycle'; +import { installSignalHandlers } from '../http/signals-shutdown'; import type { Hooks } from './types'; import { Ctor, @@ -139,6 +140,25 @@ export function createApp(opts: { * Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently. */ teardownTimeoutMs?: number; + /** + * Register `SIGINT`/`SIGTERM` to run `close()` and exit the process (default: `false`). + * + * Off by default because a library that installs process-wide handlers behind your back is worse + * than one that installs none — when the process exits is the application's call, not ours. Turn + * it on and the framework absorbs the last runtime difference an app otherwise has: `process.on` + * on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each. + * + * Leaving it off is a supported choice, not a gap — write the handler yourself if you want the + * control. What is *not* optional either way is that something calls `close()`: the teardown + * registry only runs from there, so a container `SIGKILL`ed after its grace period skips every + * `dispose()` the registry so carefully ordered, and reports nothing. + * + * Registered by `listen()`, `serveDeno()` and `serveBun()`, and taken back off by `close()` — + * so a *second* signal arriving mid-shutdown falls through to the platform default and ends the + * process at once. Ctrl-C twice is the way out of a teardown that is stuck; once is the way to + * let it finish. + */ + handleSignals?: boolean; /** * Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY). * @@ -319,15 +339,52 @@ export function createApp(opts: { }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); + // After the socket is up, so a boot that throws never leaves a handler behind pointing at an + // app that never served. + handleSignals(close); return server; }; - const close = (options: { timeoutMs?: number } = {}): Promise => - closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs); + // Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is + // load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app + // that closed itself and expected to exit would simply hang. + let removeSignalHandlers: (() => void) | undefined; + + const clearSignalHandlers = (): void => { + removeSignalHandlers?.(); + removeSignalHandlers = undefined; + }; + + const close = (options: { timeoutMs?: number } = {}): Promise => { + clearSignalHandlers(); + return closeApp( + server, + meshLinks, + streams, + options, + opts.shutdownTimeoutMs, + logger, + teardown, + opts.teardownTimeoutMs, + ); + }; + + const handleSignals = Promise>(closer: T): T => { + if (!opts.handleSignals) return closer; + + const wrapped = ((options?: { timeoutMs?: number }) => { + clearSignalHandlers(); + return closer(options); + }) as T; + + removeSignalHandlers = installSignalHandlers(() => wrapped(), logger); + return wrapped; + }; return { listen, close, + handleSignals, ready, fetch: fetchFn, upgrade: upgradeFn, diff --git a/src/app/types.ts b/src/app/types.ts index 578f728..6e9626c 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -38,6 +38,15 @@ export interface Explain { export interface App { listen(port: number): Promise; close(options?: { timeoutMs?: number }): Promise; + /** + * Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or + * returns `closer` untouched when `createApp({ handleSignals })` was not set. + * + * `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains + * their server, which is why the option is declared once on `createApp` and works on all three. + * Call it yourself only if you serve the app some other way. + */ + handleSignals Promise>(closer: T): T; /** * Resolves the dependency graph, then returns. For a mesh app that means connecting to its * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every diff --git a/src/bun.ts b/src/bun.ts index 50f66d0..32e8b06 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -117,7 +117,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu // Object.assign rather than a fresh object: Bun.serve returns more than the ambient above // declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name. return Object.assign(server, { - close: (closeOptions: { timeoutMs?: number } = {}): Promise => + // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this + // runtime's own signal API — and so the close it returns takes the handlers back off, which + // Deno requires to exit at all. + close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise => closeWithDeadline( // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // `app.close()` returns at its no-server guard on Bun, but still drains the teardown @@ -133,5 +136,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu runtime: 'bun', }), ), + ), }); } diff --git a/src/deno.ts b/src/deno.ts index 4deca38..323a61c 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -76,7 +76,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { // Object.assign rather than a fresh object: Deno.serve returns more than the ambient above // declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name. return Object.assign(server, { - close: (closeOptions: { timeoutMs?: number } = {}): Promise => + // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this + // runtime's own signal API — and so the close it returns takes the handlers back off, which + // Deno requires to exit at all. + close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise => closeWithDeadline( // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // `app.close()` returns at its no-server guard on Deno, but still drains the teardown @@ -101,5 +104,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { { timeoutMs: ms, runtime: 'deno' }, ), ), + ), }); } diff --git a/src/http/signals-shutdown.ts b/src/http/signals-shutdown.ts new file mode 100644 index 0000000..dd6db30 --- /dev/null +++ b/src/http/signals-shutdown.ts @@ -0,0 +1,125 @@ +// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime. + +import type { Logger } from '../logger'; + +/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */ +const SIGNALS = ['SIGINT', 'SIGTERM'] as const; + +type Signal = (typeof SIGNALS)[number]; + +interface SignalApi { + runtime: string; + on(signal: Signal, handler: () => void): void; + off(signal: Signal, handler: () => void): void; + exit(code: number): void; +} + +interface DenoSignals { + addSignalListener(signal: Signal, handler: () => void): void; + removeSignalListener(signal: Signal, handler: () => void): void; + exit(code: number): void; +} + +interface ProcessSignals { + on(signal: Signal, handler: () => void): unknown; + off?(signal: Signal, handler: () => void): unknown; + removeListener?(signal: Signal, handler: () => void): unknown; + exit(code: number): void; +} + +/** + * Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and + * `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively + * is the one `removeSignalListener` can take back — which matters here, because a Deno signal + * listener holds the process open until it is removed. Node and Bun share `process`. + */ +function signalApi(): SignalApi | undefined { + const deno = (globalThis as { Deno?: DenoSignals }).Deno; + + if (typeof deno?.addSignalListener === 'function') + return { + runtime: 'deno', + on: (signal, handler) => deno.addSignalListener(signal, handler), + off: (signal, handler) => deno.removeSignalListener(signal, handler), + exit: (code) => deno.exit(code), + }; + + const proc = (globalThis as { process?: ProcessSignals }).process; + + if (typeof proc?.on === 'function' && typeof proc.exit === 'function') { + const remove = proc.off ?? proc.removeListener; + + return { + runtime: 'node', + on: (signal, handler) => void proc.on(signal, handler), + off: (signal, handler) => void remove?.call(proc, signal, handler), + exit: (code) => proc.exit(code), + }; + } + + return undefined; +} + +/** + * Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those + * handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps + * the process from exiting on its own. + * + * The close is expected to unregister first thing, which leaves a **second signal falling through + * to the platform default** — an immediate end to the process, teardown or no teardown. That is + * the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and + * swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator + * sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path. + * + * If the close throws, the process still exits — with 1, because a shutdown that failed halfway is + * not a clean one and an orchestrator should be told. + */ +export function installSignalHandlers(close: () => Promise, logger: Logger): () => void { + const api = signalApi(); + + if (!api) { + logger.warn( + 'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself', + ); + return () => {}; + } + + const registered: Array<[Signal, () => void]> = []; + + const remove = (): void => { + while (registered.length) { + const [signal, handler] = registered.pop()!; + api.off(signal, handler); + } + }; + + for (const signal of SIGNALS) { + const handler = (): void => { + logger.info(`${signal} received — closing`, { signal, runtime: api.runtime }); + void close().then( + () => api.exit(0), + (error: unknown) => { + logger.error(`shutdown failed after ${signal}`, { + signal, + err: error instanceof Error ? error.message : String(error), + }); + api.exit(1); + }, + ); + }; + + try { + api.on(signal, handler); + registered.push([signal, handler]); + } catch (error) { + // Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the + // platform does have beats refusing to start over the one it does not. + logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, { + signal, + err: error instanceof Error ? error.message : String(error), + }); + } + } + + return remove; +} diff --git a/test/deno-adapter.test.ts b/test/deno-adapter.test.ts index 568218d..2c9083e 100644 --- a/test/deno-adapter.test.ts +++ b/test/deno-adapter.test.ts @@ -29,7 +29,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request', }); const upgrade = vi.fn().mockResolvedValue(undefined); - serveDeno({ upgrade } as unknown as App); + // `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity + // it returns is exactly what `createApp` returns when `handleSignals` is left off. + const handleSignals = (closer: T): T => closer; + serveDeno({ upgrade, handleSignals } as unknown as App); const info = { get remoteAddr() { if (upgraded) throw new TypeError('Request closed'); diff --git a/test/deno/signals.test.ts b/test/deno/signals.test.ts new file mode 100644 index 0000000..ec8d7a3 --- /dev/null +++ b/test/deno/signals.test.ts @@ -0,0 +1,53 @@ +// `createApp({ handleSignals: true })` under the real Deno runtime. +// +// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno +// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed — +// so an app that closed itself and forgot to unregister would hang here and nowhere else. +// +// Run with: npm run test:deno +import { assert, assertEquals } from 'jsr:@std/assert'; + +const HARNESS = 'test/interop/_signal-app-deno.ts'; + +async function run(): Promise<{ code: number; lines: string[] }> { + const child = new Deno.Command('deno', { + args: ['run', '--allow-all', '--no-check', HARNESS], + stdout: 'piped', + stderr: 'inherit', + }).spawn(); + + const lines: string[] = []; + let buffered = ''; + let signalled = false; + + const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader(); + const pump = (async () => { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buffered += value; + const parts = buffered.split('\n'); + buffered = parts.pop() ?? ''; + for (const line of parts.filter(Boolean)) { + lines.push(line); + if (!signalled && line.includes('"ready"')) { + signalled = true; + child.kill('SIGTERM'); + } + } + } + })(); + + const status = await child.status; + await pump; + return { code: status.code, lines }; +} + +Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => { + const { code, lines } = await run(); + assert( + lines.some((l) => l.includes('"disposed"')), + `dispose() never ran — got: ${lines.join(' | ')}`, + ); + assertEquals(code, 0); +}); diff --git a/test/interop/_signal-app-deno.ts b/test/interop/_signal-app-deno.ts new file mode 100644 index 0000000..be61e5e --- /dev/null +++ b/test/interop/_signal-app-deno.ts @@ -0,0 +1,29 @@ +// Not a test — a Deno app with `handleSignals: true`, spawned by test/deno/signals.test.ts. +// Deno's test runner only discovers *.test.ts, so this file is ignored by `deno test`. +// +// It exists because Deno is where the signal API actually differs: `Deno.addSignalListener` and +// `Deno.exit` rather than `process.on`/`process.exit`, and a listener that holds the process open +// until it is removed. Node passing says nothing about any of that. +import 'npm:reflect-metadata'; +import { createApp, Module } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Module({ mountpoint: '/', controllers: [] }) +class Mod {} + +// A hook rather than a provider's `dispose()`: on Deno nothing boots until the first request, so an +// unvisited app has no provider to dispose and the run would pass without proving anything. The +// hook registers at `createApp`, which makes "teardown ran" mean "close() was reached". +const app = createApp({ + modules: [Mod], + handleSignals: true, + hooks: [{ onShutdown: () => console.log(JSON.stringify({ disposed: true })) }], +}); + +// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen` +// synchronously from inside `Deno.serve`, so a parent that signals on that line races the handler +// registration that happens a few statements later and wins. +const server = serveDeno(app, { port: 0, onListen: () => {} }); + +console.log(JSON.stringify({ ready: true })); +void server; diff --git a/test/interop/_signal-app.ts b/test/interop/_signal-app.ts new file mode 100644 index 0000000..a77478c --- /dev/null +++ b/test/interop/_signal-app.ts @@ -0,0 +1,41 @@ +// Not a test — a Node app with `handleSignals: true`, spawned by shutdown-signals.test.ts. +// +// Signal handling can only be told apart from doing nothing by a real process that really gets a +// real signal: an in-process test would have to fire the handler by hand, and the handler's whole +// job is to exit the process it is running in. +// +// Prints one JSON line per event on stdout: {"ready":port}, then {"disposed":n} per dispose call. +import 'reflect-metadata'; +import { createApp, Provider, Route, Get, Module } from '../../src/index'; + +const SLOW = Number(process.env.DISPOSE_DELAY_MS ?? 0); +let disposals = 0; + +@Provider({ provides: 'db' }) +class Db { + provide() { + return { db: { name: 'db' } }; + } + + async dispose() { + if (SLOW) await new Promise((r) => setTimeout(r, SLOW)); + disposals++; + console.log(JSON.stringify({ disposed: disposals })); + } +} + +@Route('/') +class Api { + @Get('/ping') ping() { + return { ok: true }; + } +} + +@Module({ mountpoint: '/', controllers: [Api], providers: [Db] }) +class Mod {} + +const app = createApp({ modules: [Mod], handleSignals: process.env.HANDLE_SIGNALS !== 'false' }); + +void app.listen(0).then((server) => { + console.log(JSON.stringify({ ready: (server.address() as { port: number }).port })); +}); diff --git a/test/shutdown-signals.test.ts b/test/shutdown-signals.test.ts new file mode 100644 index 0000000..5afd6ca --- /dev/null +++ b/test/shutdown-signals.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { createApp, Module } from '../src'; + +@Module({ mountpoint: '/', controllers: [] }) +class Empty {} + +let app: ReturnType | undefined; +let child: ChildProcess | undefined; + +afterEach(async () => { + await app?.close(); + app = undefined; + child?.kill('SIGKILL'); + child = undefined; +}); + +const disposed = (r: { lines: string[] }) => r.lines.filter((l) => l.includes('"disposed"')); +const handled = (r: { lines: string[] }) => r.lines.some((l) => l.includes('received — closing')); +const listeners = () => process.listenerCount('SIGINT') + process.listenerCount('SIGTERM'); + +describe('handleSignals registration', () => { + it('registers nothing by default — a library must not own when the process exits', async () => { + const before = listeners(); + app = createApp({ modules: [Empty] }); + await app.listen(0); + expect(listeners()).toBe(before); + }); + + it('registers SIGINT and SIGTERM when asked, and takes both back off in close()', async () => { + const before = listeners(); + const opted = createApp({ modules: [Empty], handleSignals: true }); + await opted.listen(0); + expect(listeners()).toBe(before + 2); + + // Not tidiness: on Deno a live signal listener holds the process open, so an app that closed + // itself and expected to exit would hang. Node is where it is observable. + await opted.close(); + expect(listeners()).toBe(before); + }); +}); + +/** Boots the harness app, waits for its `ready` line, and resolves once it has exited. */ +function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwice = false) { + return new Promise<{ code: number | null; signal: NodeJS.Signals | null; lines: string[] }>((resolve, reject) => { + // `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further + // down, and on Linux the signal then lands on the wrapper while the app never hears it — which + // is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader` + // because it is the one form that works on both the Node 18 floor CI builds against and the + // current release. + const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], { + env: { ...process.env, ...env }, + stdio: ['ignore', 'pipe', 'inherit'], + }); + child = proc; + + const lines: string[] = []; + let ready = false; + let buffered = ''; + + proc.stdout.on('data', (chunk: Buffer) => { + buffered += chunk.toString(); + const parts = buffered.split('\n'); + buffered = parts.pop() ?? ''; + + for (const line of parts.filter(Boolean)) { + lines.push(line); + if (!ready && line.includes('"ready"')) { + ready = true; + proc.kill(signal); + if (sendTwice) setTimeout(() => proc.kill(signal), 20); + } + } + }); + + proc.on('error', reject); + proc.on('exit', (code, exitSignal) => resolve({ code, signal: exitSignal, lines })); + }); +} + +// These need a real process because the handler's job is to exit the one it runs in — firing it by +// hand in the test runner would either take the runner down or prove nothing. +describe('handleSignals end to end', () => { + it('SIGTERM runs teardown and exits 0', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM'); + expect(disposed(r)).toHaveLength(1); + expect(r.code).toBe(0); + }); + + it('SIGINT does the same — Ctrl-C is not a different kind of shutdown', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGINT'); + expect(disposed(r)).toHaveLength(1); + expect(r.code).toBe(0); + }); + + // The escape hatch, and the reason `close()` unregisters before it starts draining: a second + // signal finds no handler and gets the platform default. Ctrl-C twice ends a stuck teardown + // rather than waiting out the whole shutdown budget. + it('lets a second signal end a shutdown that is still draining', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM', { DISPOSE_DELAY_MS: '2000' }, true); + expect(handled(r)).toBe(true); // the first signal was ours + expect(disposed(r)).toHaveLength(0); // the second one did not wait for the 2s dispose + expect(r.code).not.toBe(0); + }); + + it('leaves the process to its default fate when handleSignals is off', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM', { HANDLE_SIGNALS: 'false' }); + expect(handled(r)).toBe(false); // nothing of ours ran at all + expect(disposed(r)).toHaveLength(0); + expect(r.code).not.toBe(0); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 8d268e0..0d0bf73 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,5 +15,5 @@ "forceConsistentCasingInFileNames": true }, "include": ["src", "test", "example"], - "exclude": ["test/deno", "test/bun", "test/edge"] + "exclude": ["test/deno", "test/bun", "test/edge", "test/interop/_signal-app-deno.ts"] }