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>
This commit is contained in:
12 files changed
+440
-7
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user