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

+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 });
}
}
}
}