From 085eb9a67d02737f93c7616487cfd115832477b4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 16 Aug 2026 13:03:09 -0500 Subject: [PATCH] fix(app): arm the shutdown timer before finish(), and make the deadline an app option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #20. finish() called clearTimeout(timer) from above the timer's own declaration. It worked because server.close(cb) always defers, so the assignment won the race — correct by timing, and a ReferenceError waiting in the shutdown path for whoever added a synchronous call site. The issue proposed hoisting a `let timer`, but prefer-const rejects that and is right to. Swapping the two blocks fixes it without a suppression and lands somewhere better: the surviving forward reference is the timer callback reaching finish(), and setTimeout not firing synchronously is the event loop rather than a library's current behaviour. Closes #19. The 10s deadline is now settable via createApp({ shutdownTimeoutMs }), with the per-call close({ timeoutMs }) still winning. close() is usually reached from a signal handler, a test helper or a shutdown hook you do not own, where passing it per call is not available. Nothing changes for anyone passing neither. The precedence test uses a 30s app-level default, so it can only pass if the per-call value took priority. Signed-off-by: Diego Resendez --- src/app/index.ts | 50 ++++++++++++++++++++++++++++++++---------------- test/app.test.ts | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 17 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 8bbdd2a..df45a09 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -103,6 +103,13 @@ export function createApp(opts: { viewEngine?: (source: string, data: unknown) => string; /** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */ static?: boolean | string; + /** + * How long `close()` gives in-flight work before forcing remaining connections shut, in ms + * (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is + * reached from a signal handler, a test helper or a shutdown hook you do not own, which is + * where passing it per call is not an option. + */ + shutdownTimeoutMs?: number; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; /** @@ -260,7 +267,8 @@ export function createApp(opts: { return server; }; - const close = (options: { timeoutMs?: number } = {}): Promise => closeApp(server, meshLinks, streams, options); + const close = (options: { timeoutMs?: number } = {}): Promise => + closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs); return { listen, @@ -950,6 +958,7 @@ function closeApp( meshLinks: Link[], streams: Set<() => void>, options: { timeoutMs?: number }, + defaultTimeoutMs: number | undefined, ): Promise { return new Promise((resolve) => { // A mesh app booted through `app.fetch` has links but no server, and would leak every @@ -967,9 +976,31 @@ function closeApp( return resolve(); } - const timeoutMs = options.timeoutMs ?? 10_000; + const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000; let settled = false; + // The timer is armed before `finish` exists, rather than the other way round, and the ordering + // is the point. Whichever one comes second is referenced by the other before its declaration + // runs, so what matters is which forward reference rests on a guarantee. setTimeout cannot + // invoke its callback synchronously — that is the event loop, not an implementation detail — + // so `finish` is always assigned by the time the callback can reach it. The reverse ordering + // relied on `server.close(cb)` deferring, which is Node's behaviour rather than a promise to + // us, and left a `ReferenceError` waiting in the shutdown path for whoever changed it. + const timer = setTimeout(() => { + if (settled) return; + + console.warn( + `[green-tea] graceful shutdown timed out after ${timeoutMs}ms — ` + 'forcing remaining HTTP connections closed', + ); + + // closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections() + // below — `engines` in package.json only guarantees >=18, so this matters. + server.closeAllConnections(); + finish(); + }, timeoutMs); + + timer.unref?.(); + const finish = () => { if (settled) return; settled = true; @@ -981,21 +1012,6 @@ function closeApp( for (const closeStream of streams) closeStream(); server.closeIdleConnections(); - - const timer = setTimeout(() => { - if (settled) return; - - console.warn( - `[green-tea] graceful shutdown timed out after ${timeoutMs}ms — ` + 'forcing remaining HTTP connections closed', - ); - - // closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections() - // above — `engines` in package.json only guarantees >=18, so this matters. - server.closeAllConnections(); - finish(); - }, timeoutMs); - - timer.unref?.(); }); } diff --git a/test/app.test.ts b/test/app.test.ts index 02ff257..6e0400f 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -439,6 +439,28 @@ describe('devGraph endpoint', () => { }); describe('graceful shutdown', () => { + // A module whose only route never responds, so shutdown always has something in flight to give + // up on — the deadline is the only thing that can end close(). + const hangModule = () => { + @Route('/') + class Ctl { + @Get('/hang') hang() { + return new Promise(() => {}); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + return M; + }; + + const listenHanging = async (app: ReturnType): Promise => { + const server = await app.listen(0); + const port = (server.address() as any).port; + fetch(`http://127.0.0.1:${port}/hang`).catch(() => {}); + await new Promise((r) => setTimeout(r, 50)); // let the request reach the handler + return port; + }; + it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { @Route('/') class Ctl { @@ -485,6 +507,28 @@ describe('graceful shutdown', () => { await app.close({ timeoutMs: 300 }); expect(Date.now() - start).toBeLessThan(600); }); + + // The app-level default exists for the case where close() is reached from a signal handler or a + // test helper nobody local owns, so it has to work with close() called bare. + it('createApp({ shutdownTimeoutMs }) applies when close() is called with no options', async () => { + const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 300 }); + await listenHanging(app); + + const start = Date.now(); + await app.close(); + expect(Date.now() - start).toBeLessThan(600); + }); + + // The interesting half of the precedence rule: an app-level default long enough to fail this + // test if it won, so the assertion can only pass if the per-call value took priority. + it('close({ timeoutMs }) overrides the app-level default', async () => { + const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 30_000 }); + await listenHanging(app); + + const start = Date.now(); + await app.close({ timeoutMs: 300 }); + expect(Date.now() - start).toBeLessThan(600); + }); }); describe('overrides', () => {