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

+20
View File
@@ -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']);
});
+21
View File
@@ -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(',')}`);
});
+86
View File
@@ -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);
});
});
+37 -2
View File
@@ -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);
});
+215
View File
@@ -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<void>(() => {})); // 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);
});
});