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

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 18:18:23 -05:00
1 parent d90e7ca2b0
commit 212d2fa5c4
4 files changed
+57 -5

No files matched your search

+9 -5
View File
@@ -25,7 +25,7 @@ export type TeardownFn = () => void | Promise<void>;
*/
export class TeardownRegistry {
private readonly callbacks: TeardownFn[] = [];
private drained = false;
private running: Promise<void> | undefined;
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
add(fn: TeardownFn): void {
@@ -53,12 +53,16 @@ export class TeardownRegistry {
* 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.
* anyone expects, and a second call must not re-close what the first one closed. A second call
* made while the first is still running gets the same promise rather than an early return: a
* caller that awaits `close()` must not move on with a connection the first call has yet to close.
*/
async run(logger: Logger): Promise<void> {
if (this.drained) return;
this.drained = true;
run(logger: Logger): Promise<void> {
this.running ??= this.drain(logger);
return this.running;
}
private async drain(logger: Logger): Promise<void> {
for (let index = this.callbacks.length - 1; index >= 0; index--) {
try {
await this.callbacks[index]();