CI picked up Bun 1.4.4 (`oven-sh/setup-bun@v2`, latest), which now sends a real `1009` close frame when `maxPayloadLength` refuses a frame. Bun 1.3 dropped the connection instead, so the peer saw `1006` — the difference D1 documented and these two assertions pinned on purpose so a Bun upgrade would be noticed. It was: `runtimes (bun)` fails on develop. The assertion now follows `Bun.version` (1006 before 1.4, 1009 from 1.4), so a further change in either direction still fails. JSDoc, README and the #107 CHANGELOG entry say which Bun versions do what. Verified with Bun 1.3.14 and 1.4.4 (26/26 each); lint, format, typecheck, npm test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
164 lines
7.3 KiB
TypeScript
164 lines
7.3 KiB
TypeScript
import { channel } from './channel';
|
|
import type { Channel } from './channel';
|
|
import type { App } from './app/types';
|
|
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
|
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
|
import { closeWithDeadline } from './http/shutdown';
|
|
import { setPeer } from './http/peer';
|
|
|
|
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
|
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
|
interface BunServerWebSocket {
|
|
data: unknown;
|
|
readyState: number;
|
|
send(data: string): number;
|
|
close(code?: number, reason?: string): void;
|
|
terminate?(): void;
|
|
}
|
|
interface BunWebSocketHandler {
|
|
maxPayloadLength?: number;
|
|
open?(ws: BunServerWebSocket): void;
|
|
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
|
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
|
error?(ws: BunServerWebSocket, error?: unknown): void;
|
|
}
|
|
interface BunServer {
|
|
port: number;
|
|
// 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;
|
|
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
|
|
websocket?: BunWebSocketHandler;
|
|
}
|
|
type BunServeShortOptions = { port?: number; hostname?: string };
|
|
declare const Bun: { serve(options: BunServeOptions): BunServer };
|
|
|
|
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
|
|
interface BunConnData {
|
|
wsReq: WsRequest;
|
|
inbound: Channel<unknown>;
|
|
ac: AbortController;
|
|
}
|
|
|
|
/**
|
|
* Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket
|
|
* events to a server-level handler rather than the socket, so the channel and abort are
|
|
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
|
*/
|
|
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
|
const { inbound, ac } = ws.data as BunConnData;
|
|
|
|
return neutralSocket(ws, inbound, ac);
|
|
}
|
|
|
|
/**
|
|
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
|
|
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
|
|
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
|
* Bun.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 serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
|
|
// 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.
|
|
await app.boot();
|
|
|
|
const server = Bun.serve({
|
|
...options,
|
|
fetch(request, server) {
|
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
const inbound = channel();
|
|
const ac = new AbortController();
|
|
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
|
const data: BunConnData = { wsReq, inbound, ac };
|
|
if (server.upgrade(request, { data })) return undefined;
|
|
return new Response('WebSocket upgrade failed', { status: 400 });
|
|
}
|
|
|
|
// The same object goes to `app.fetch`, which is what lets it find the peer again.
|
|
setPeer(request, server.requestIP(request)?.address ?? '');
|
|
return app.fetch(request);
|
|
},
|
|
websocket: {
|
|
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
|
|
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
|
|
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
|
|
// `app.upgrade` checks the same bound again on the decoded text.
|
|
maxPayloadLength:
|
|
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
|
open(ws) {
|
|
const { wsReq } = ws.data as BunConnData;
|
|
|
|
void upgradeSafely(app, wsReq, bunSocket(ws));
|
|
},
|
|
message(ws, message) {
|
|
const { inbound } = ws.data as BunConnData;
|
|
|
|
inbound.push(decodeMessage(message));
|
|
},
|
|
close(ws) {
|
|
const { inbound, ac } = ws.data as BunConnData;
|
|
inbound.close();
|
|
ac.abort();
|
|
},
|
|
error(ws) {
|
|
const { inbound, ac } = ws.data as BunConnData;
|
|
inbound.fail(new Error('websocket error'));
|
|
ac.abort();
|
|
},
|
|
},
|
|
});
|
|
|
|
// 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, {
|
|
// 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<void> =>
|
|
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 Bun, 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.
|
|
() => server.stop(false).then(() => app.close()),
|
|
() => void server.stop(true),
|
|
closeOptions.timeoutMs ?? 10_000,
|
|
(ms) =>
|
|
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
|
|
timeoutMs: ms,
|
|
runtime: 'bun',
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
}
|