feat: shutdown teardown for plugins, providers and applications

Closing a connection meant writing process.on('SIGTERM') by hand: closeApp
drained the server and mesh links and knew nothing about the graph, and the
Bus had no shutdown event at all, so a plugin could not even observe that the
app was going away.

Implements docs/plans/2026-08-17-shutdown-teardown-design.md, D1-D8.

Three doors into one registry, with one order and one failure policy — a
@Provider may declare dispose(), a plugin may call api.onShutdown(fn), and an
application that wants neither passes createApp({ hooks: [{ onShutdown }] }).
Shipping only the plugin half would have frozen the public API around the less
common case: the thing that holds a database connection is a provider.

Callbacks take no arguments. Whatever needs closing is already in the closure
that registered it, so nothing crosses a scope and the registry needs no
container, app reference or transport. That is what keeps this a registry
rather than a second event bus — Bus.on is synchronous and emit swallows
failures on purpose, and a teardown needs the opposite of both.

Provider dispose() is registered as the provider boots rather than as it is
collected, so reverse-registration is reverse-topological order for free: a
cache that needs db closes before the db it is holding, with no second sort to
keep in step. It registers inside the try, so a provider that failed to boot is
never disposed — nothing it might close was ever opened.

Teardown runs after the drain, because an in-flight request may still be using
what a teardown is about to close, and inside the same timeoutMs, because that
number is a promise about when close() returns. teardownTimeoutMs reserves a
slice of that budget rather than extending it, and is rejected at boot rather
than clamped.

Node, Deno and Bun reach it through the close() each runtime actually uses.
app.close() returns at its no-server guard everywhere but Node, so the Deno and
Bun adapters chain it after their own drain — and app.close() now runs teardown
on that path too, since an app served through app.fetch still booted providers
that opened things. The registry drains once, so both entry points are safe.

Edge gets a doc comment and nothing else. workerd has no shutdown to intercept;
a best-effort call on an event that does not exist would be worse than saying so.

Recorded in mountPlugin's comment while widening it: "isolation is structural"
is a guarantee about the registration surface, not about the request context. A
plugin's step already receives the live context and can overwrite keys in it.
Pre-existing, unrelated, and now written where the next reader will look.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-17 11:37:31 -05:00
1 parent bfe8b66127
commit 24feca481c
16 files changed
+670 -25

No files matched your search

+142 -12
View File
@@ -12,6 +12,8 @@ import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocke
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import type { Hooks } from './types';
import {
Ctor,
getModuleMeta,
@@ -48,6 +50,13 @@ interface Registry {
stepNodes: GraphNode[];
runners: Map<string, Runner>;
providerMeta: Map<string, { optional: boolean }>;
/**
* The `@Provider` instance behind each node, kept only so a `dispose()` can be reached.
*
* `collectProviders` used to build the instance and let it live on solely inside the runner's
* closure, which meant nothing could ever call a method on it again.
*/
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
routePlans: RoutePlan[];
exportedProviders: string[];
exportedSteps: string[];
@@ -86,6 +95,14 @@ interface PipelineDeps {
export function createApp(opts: {
modules: Ctor[];
plugins?: Plugin[];
/**
* Lifecycle participation without extending the graph.
*
* A plugin means "I want to add nodes"; someone who only needs to close a connection should not
* have to declare an extension they do not want. Methods are optional so later stages can join
* without a breaking change — only `onShutdown` exists today.
*/
hooks?: Hooks[];
mesh?: MeshConfig;
limits?: RequestLimits;
devGraph?: boolean;
@@ -111,6 +128,17 @@ export function createApp(opts: {
* where passing it per call is not an option.
*/
shutdownTimeoutMs?: number;
/**
* Milliseconds reserved out of the shutdown budget for teardown, in ms (default: none reserved).
*
* Teardown runs after the drain and inside the same `timeoutMs`, so `close()` never takes longer
* than the caller asked for. Left unset, the drain may use the whole budget and teardown gets
* whatever remains — possibly nothing. Set it when a connection *must* get its chance to close:
* the drain is then bounded to `timeoutMs - teardownTimeoutMs` and this slice is guaranteed.
*
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
*/
teardownTimeoutMs?: number;
/**
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
*
@@ -158,7 +186,8 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry);
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger);
// For each route, resolve which providers/steps feed it via topo order.
@@ -236,7 +265,7 @@ export function createApp(opts: {
registry,
opts.overrides,
() => orderedProviders,
{ runners, container, providerMeta, bus, logger },
{ runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
degradedProviders,
ready,
);
@@ -292,7 +321,7 @@ export function createApp(opts: {
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger);
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs);
return {
listen,
@@ -327,6 +356,7 @@ function emptyRegistry(): Registry {
stepNodes: [],
runners,
providerMeta: new Map(),
providerInstances: new Map(),
routePlans: [],
exportedProviders: [],
exportedSteps: [],
@@ -343,6 +373,7 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides);
const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
}
}
@@ -459,12 +490,40 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
return registry;
}
/**
* Builds the teardown registry, seeds it with the application's hooks, and validates the reservation.
*
* Hooks land before plugins, so the registry running in reverse tears plugins down before the hooks
* an application registered around them. Both go into the same list: one order, one failure policy.
*/
function buildTeardownRegistry(
hooks: Hooks[] | undefined,
teardownTimeoutMs: number | undefined,
shutdownTimeoutMs: number | undefined,
): TeardownRegistry {
const budget = shutdownTimeoutMs ?? 10_000;
// Rejected rather than clamped: a reservation larger than the budget it is carved from is a
// mistake in the caller's numbers, and quietly shrinking it would hide which of the two they got
// wrong — at boot, where there is time to fix it, rather than during a shutdown.
if (teardownTimeoutMs !== undefined && teardownTimeoutMs > budget) {
throw new Error(
`teardownTimeoutMs (${teardownTimeoutMs}) cannot exceed shutdownTimeoutMs (${budget}) — ` +
'it is reserved out of that budget, not added to it',
);
}
const teardown = new TeardownRegistry();
for (const hook of hooks ?? []) if (hook.onShutdown) teardown.add(hook.onShutdown);
return teardown;
}
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -667,11 +726,13 @@ async function bootProviders(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
): Promise<string[]> {
const { runners, container, providerMeta, bus, logger } = deps;
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
const degraded: string[] = [];
for (const node of orderedProviders) {
@@ -681,6 +742,15 @@ async function bootProviders(
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
// Registered here, as it boots, rather than where it was collected. `orderedProviders` is
// topologically sorted, so registration order *is* boot order — and the registry running in
// reverse then gives dependants teardown before their dependencies for free, with no second
// sort to keep in step with this one.
//
// Inside the try on purpose: a provider that threw never provided anything, and calling
// dispose() on a half-constructed one is how a teardown finds a null connection.
const instance = providerInstances.get(node.name);
if (instance?.dispose) teardown.add(() => instance.dispose!());
bus.emit('boot:provider:ok', { name: node.name });
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
@@ -717,6 +787,8 @@ function makeAppBooter(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
@@ -1006,6 +1078,46 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
}));
}
/**
* Runs registered teardown, bounded so it cannot push `close()` past the budget it was given.
*
* Bounding lives here rather than in {@link TeardownRegistry} because the registry has no business
* knowing about deadlines — `closeApp` and `closeWithDeadline` each already own one, and a third
* implementation is how the three drift into different meanings of the same `timeoutMs`.
*
* A teardown that overruns is left running rather than awaited: the callback is someone else's code
* and there is no way to interrupt it, so the choice is between returning on time and waiting
* indefinitely. It resolves on its own timer for the same reason `closeWithDeadline` does.
*/
function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: number): Promise<void> {
if (teardown.size === 0) return Promise.resolve();
return new Promise<void>((resolve) => {
let settled = false;
const finish = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
const timer = setTimeout(
() => {
if (settled) return;
logger.warn(`shutdown teardown exceeded its ${Math.max(0, budgetMs)}ms budget — returning without it`, {
budgetMs: Math.max(0, budgetMs),
});
finish();
},
Math.max(0, budgetMs),
);
timer.unref?.();
void teardown.run(logger).then(finish, finish);
});
}
function closeApp(
server: http.Server | undefined,
meshLinks: Link[],
@@ -1013,8 +1125,17 @@ function closeApp(
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
logger: Logger,
teardown: TeardownRegistry,
reservedMs: number | undefined,
): Promise<void> {
return new Promise((resolve) => {
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
const startedAt = Date.now();
// Unset reserves nothing: the drain may use the whole budget and teardown takes what is left.
// Set, it is carved out of the same budget rather than added to it, so `close()` still returns
// within `timeoutMs` — which is the whole reason the caller set that number.
const drainBudget = timeoutMs - (reservedMs ?? 0);
const drain = new Promise<void>((resolve) => {
// A mesh app booted through `app.fetch` has links but no server, and would leak every
// teapot connection otherwise — so links close before we even check for a server.
closeLinks(meshLinks);
@@ -1026,16 +1147,20 @@ function closeApp(
if (!server) {
if (options.timeoutMs !== undefined) {
logger.warn(
'close({ timeoutMs }) has no effect here — this app has no listen()ed server. On Deno ' +
'and Bun, call close() on the server serveDeno()/serveBun() returned; it takes the ' +
'same option. On the edge the platform owns the lifecycle.',
'close({ timeoutMs }) does not drain connections here — this app has no listen()ed ' +
'server, so it only bounds teardown. On Deno and Bun, call close() on the server ' +
'serveDeno()/serveBun() returned; it takes the same option and drains too. On the ' +
'edge the platform owns the lifecycle.',
);
}
// Falls through to teardown rather than returning from close(). An app served through
// `app.fetch` still booted its providers, so it still has connections that were opened and
// are owed a close — the transport being someone else's job does not make them not ours.
// Running teardown twice is safe: the registry drains once, whichever entry point is first.
return resolve();
}
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
let settled = false;
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
@@ -1056,7 +1181,7 @@ function closeApp(
// below — `engines` in package.json only guarantees >=18, so this matters.
server.closeAllConnections();
finish();
}, timeoutMs);
}, drainBudget);
timer.unref?.();
@@ -1072,6 +1197,11 @@ function closeApp(
for (const closeStream of streams) closeStream();
server.closeIdleConnections();
});
// Teardown runs after the drain and before close() resolves: an in-flight request may still be
// using the connection a teardown is about to close, so draining first is not an ordering
// preference. It gets whatever is left of the budget — at least the reservation, if one was made.
return drain.then(() => runTeardown(teardown, logger, timeoutMs - (Date.now() - startedAt)));
}
/** Best-effort close of every mesh link, ignoring individual failures. */
+12
View File
@@ -1,6 +1,7 @@
import type http from 'http';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { TeardownFn } from '../lifecycle';
import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata';
@@ -103,3 +104,14 @@ export interface MeshConfig {
*/
heartbeatMs?: number;
}
/**
* Lifecycle participation for an application that does not want to be a plugin.
*
* Every method is optional, and the shape is an object rather than a single callback so later
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
*/
export interface Hooks {
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
onShutdown?: TeardownFn;
}
+6 -1
View File
@@ -119,7 +119,12 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.stop(false),
// 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
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.stop(false).then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
+6 -1
View File
@@ -78,7 +78,12 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.shutdown(),
// 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
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.shutdown().then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
+7
View File
@@ -15,6 +15,13 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*/
export function edgeHandler(
app: App,
+70
View File
@@ -0,0 +1,70 @@
// src/lifecycle.ts — the teardown registry. Knows nothing about plugins, providers, apps or HTTP;
// the doors into it live where those things do.
import type { Logger } from './logger';
/**
* Something to run before the app goes away.
*
* Takes no arguments on purpose. State lives in the closure that registered it — a provider's
* `dispose()` already holds its own connection, and a plugin's callback already holds whatever the
* plugin built. Nothing has to cross a scope, which is what makes this a registry rather than an
* event bus: a bus solves "tell someone I do not know", and this is "run the thing I registered".
*/
export type TeardownFn = () => void | Promise<void>;
/**
* Await-aware teardown, deliberately not the {@link Bus}.
*
* `Bus.on` takes a synchronous listener and `emit` swallows failures, both so that an observer can
* never break the pipeline. A teardown needs the opposite of each: it must be awaited, and its
* failure must be visible. Same word, opposite guarantees — see D1 of the design.
*
* Bounding is deliberately *not* here. `closeApp` and `closeWithDeadline` already implement a
* deadline each, and a third implementation is how the three drift into different meanings of the
* same `timeoutMs`.
*/
export class TeardownRegistry {
private readonly callbacks: TeardownFn[] = [];
private drained = false;
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
add(fn: TeardownFn): void {
this.callbacks.push(fn);
}
/** How many callbacks are registered; lets a caller skip the whole path when nothing wants it. */
get size(): number {
return this.callbacks.length;
}
/**
* Run every callback, newest first, awaiting each.
*
* **Reverse registration order is load-bearing.** Providers register as they boot, and they boot
* in topological order, so reversing registration is what gives dependants teardown before their
* dependencies: a `cache` that needs `db` closes before the `db` it is still holding.
*
* Sequential rather than parallel, for the same reason — an order only means something if it is
* waited on.
*
* A failing callback is reported and the next one still runs. One broken teardown must not strand
* the rest or leave the process up. This mirrors `Bus`'s "a subscriber cannot break the system",
* but with the visibility `Bus` lacks: `Bus` swallows silently because no logger existed when it
* was written, and one exists now.
*
* Never throws, and never runs twice — `close()` is called twice by more real applications than
* anyone expects, and a second call must not re-close what the first one closed.
*/
async run(logger: Logger): Promise<void> {
if (this.drained) return;
this.drained = true;
for (let index = this.callbacks.length - 1; index >= 0; index--) {
try {
await this.callbacks[index]();
} catch (error) {
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
}
}
}
}
+21 -4
View File
@@ -1,4 +1,5 @@
import { Bus } from './bus';
import type { TeardownFn } from './lifecycle';
/** A step or provider a plugin contributes to the graph. */
export interface ScopeNode {
@@ -13,18 +14,34 @@ export interface ScopeNode {
export interface ScopeApi {
add(node: ScopeNode): void;
}
/** The capabilities handed to a plugin: event subscription and node registration only. */
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
/**
* Run something before the app closes — closing a pool, stopping a timer, flushing a buffer.
*
* Takes no arguments: whatever needs closing is already in the closure of the plugin that opened
* it. It is awaited, unlike a `bus.on` listener, and a failure is logged rather than swallowed.
*/
onShutdown(fn: TeardownFn): void;
}
/** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void;
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void {
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
// Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
//
// "Isolation is structural" means this list and nothing else — it is a guarantee about the
// *registration surface*, not about the request context. A plugin's step receives the live
// context like any other step and can overwrite keys in it (`src/pipeline.ts`, `Object.assign`),
// which is a separate, pre-existing question this list has never covered.
//
// `onShutdown` is the first capability here the framework must *wait* for: nothing a plugin did
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
}