Files
core/test/lifecycle.test.ts
chrnx 24feca481c 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>
2026-08-17 11:37:31 -05:00

87 lines
3.1 KiB
TypeScript

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