Files
core/test/shutdown-signals.test.ts
T
chrnx e5d5fb801a
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
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>
2026-09-01 09:09:56 -05:00

113 lines
4.6 KiB
TypeScript

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) => {
// `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);
});
});