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
+445
-7
No files matched your search
+59
-2
@@ -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<void>((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<void> =>
|
||||
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<void> => {
|
||||
clearSignalHandlers();
|
||||
return closeApp(
|
||||
server,
|
||||
meshLinks,
|
||||
streams,
|
||||
options,
|
||||
opts.shutdownTimeoutMs,
|
||||
logger,
|
||||
teardown,
|
||||
opts.teardownTimeoutMs,
|
||||
);
|
||||
};
|
||||
|
||||
const handleSignals = <T extends (options?: { timeoutMs?: number }) => Promise<void>>(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,
|
||||
|
||||
@@ -38,6 +38,15 @@ export interface Explain {
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/**
|
||||
* 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<T extends (options?: { timeoutMs?: number }) => Promise<void>>(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
|
||||
|
||||
+5
-1
@@ -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<void> =>
|
||||
// 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<void> =>
|
||||
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',
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
+5
-1
@@ -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<void> =>
|
||||
// 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<void> =>
|
||||
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' },
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -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<void>, 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;
|
||||
}
|
||||
Reference in new issue
Block a user