fix(lifecycle): make a concurrent close() wait for the teardown in flight
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s

TeardownRegistry.run set a `drained` flag and returned at once to any
later caller. That kept teardown from running twice, but a second
close() made while the first was still awaiting its callbacks resolved
straight away. A signal handler and a test hook closing together could
then move on with a database the first call had not closed yet. This
reached every close path: app.close() with or without a listen()ed
server, and serveDeno/serveBun, which hand over to app.close().

The registry now keeps the promise of the teardown it started and
returns it to every caller, so the callbacks still run once and each
caller resolves only after they finish, within its own runTeardown
budget. The drain window and closeApp needed no change: the health
drain already shares one window, and a second server.close() waits for
the same 'close' event. close() after a failed listen() still has no
server and only runs teardown.

GitHub #45.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-24 15:53:36 -05:00
1 parent 1e2d55f158
commit e6f6f90cc2
4 files changed
+57 -5

No files matched your search

+17
View File
@@ -70,6 +70,23 @@ describe('TeardownRegistry', () => {
expect(runs).toBe(1);
});
it('makes a concurrent second close() wait for the teardown the first one started (GitHub #45)', async () => {
const order: string[] = [];
const registry = new TeardownRegistry();
registry.add(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
order.push('torn down');
});
const logger = silentLogger();
await Promise.all([
registry.run(logger).then(() => order.push('first returned')),
registry.run(logger).then(() => order.push('second returned')),
]);
expect(order).toEqual(['torn down', 'first returned', 'second returned']);
});
it('resolves when nothing is registered, and reports an empty size', async () => {
const registry = new TeardownRegistry();
expect(registry.size).toBe(0);