feat(runtimes): a bounded close() on the Deno and Bun adapters
Closes #15, taking the second of the two answers it framed: app.close() stays Node-only, and each transport that owns a handle offers the same close({ timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun because they serve through app.fetch and never through listen(), and only the transport can drain what it accepted. The warning there now names the replacement instead of pointing at this issue. The runtimes do not agree, and the code says so rather than averaging them: Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves between them like Node's closeAllConnections(). Deno cannot. Its two levers are mutually exclusive — aborting the serve signal while shutdown() is pending throws BadResource from Deno's own listener, uncaught and fatal under deno test. Measured on 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long close() waits, not when connections die, and both the type and the timeout warning say that outright. Silently accepting an option that does less is the failure mode AGENTS.md rules out. closeWithDeadline is shared so the two cannot drift into different meanings of the same timeoutMs, and it resolves on its own timer rather than awaiting the force call — Bun's stop(true) was measured waiting out a handler with a pending timer, which is exactly the unbounded wait the deadline exists to prevent. serveDeno now owns the AbortController it serves with, chaining any caller signal into it so neither party loses control; a test covers that. The Bun ambient said stop() returns void, which was simply wrong. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+256
-7
No files matched your search
+7
-2
@@ -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.',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+32
-3
@@ -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<void>;
|
||||
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): 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<void>;
|
||||
}
|
||||
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<void> =>
|
||||
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`),
|
||||
),
|
||||
});
|
||||
}
|
||||
+51
-2
@@ -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<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<void>;
|
||||
}
|
||||
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
|
||||
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<void> =>
|
||||
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.',
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -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<void>,
|
||||
force: () => void,
|
||||
timeoutMs: number,
|
||||
onTimeout?: (timeoutMs: number) => void,
|
||||
): Promise<void> {
|
||||
return new Promise<void>((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);
|
||||
});
|
||||
}
|
||||
@@ -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 });
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
Reference in new issue
Block a user