diff --git a/src/bun.ts b/src/bun.ts index 9169db7..4656034 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -2,6 +2,7 @@ import { channel } from './channel'; 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'; // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. @@ -33,8 +34,6 @@ interface BunServeOptions { type BunServeShortOptions = { port?: number; hostname?: string }; declare const Bun: { serve(options: BunServeOptions): BunServer }; -const decoder = new TextDecoder(); - /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ interface BunConnData { wsReq: WsRequest; @@ -42,48 +41,15 @@ interface BunConnData { ac: AbortController; } -/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */ -function toWsRequest(request: Request, server: BunServer): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: server.requestIP(request)?.address ?? '', - }; -} - -/** Wraps a Bun ServerWebSocket (+ its stashed channel/abort) as a neutral WsSocket. */ +/** + * 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 { - inbound, - abort: ac.signal, - get isOpen() { - return ws.readyState === 1; // 1 = OPEN - }, - send: (data) => { - ws.send(data); - }, - close: (code, reason) => { - try { - ws.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - (ws.terminate ?? ws.close).call(ws); - } catch { - /* already closed */ - } - }, - }; + + return neutralSocket(ws, inbound, ac); } /** @@ -98,7 +64,8 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const inbound = channel(); const ac = new AbortController(); - const data: BunConnData = { wsReq: toWsRequest(request, server), inbound, ac }; + 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 }); } @@ -108,21 +75,13 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { websocket: { open(ws) { const { wsReq } = ws.data as BunConnData; - // fire-and-forget: app.upgrade can reject before runWsConnection's try/catch - // (mesh-before-listen, provider boot failure); guard it or an uncaught rejection - // could crash the Bun process. - void app.upgrade(wsReq, bunSocket(ws)).catch(() => { - try { - ws.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + + void upgradeSafely(app, wsReq, bunSocket(ws)); }, message(ws, message) { const { inbound } = ws.data as BunConnData; - // decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity) - inbound.push(typeof message === 'string' ? message : decoder.decode(message)); + + inbound.push(decodeMessage(message)); }, close(ws) { const { inbound, ac } = ws.data as BunConnData; diff --git a/src/deno.ts b/src/deno.ts index eafe6dc..f73e80a 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,23 +1,11 @@ -import { channel } from './channel'; import type { App } from './app/types'; -import type { WsSocket, WsRequest } from './http/ws-core'; +import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; // 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 -// (both the instance interface and the `OPEN` static, mirroring the real WebSocket). -interface WebSocketEventMap { - message: { data: string | ArrayBuffer }; - close: object; - error: object; -} -interface WebSocket { - readonly readyState: number; +// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. +interface WebSocket extends EventfulSocket { binaryType: string; - send(data: string): void; - close(code?: number, reason?: string): void; - addEventListener(type: K, listener: (event: WebSocketEventMap[K]) => void): void; } -declare const WebSocket: { readonly OPEN: number }; // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. @@ -40,63 +28,6 @@ declare const Deno: { upgradeWebSocket(request: Request): { socket: WebSocket; response: Response }; }; -/** Builds a neutral WsRequest from a Deno upgrade Request + connection info. */ -function toWsRequest(request: Request, info: DenoServeHandlerInfo): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: info.remoteAddr.hostname, - }; -} - -/** Wraps a Deno/web WebSocket as a neutral WsSocket. */ -function denoSocket(ws: WebSocket): WsSocket { - const inbound = channel(); - const ac = new AbortController(); - ws.binaryType = 'arraybuffer'; - const decoder = new TextDecoder(); - ws.addEventListener('message', (e) => { - const data = e.data; - inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer)); - }); - ws.addEventListener('close', () => { - inbound.close(); - ac.abort(); - }); - ws.addEventListener('error', () => { - inbound.fail(new Error('websocket error')); - ac.abort(); - }); - return { - inbound, - abort: ac.signal, - get isOpen() { - return ws.readyState === WebSocket.OPEN; - }, - send: (data) => ws.send(data), - close: (code, reason) => { - try { - ws.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - ws.close(); - } catch { - /* already closed */ - } - }, - }; -} - /** * 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. @@ -105,17 +36,9 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer return Deno.serve(options ?? {}, (request, info) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(request); - // Fire-and-forget: the upgrade response must be returned synchronously while - // the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch - // (mesh-before-listen throw, or a provider boot failure), so guard the call here — - // an uncaught rejection would be fatal on Deno and crash the whole server. - void app.upgrade(toWsRequest(request, info), denoSocket(socket)).catch(() => { - try { - socket.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + 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, toWsRequest(request, info.remoteAddr.hostname), eventSocket(socket)); return response; } diff --git a/src/edge.ts b/src/edge.ts index ec4780c..a064aa2 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -1,83 +1,16 @@ -import { channel } from './channel'; import type { App } from './app/types'; -import type { WsSocket, WsRequest } from './http/ws-core'; +import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. -interface EdgeWebSocket { +interface EdgeWebSocket extends EventfulSocket { accept(): void; - addEventListener( - type: 'message' | 'close' | 'error', - listener: (event: { data?: string | ArrayBuffer }) => void, - ): void; - send(data: string): void; - close(code?: number, reason?: string): void; - readyState: number; } interface EdgeCtx { waitUntil(promise: Promise): void; } declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; -const decoder = new TextDecoder(); - -/** Builds a neutral WsRequest from a Cloudflare Worker request. */ -function toWsRequest(request: Request): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: request.headers.get('cf-connecting-ip') ?? '', - }; -} - -/** Wraps a Cloudflare server-side WebSocket (already accept()ed) as a neutral WsSocket. */ -function edgeSocket(server: EdgeWebSocket): WsSocket { - const inbound = channel(); - const ac = new AbortController(); - server.addEventListener('message', (event) => { - const data = event.data; - inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer)); - }); - server.addEventListener('close', () => { - inbound.close(); - ac.abort(); - }); - server.addEventListener('error', () => { - inbound.fail(new Error('websocket error')); - ac.abort(); - }); - return { - inbound, - abort: ac.signal, - get isOpen() { - return server.readyState === 1; // 1 = OPEN - }, - send: (data) => { - server.send(data); - }, - close: (code, reason) => { - try { - server.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - server.close(); - } catch { - /* already closed */ - } - }, - }; -} - /** * Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair. * Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` @@ -90,13 +23,8 @@ export function edgeHandler( if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); - const lifecycle = app.upgrade(toWsRequest(request), edgeSocket(server)).catch(() => { - try { - server.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? ''); + const lifecycle = upgradeSafely(app, wsReq, eventSocket(server)); if (ctx?.waitUntil) ctx.waitUntil(lifecycle); else void lifecycle; diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts new file mode 100644 index 0000000..8e024c0 --- /dev/null +++ b/src/http/ws-adapter.ts @@ -0,0 +1,120 @@ +import { channel } from '../channel'; +import type { App } from '../app/types'; +import type { WsRequest, WsSocket } from './ws-core'; + +/** + * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket + * to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose: + * that module *runs* a connection, this one *builds* one from a host runtime's socket. + */ + +const decoder = new TextDecoder(); +const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient + +/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */ +export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string { + return typeof data === 'string' ? data : decoder.decode(data); +} + +/** + * Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives + * url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in. + */ +export function toWsRequest(request: Request, ip: string): WsRequest { + const url = new URL(request.url); + const headers: Record = {}; + request.headers.forEach((value, key) => { + headers[key] = value; + }); + + return { + url: url.pathname + url.search, + headers, + protocol: url.protocol === 'https:' ? 'https' : 'http', + ip, + }; +} + +/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */ +export interface EventfulSocket { + readonly readyState: number; + send(data: string): void; + close(code?: number, reason?: string): void; + addEventListener( + type: 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer }) => void, + ): void; +} + +/** + * Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}: + * creates the inbound channel and abort controller and wires message/close/error into them. + * Bun does not use this — its socket events are delivered to a server-level handler rather + * than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`. + */ +export function eventSocket(host: EventfulSocket): WsSocket { + const inbound = channel(); + const ac = new AbortController(); + + host.addEventListener('message', (event) => { + inbound.push(decodeMessage(event.data as string | ArrayBuffer)); + }); + host.addEventListener('close', () => { + inbound.close(); + ac.abort(); + }); + host.addEventListener('error', () => { + inbound.fail(new Error('websocket error')); + ac.abort(); + }); + + return neutralSocket(host, inbound, ac); +} + +/** + * Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an + * already-wired channel and abort controller. `close`/`terminate` swallow throws so + * callers never have to guard an already-closed socket. + */ +export function neutralSocket( + host: Pick & { terminate?(): void }, + inbound: ReturnType>, + ac: AbortController, +): WsSocket { + return { + inbound, + abort: ac.signal, + get isOpen() { + return host.readyState === OPEN; + }, + send: (data) => { + host.send(data); + }, + close: (code, reason) => { + try { + host.close(code, reason); + } catch { + /* already closed */ + } + }, + terminate: () => { + try { + (host.terminate ?? host.close).call(host); + } catch { + /* already closed */ + } + }, + }; +} + +/** + * Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before* + * `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded, + * that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so + * edge can hand it to `ctx.waitUntil`. + */ +export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise { + return app.upgrade(request, socket).catch(() => { + socket.close(1011, 'internal error'); // neutral close already swallows throws + }); +}