feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Failing after 41s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 12s

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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-01 09:06:06 -05:00
1 parent 4896ee86d2
commit 10c8262824
12 files changed
+440 -7

No files matched your search

+4 -1
View File
@@ -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 = <T,>(closer: T): T => closer;
serveDeno({ upgrade, handleSignals } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
+53
View File
@@ -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);
});
+29
View File
@@ -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;
+41
View File
@@ -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 }));
});
+107
View File
@@ -0,0 +1,107 @@
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<typeof createApp> | 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) => {
const proc = spawn('npx', ['tsx', '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);
});
});