diff --git a/src/app/index.ts b/src/app/index.ts index df45a09..65ff8db 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -965,11 +965,16 @@ function closeApp( // teapot connection otherwise — so links close before we even check for a server. closeLinks(meshLinks); + // No server means the app is served through `app.fetch` rather than `listen()`, which is how + // Deno, Bun and the edge all run. Draining is the transport's job and only the transport holds + // the handle, so `close()` is deliberately Node-only here rather than pretending otherwise; + // `serveDeno`/`serveBun` return a server with the same bounded `close({ timeoutMs })`. if (!server) { if (options.timeoutMs !== undefined) { console.warn( - '[green-tea] close({ timeoutMs }) has no effect here — this app has no ' + - 'listen()ed server (Bun/Deno run through app.fetch). See #15.', + '[green-tea] close({ timeoutMs }) has no effect here — this app has no listen()ed ' + + 'server. On Deno and Bun, call close() on the server serveDeno()/serveBun() returned; ' + + 'it takes the same option. On the edge the platform owns the lifecycle.', ); } diff --git a/src/bun.ts b/src/bun.ts index cdb34c3..1824a5f 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -3,6 +3,7 @@ import type { Channel } from './channel'; import type { App } from './app/types'; import type { WsSocket, WsRequest } from './http/ws-core'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; +import { closeWithDeadline } from './http/shutdown'; // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. @@ -21,10 +22,25 @@ interface BunWebSocketHandler { } interface BunServer { port: number; - stop(closeActiveConnections?: boolean): void; + // Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it + // hid the fact that this is awaitable at all. + stop(closeActiveConnections?: boolean): Promise; upgrade(request: Request, options?: { data?: unknown; headers?: Record }): boolean; requestIP(request: Request): { address: string; family: string; port: number } | null; } + +/** + * What {@link serveBun} hands back: Bun's own server, plus the bounded `close()` that + * `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Bun, + * because a Bun app is served through `app.fetch` and never through `listen()`. + */ +export interface BunServeResult extends BunServer { + /** + * Drains in-flight requests, then force-closes whatever is left after `timeoutMs` (default: + * 10s). Same meaning as `app.close({ timeoutMs })` on Node. + */ + close(options?: { timeoutMs?: number }): Promise; +} interface BunServeOptions { port?: number; hostname?: string; @@ -59,8 +75,8 @@ function bunSocket(ws: BunServerWebSocket): WsSocket { * Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at * the deployment platform or reverse proxy. */ -export function serveBun(app: App, options?: BunServeShortOptions): BunServer { - return Bun.serve({ +export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult { + const server = Bun.serve({ ...options, fetch(request, server) { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { @@ -97,4 +113,17 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { }, }, }); + + // Object.assign rather than a fresh object: Bun.serve returns more than the ambient above + // declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name. + return Object.assign(server, { + close: (closeOptions: { timeoutMs?: number } = {}): Promise => + closeWithDeadline( + () => server.stop(false), + () => void server.stop(true), + closeOptions.timeoutMs ?? 10_000, + (ms) => + console.warn(`[green-tea] graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`), + ), + }); } diff --git a/src/deno.ts b/src/deno.ts index 12a3809..cd9574a 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,5 +1,6 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; +import { closeWithDeadline } from './http/shutdown'; // The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) // doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. @@ -22,6 +23,23 @@ interface DenoHttpServer { finished: Promise; shutdown(): Promise; } + +/** + * What {@link serveDeno} hands back: Deno's own server, plus the bounded `close()` that + * `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Deno, + * because a Deno app is served through `app.fetch` and never through `listen()`. + */ +export interface DenoServer extends DenoHttpServer { + /** + * Drains in-flight requests, returning after at most `timeoutMs` (default: 10s). + * + * **The deadline bounds the wait, not the connections** — unlike Node's `app.close()` and Bun's + * `close()`, which force the remainder shut. Deno offers no force-close that composes with a + * drain already under way: aborting the serve signal at that point throws `BadResource` from + * Deno's own listener, uncaught. Whatever is still open when this resolves ends with the process. + */ + close(options?: { timeoutMs?: number }): Promise; +} type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise; declare const Deno: { serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer; @@ -34,8 +52,14 @@ declare const Deno: { * Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at * the deployment platform or reverse proxy. */ -export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { - return Deno.serve(options ?? {}, (request, info) => { +export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { + // Deno's only force-close lever is the abort signal it was served with, so the adapter has to + // own one to offer a deadline at all. A caller-supplied signal still works and still aborts the + // server — it is chained into ours rather than replaced, so neither party loses its control. + const ac = new AbortController(); + options?.signal?.addEventListener('abort', () => ac.abort(), { once: true }); + + const server = Deno.serve({ ...options, signal: ac.signal }, (request, info) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { // Deno invalidates request connection metadata as soon as the upgrade is accepted. const wsRequest = toWsRequest(request, info.remoteAddr.hostname); @@ -48,4 +72,29 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer return app.fetch(request); }); + + // Object.assign rather than a fresh object: Deno.serve returns more than the ambient above + // declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name. + return Object.assign(server, { + close: (closeOptions: { timeoutMs?: number } = {}): Promise => + closeWithDeadline( + () => server.shutdown(), + // Nothing to force, and that is Deno's constraint rather than an omission here. Its two + // levers are mutually exclusive: aborting the serve signal after `shutdown()` is already + // pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which + // surfaces uncaught — not catchable at this call site, and fatal under `deno test`. + // Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot + // escalate from graceful to forced the way Node's closeAllConnections() and Bun's + // stop(true) can, and the deadline here bounds how long `close()` waits, not when the + // connections die. Exiting the process after `close()` resolves is what ends them. + () => {}, + closeOptions.timeoutMs ?? 10_000, + (ms) => + console.warn( + `[green-tea] graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot ` + + 'force-close a server that is already draining, so remaining connections end when the ' + + 'process does.', + ), + ), + }); } diff --git a/src/http/shutdown.ts b/src/http/shutdown.ts new file mode 100644 index 0000000..3bb4af2 --- /dev/null +++ b/src/http/shutdown.ts @@ -0,0 +1,50 @@ +/** + * Bounds a graceful shutdown by a deadline, forcing whatever is left. + * + * Shared by the Deno and Bun adapters so the two cannot drift into different meanings of the same + * `timeoutMs`, and shaped like the Node path in `closeApp`: try to drain, and if the deadline + * passes first, force the remainder and resolve anyway. + * + * The race is the point, and it is not paranoia. Both runtimes' force calls were measured against + * a handler that never resolves and returned immediately, but `Bun.stop(true)` was also measured + * waiting out a handler with a pending timer — same call, ~2s, because it awaits pending async + * work rather than only open connections. Awaiting the force call would therefore inherit exactly + * the unbounded wait the deadline exists to prevent. Resolving on our own timer means `close()` + * returns within `timeoutMs` whatever either runtime decides to wait for. + * + * @param graceful Drain in flight work. Unbounded — that is what the deadline is for. + * @param force Stop waiting and drop what is left. Fire-and-forget; its promise is not awaited. + */ +export function closeWithDeadline( + graceful: () => Promise, + force: () => void, + timeoutMs: number, + onTimeout?: (timeoutMs: number) => void, +): Promise { + return new Promise((resolve) => { + let settled = false; + + // Armed before `finish` exists, and deliberately: setTimeout cannot invoke its callback + // synchronously, so `finish` is always assigned by the time this can reach it. The reverse + // ordering would rest on when the runtime's own promise settles. Mirrors `closeApp`. + const timer = setTimeout(() => { + if (settled) return; + onTimeout?.(timeoutMs); + force(); + finish(); + }, timeoutMs); + + timer.unref?.(); + + const finish = (): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(); + }; + + // A graceful path that rejects still has to end the shutdown: the deadline covers a slow + // close, not a broken one, and leaving close() pending forever is the worse failure. + void graceful().then(finish, finish); + }); +} diff --git a/test/bun/shutdown.test.ts b/test/bun/shutdown.test.ts new file mode 100644 index 0000000..f0fc33a --- /dev/null +++ b/test/bun/shutdown.test.ts @@ -0,0 +1,51 @@ +// Real Bun integration test for the bounded close() serveBun returns. app.close() cannot do this +// job on Bun — it returns at its `if (!server)` guard, because a Bun app is served through +// app.fetch and never through listen() — so the deadline lives on the transport that owns the +// handle. See issue #15. +// +// Run with: npm run test:bun (or: bun test test/bun/) +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Route, Get, Module } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Route('/') +class Ctl { + @Get('/hang') + hang() { + return new Promise(() => {}); // never resolves — a stuck handler + } + @Get('/slow') + async slow() { + await Bun.sleep(200); // finite, so draining has something real to wait out + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => { + const server = serveBun(createApp({ modules: [M] }), { port: 0 }); + + fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {}); + await Bun.sleep(50); // let the request actually reach the handler + + const start = Date.now(); + await server.close({ timeoutMs: 300 }); + const elapsed = Date.now() - start; + + // The assertion that matters is the upper bound: without the deadline this never returns. + expect(elapsed).toBeLessThan(2000); + expect(elapsed).toBeGreaterThanOrEqual(250); +}); + +test('serveBun close() drains an in-flight request rather than cutting it', async () => { + const server = serveBun(createApp({ modules: [M] }), { port: 0 }); + + const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json()); + await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in + + await server.close({ timeoutMs: 5000 }); + + expect(await inFlight).toEqual({ ok: true }); +}); diff --git a/test/deno/shutdown.test.ts b/test/deno/shutdown.test.ts new file mode 100644 index 0000000..8cee2da --- /dev/null +++ b/test/deno/shutdown.test.ts @@ -0,0 +1,65 @@ +// Real Deno integration test for the bounded close() serveDeno returns. app.close() cannot do this +// job on Deno — it returns at its `if (!server)` guard, because a Deno app is served through +// app.fetch and never through listen() — so the deadline lives on the transport that owns the +// handle. See issue #15. +// +// Run with: npm run test:deno +import 'reflect-metadata'; +import { createApp, Route, Get, Module } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Route('/') +class Ctl { + @Get('/hang') + hang() { + return new Promise(() => {}); // never resolves — a stuck handler + } + @Get('/slow') + async slow() { + await new Promise((r) => setTimeout(r, 200)); // finite, so draining has something real to wait out + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +const portOf = (server: { addr?: { port: number } }): number => server.addr!.port; + +// On Deno the deadline bounds the wait, not the connections — see the comment on serveDeno's +// force callback. This test asserts exactly that: close() returns on time, and does so without +// the uncaught BadResource that aborting a draining server produces. The test runner fails on +// that error even when the assertions pass, so a green run here is the real assertion. +Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => { + const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); + + fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {}); + await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler + + const start = Date.now(); + await server.close({ timeoutMs: 300 }); + const elapsed = Date.now() - start; + + // The assertion that matters is the upper bound: without the deadline this never returns. + if (elapsed >= 2000) throw new Error(`close() took ${elapsed}ms — the deadline did not fire`); + if (elapsed < 250) throw new Error(`close() returned in ${elapsed}ms — it did not wait the deadline`); +}); + +Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => { + const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); + + const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json()); + await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close + + await server.close({ timeoutMs: 5000 }); + + const body = await inFlight; + if (body.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(body)}`); +}); + +Deno.test('a caller-supplied signal still aborts the server', async () => { + const ac = new AbortController(); + const server = serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} }); + + ac.abort(); + await server.finished; // hangs here if chaining the caller's signal into ours dropped it +});