diff --git a/CHANGELOG.md b/CHANGELOG.md index bece1f2..8cddd15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,25 @@ npm treats versions as semver and semver forbids leading zeros. ### Added +- Shutdown is now an extension point. A `@Provider` may declare `dispose()`, a plugin may call + `api.onShutdown(fn)`, and an application may pass `createApp({ hooks: [{ onShutdown }] })` — three + doors into one registry, so an app closing a connection no longer writes `process.on('SIGTERM')` + by hand. Callbacks are **awaited**, unlike `bus.on` listeners, and take no arguments: whatever + needs closing is already in the closure that registered it. + + They run in reverse boot order, so a `cache` that needs `db` closes before the `db` it is holding. + A failing teardown is logged and the rest still run — one broken callback must not leave the + process up. Everything happens inside `close()`'s existing deadline; `createApp({ teardownTimeoutMs })` + reserves a slice of that budget when a connection must get its chance to close, and is rejected at + boot if it exceeds `shutdownTimeoutMs`. + + Node, Deno and Bun behave identically — on Deno and Bun the teardown runs from the `close()` on the + server `serveDeno()`/`serveBun()` returned. **The edge cannot participate**: workerd has no + shutdown to intercept, so anything that must be released belongs in the request that acquired it. + + Nothing changes for existing code. `Plugin`'s signature is unchanged, `Hooks` methods are optional, + and `dispose()` is called only if present. + - `limits.maxConnections` changes Node's previously unlimited concurrent socket count to a default cap of `1000`; values `<= 0` leave Node unlimited. Deno and Bun have no equivalent runtime setting and require a platform or reverse-proxy connection cap. diff --git a/README.md b/README.md index 454dfc6..3bf4398 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ npm install busboy # multipart/form-data file uploads - **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on. - **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere. - **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere. -- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser. +- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser. ## Real-time is a primitive, not a second framework @@ -111,7 +111,8 @@ Beta shipped the parts a real API needs, without growing the runtime dependency - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. - **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. -- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. `app.close()` is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. +- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. +- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. diff --git a/docs/plans/2026-08-17-shutdown-teardown-design.md b/docs/plans/2026-08-17-shutdown-teardown-design.md index 60f1264..dc1d19d 100644 --- a/docs/plans/2026-08-17-shutdown-teardown-design.md +++ b/docs/plans/2026-08-17-shutdown-teardown-design.md @@ -122,10 +122,12 @@ Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**: `timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for. - Drain runs first. Teardown runs after, within the same budget. -- `teardownTimeoutMs` is optional and defaults to `timeoutMs` — no separate cap, teardown may use whatever the drain left. -- Setting it lower **reserves**: the drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice. +- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one. +- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice. - `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped. +An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement. + Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run. --- diff --git a/docs/plans/2026-08-17-shutdown-teardown-plan.md b/docs/plans/2026-08-17-shutdown-teardown-plan.md index 183ef0b..07d63e8 100644 --- a/docs/plans/2026-08-17-shutdown-teardown-plan.md +++ b/docs/plans/2026-08-17-shutdown-teardown-plan.md @@ -72,7 +72,7 @@ Tests: `dispose()` is called; a provider without one is skipped; `cache` needing Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining. -The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` defaults to `timeoutMs`; when set lower it **reserves**, so the drain is bounded to `timeoutMs − teardownTimeoutMs` and teardown is guaranteed its slice. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently. +The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently. `closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering. diff --git a/src/app/index.ts b/src/app/index.ts index 281f8be..836bff1 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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; providerMeta: Map; + /** + * 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 void | Promise }>; 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 => - 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; container: Container; providerMeta: Map; + providerInstances: Map void | Promise }>; + teardown: TeardownRegistry; bus: Bus; logger: Logger; }, ): Promise { - 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; container: Container; providerMeta: Map; + providerInstances: Map void | Promise }>; + 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 { + if (teardown.size === 0) return Promise.resolve(); + + return new Promise((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 { - 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((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. */ diff --git a/src/app/types.ts b/src/app/types.ts index 52e857d..2322acc 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -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; +} diff --git a/src/bun.ts b/src/bun.ts index 0857809..50f66d0 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -119,7 +119,12 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu return Object.assign(server, { close: (closeOptions: { timeoutMs?: number } = {}): Promise => 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) => diff --git a/src/deno.ts b/src/deno.ts index 809acce..4deca38 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -78,7 +78,12 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { return Object.assign(server, { close: (closeOptions: { timeoutMs?: number } = {}): Promise => 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 diff --git a/src/edge.ts b/src/edge.ts index a064aa2..183a022 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -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, diff --git a/src/lifecycle.ts b/src/lifecycle.ts new file mode 100644 index 0000000..8987220 --- /dev/null +++ b/src/lifecycle.ts @@ -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; + +/** + * 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 { + 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 }); + } + } + } +} diff --git a/src/plugin.ts b/src/plugin.ts index 2a0eb6f..92dfa33 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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' }); } diff --git a/test/bun/shutdown.test.ts b/test/bun/shutdown.test.ts index f0fc33a..d6919d4 100644 --- a/test/bun/shutdown.test.ts +++ b/test/bun/shutdown.test.ts @@ -49,3 +49,23 @@ test('serveBun close() drains an in-flight request rather than cutting it', asyn expect(await inFlight).toEqual({ ok: true }); }); + +// D7 of the teardown design: proving the Node path works proves nothing here, because app.close() +// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses. +test('serveBun close() runs registered teardown', async () => { + const closed: string[] = []; + const app = createApp({ + modules: [M], + hooks: [{ onShutdown: () => void closed.push('hook') }], + plugins: [(api) => api.onShutdown(async () => { + await Bun.sleep(10); + closed.push('plugin'); + })], + }); + const server = serveBun(app, { port: 0 }); + + await server.close({ timeoutMs: 2000 }); + + // Reverse registration order: the plugin registered after the hook, so it tears down first. + expect(closed).toEqual(['plugin', 'hook']); +}); diff --git a/test/deno/shutdown.test.ts b/test/deno/shutdown.test.ts index 8cee2da..74c43bf 100644 --- a/test/deno/shutdown.test.ts +++ b/test/deno/shutdown.test.ts @@ -63,3 +63,24 @@ Deno.test('a caller-supplied signal still aborts the server', async () => { ac.abort(); await server.finished; // hangs here if chaining the caller's signal into ours dropped it }); + +// D7 of the teardown design: a teardown must run on every runtime that has a shutdown, and it must +// run from the close() the runtime actually uses. app.close() returns at its no-server guard here, +// so proving the Node path works proves nothing about this one — hence a Deno assertion of its own. +Deno.test('serveDeno close() runs registered teardown', async () => { + const closed: string[] = []; + const app = createApp({ + modules: [M], + hooks: [{ onShutdown: () => void closed.push('hook') }], + plugins: [(api) => api.onShutdown(async () => { + await new Promise((r) => setTimeout(r, 10)); + closed.push('plugin'); + })], + }); + const server = serveDeno(app, { port: 0 }); + + await server.close({ timeoutMs: 2000 }); + + // Reverse registration order: the plugin registered after the hook, so it tears down first. + if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`); +}); diff --git a/test/lifecycle.test.ts b/test/lifecycle.test.ts new file mode 100644 index 0000000..975e891 --- /dev/null +++ b/test/lifecycle.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, vi } from 'vitest'; +import { TeardownRegistry, type TeardownFn } from '../src/lifecycle'; +import type { Logger } from '../src/logger'; + +const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }); + +describe('TeardownRegistry', () => { + it('runs callbacks newest first, so a dependant tears down before its dependency', async () => { + const order: string[] = []; + const registry = new TeardownRegistry(); + // Providers register as they boot, and they boot in topological order — so `db` registering + // before `cache` is what a `cache` needing `db` actually looks like here. + registry.add(() => void order.push('db')); + registry.add(() => void order.push('cache')); + + await registry.run(silentLogger()); + + expect(order).toEqual(['cache', 'db']); + }); + + it('awaits each callback before starting the next', async () => { + const order: string[] = []; + const registry = new TeardownRegistry(); + registry.add(async () => { + await new Promise((resolve) => setTimeout(resolve, 20)); + order.push('slow'); + }); + registry.add(() => void order.push('fast')); + + await registry.run(silentLogger()); + + // 'fast' is registered last so it runs first; 'slow' must still have finished by return. + expect(order).toEqual(['fast', 'slow']); + }); + + it('logs a throwing callback and still runs the rest', async () => { + const logger = silentLogger(); + const order: string[] = []; + const registry = new TeardownRegistry(); + registry.add(() => void order.push('first')); + registry.add(() => { + throw new Error('boom'); + }); + registry.add(() => void order.push('third')); + + await expect(registry.run(logger)).resolves.toBeUndefined(); + expect(order).toEqual(['third', 'first']); + expect(logger.warn).toHaveBeenCalledOnce(); + expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/boom/); + }); + + it('treats a rejecting async callback the same as a throwing one', async () => { + const logger = silentLogger(); + const registry = new TeardownRegistry(); + registry.add(() => Promise.reject(new Error('async boom'))); + registry.add(() => Promise.resolve()); + + await expect(registry.run(logger)).resolves.toBeUndefined(); + expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/async boom/); + }); + + it('does not re-run callbacks on a second close()', async () => { + let runs = 0; + const registry = new TeardownRegistry(); + registry.add(() => void runs++); + + await registry.run(silentLogger()); + await registry.run(silentLogger()); + + expect(runs).toBe(1); + }); + + it('resolves when nothing is registered, and reports an empty size', async () => { + const registry = new TeardownRegistry(); + expect(registry.size).toBe(0); + await expect(registry.run(silentLogger())).resolves.toBeUndefined(); + }); + + it('reports how many callbacks are registered', () => { + const registry = new TeardownRegistry(); + const noop: TeardownFn = () => {}; + registry.add(noop); + registry.add(noop); + expect(registry.size).toBe(2); + }); +}); diff --git a/test/plugin.test.ts b/test/plugin.test.ts index c1f620b..edc8afa 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -1,6 +1,9 @@ import { expect, test, vi } from 'vitest'; import { Bus } from '../src/bus'; import { mountPlugin, Plugin, ScopeApi } from '../src/plugin'; +import type { TeardownFn } from '../src/lifecycle'; + +const noTeardown = (): ((fn: TeardownFn) => void) => () => {}; test('plugin can observe via bus.on and add to its own scope', () => { const bus = new Bus(); @@ -14,7 +17,7 @@ test('plugin can observe via bus.on and add to its own scope', () => { const mounted = vi.fn(); bus.on('plugin:mounted', mounted); - mountPlugin(logger, bus, scope); + mountPlugin(logger, bus, scope, noTeardown()); expect(added).toEqual(['log']); expect(mounted).toHaveBeenCalled(); @@ -26,5 +29,37 @@ test('plugin api does NOT expose bus.emit', () => { const plugin: Plugin = (api) => { expect((api.bus as any).emit).toBeUndefined(); }; - mountPlugin(plugin, bus, scope); + mountPlugin(plugin, bus, scope, noTeardown()); +}); + +test('plugin can register a teardown, and it reaches the registry', () => { + const bus = new Bus(); + const registered: TeardownFn[] = []; + const plugin: Plugin = (api) => { + api.onShutdown(() => {}); + }; + + mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn)); + + expect(registered).toHaveLength(1); +}); + +// D3's no-break guarantee, asserted rather than assumed: `Plugin`'s signature did not change, so a +// plugin written before this capability existed must mount and behave exactly as it did. +test('a plugin that never calls onShutdown behaves exactly as before', () => { + const bus = new Bus(); + const added: string[] = []; + const registered: TeardownFn[] = []; + const legacy: Plugin = (api) => { + api.bus.on('stream:open', () => {}); + api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) }); + }; + + const mounted = vi.fn(); + bus.on('plugin:mounted', mounted); + mountPlugin(legacy, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn)); + + expect(added).toEqual(['thing']); + expect(mounted).toHaveBeenCalled(); + expect(registered).toHaveLength(0); }); diff --git a/test/teardown.test.ts b/test/teardown.test.ts new file mode 100644 index 0000000..d99f907 --- /dev/null +++ b/test/teardown.test.ts @@ -0,0 +1,215 @@ +import 'reflect-metadata'; +import { describe, expect, it, vi } from 'vitest'; +import { Provider, Module, Route, Get } from '../src/metadata'; +import { createApp } from '../src/app'; +import type { Plugin } from '../src/plugin'; +import type { Logger } from '../src/logger'; + +const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }); + +@Route('/') +class Ctl { + @Get('/ping') ping() { + return { ok: true }; + } +} + +describe('shutdown teardown', () => { + it('awaits a plugin onShutdown before close() resolves', async () => { + const order: string[] = []; + const plugin: Plugin = (api) => { + api.onShutdown(async () => { + await new Promise((r) => setTimeout(r, 20)); + order.push('plugin torn down'); + }); + }; + + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() }); + await app.listen(0); + await app.close(); + order.push('close returned'); + + expect(order).toEqual(['plugin torn down', 'close returned']); + }); + + it('runs a hook onShutdown without the app declaring a plugin', async () => { + const seen: string[] = []; + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const app = createApp({ + modules: [M], + hooks: [{ onShutdown: () => void seen.push('hook') }], + logger: silentLogger(), + }); + await app.listen(0); + await app.close(); + + expect(seen).toEqual(['hook']); + }); + + it('calls a provider dispose(), and skips a provider without one', async () => { + const closed: string[] = []; + + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: {} }; + } + async dispose() { + closed.push('db'); + } + } + @Provider({ provides: 'plain' }) + class Plain { + provide() { + return { plain: {} }; + } + } + + @Module({ mountpoint: '/', providers: [Db, Plain], controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + await app.listen(0); + await app.close(); + + expect(closed).toEqual(['db']); + }); + + // D5, and the reason dispose() is registered as a provider boots rather than as it is collected. + it('tears a dependant down before the dependency it needs', async () => { + const closed: string[] = []; + + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: {} }; + } + dispose() { + closed.push('db'); + } + } + @Provider({ provides: 'cache', needs: ['db'] }) + class Cache { + provide() { + return { cache: {} }; + } + dispose() { + closed.push('cache'); + } + } + + // Declared dependency-last on purpose: the order must come from the graph, not the array. + @Module({ mountpoint: '/', providers: [Cache, Db], controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + await app.listen(0); + await app.close(); + + expect(closed).toEqual(['cache', 'db']); + }); + + it('does not dispose a provider that failed to boot', async () => { + const closed: string[] = []; + + @Provider({ provides: 'broken', optional: true }) + class Broken { + provide(): unknown { + throw new Error('cannot connect'); + } + dispose() { + closed.push('broken'); + } + } + + @Module({ mountpoint: '/', providers: [Broken], controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + await app.listen(0); + await app.close(); + + expect(closed).toEqual([]); + }); + + it('logs a failing teardown, runs the rest, and still resolves', async () => { + const logger = silentLogger(); + const closed: string[] = []; + const plugin: Plugin = (api) => { + api.onShutdown(() => { + throw new Error('teardown boom'); + }); + api.onShutdown(() => void closed.push('survivor')); + }; + + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], plugins: [plugin], logger }); + await app.listen(0); + await expect(app.close()).resolves.toBeUndefined(); + + expect(closed).toEqual(['survivor']); + expect(vi.mocked(logger.warn).mock.calls.some((c) => /teardown boom/.test(c[0]))).toBe(true); + }); + + it('does not let a hanging teardown push close() past its deadline', async () => { + const plugin: Plugin = (api) => { + api.onShutdown(() => new Promise(() => {})); // never settles + }; + + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() }); + await app.listen(0); + + const startedAt = Date.now(); + await app.close({ timeoutMs: 300 }); + expect(Date.now() - startedAt).toBeLessThan(1500); + }); + + it('rejects a reservation larger than the budget it comes out of', () => { + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + expect(() => createApp({ modules: [M], shutdownTimeoutMs: 1000, teardownTimeoutMs: 2000 })).toThrow( + /cannot exceed shutdownTimeoutMs/, + ); + }); + + it('tears down an app that was never listen()ed, since its providers still booted', async () => { + const closed: string[] = []; + + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: {} }; + } + dispose() { + closed.push('db'); + } + } + + @Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + await app.fetch(new Request('http://x/ping')); // boots providers, no server + await app.close(); + + expect(closed).toEqual(['db']); + }); + + it('drains only once when close() is called twice', async () => { + let runs = 0; + const plugin: Plugin = (api) => { + api.onShutdown(() => void runs++); + }; + + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() }); + await app.listen(0); + await app.close(); + await app.close(); + + expect(runs).toBe(1); + }); +});