import type { App } from './app/types'; import { refuseTls } from './security'; import { beginDrain } from './http/health'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; import { setPeer } from './http/peer'; // The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of // Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare. interface WebSocket extends EventfulSocket { binaryType: string; } // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. /** Options for {@link serveDeno}; passed through to `Deno.serve`. */ export interface DenoServeOptions { port?: number; hostname?: string; signal?: AbortSignal; onListen?: (addr: { hostname: string; port: number }) => void; } interface DenoServeHandlerInfo { remoteAddr: { hostname: string; port: number; transport: string }; } /** The part of the server `Deno.serve` returns that {@link DenoServer} builds on. */ export 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; upgradeWebSocket(request: Request): { socket: WebSocket; response: Response }; }; /** * Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. * WebSocket messages flow through app.upgrade over the shared neutral core. * Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at * the deployment platform or reverse proxy. * * **Boots before it binds**, which is why it is async — see the `await app.boot()` below. */ export async function serveDeno(app: App, options?: DenoServeOptions): Promise { // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the // graph and run the provider factories here, so a missing key or an unreachable pool is a startup // failure rather than a 500 on every request. // // Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so // the first request would fix the failure in place and the runtime would answer from it forever, // without ever reaching `onError`. This was documented as something the caller should remember to // do, which made the correct use of a core helper depend on reading a README. refuseTls(app, 'serveDeno'); await app.boot(); // 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); const { socket, response } = Deno.upgradeWebSocket(request); socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects // fire-and-forget: the 101 response must be returned synchronously while the graph runs void upgradeSafely(app, wsRequest, eventSocket(socket)); return response; } // The same object goes to `app.fetch`, which is what lets it find the peer again. A unix socket // has no `hostname`, and records nothing. setPeer(request, info.remoteAddr.hostname); 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, { // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this // runtime's own signal API — and so the close it returns takes the handlers back off, which // Deno requires to exit at all. close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise => closeWithDeadline( // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // `app.close()` returns at its no-server guard on Deno, but still drains the teardown // registry, which is what makes one `close()` enough here instead of two. Called without // options on purpose: passing a timeout it cannot use to drain would only earn its warning, // and the deadline below already bounds the whole call. // The drain window first: `/__ready__` answers 503 while the listener is still open (D14). () => beginDrain(app) .then(() => server.shutdown()) .then(() => app.close()), // 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) => app.logger.warn( `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.', { timeoutMs: ms, runtime: 'deno' }, ), ), ), }); }