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>
75 lines
3.3 KiB
TypeScript
75 lines
3.3 KiB
TypeScript
// 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<void>;
|
|
|
|
/**
|
|
* 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 running: Promise<void> | undefined;
|
|
|
|
/** 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. 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.
|
|
*/
|
|
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]();
|
|
} catch (error) {
|
|
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
|
|
}
|
|
}
|
|
}
|
|
}
|