diff --git a/src/http/types.ts b/src/http/types.ts index 44cdcd3..ddd02db 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -3,6 +3,7 @@ import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; +import type { WsRequest } from './ws-core'; /** Per-request size and timeout ceilings applied by the server. */ export interface RequestLimits { @@ -54,12 +55,12 @@ export interface MatchedRoute { def: RouteDef; } -/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */ +/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */ export interface WsOpenCtx { params: Record; inbound: AsyncIterable; abort: AbortSignal; - req: http.IncomingMessage; + req: WsRequest; } /** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */ diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts new file mode 100644 index 0000000..8e411af --- /dev/null +++ b/src/http/ws-core.ts @@ -0,0 +1,114 @@ +import { isHttpError } from '../signals'; +import type { Bus } from '../bus'; +import { matchPattern } from './router'; +import type { WsRouteDef } from './types'; + +/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */ +export interface WsRequest { + url: string; + headers: Record; + protocol: 'http' | 'https'; + ip: string; +} + +/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */ +export interface WsSocket { + readonly inbound: AsyncIterable; + readonly abort: AbortSignal; + readonly isOpen: boolean; + send(data: string): void; + close(code?: number, reason?: string): void; + terminate(): void; +} + +/** Finds the first ws route whose pattern matches `path`, capturing its params. */ +export function matchWsRoute( + wsRoutes: WsRouteDef[], + path: string, +): { def: WsRouteDef; params: Record | undefined } | undefined { + return wsRoutes + .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) + .find((entry) => entry.params); +} + +/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ +function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } { + const closer = () => { + try { + socket.terminate(); + } catch { + /* */ + } + }; + + streams?.add(closer); + return { closer }; +} + +/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */ +async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator): Promise { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + if (!socket.isOpen) break; + socket.send(typeof value === 'string' ? value : JSON.stringify(value)); + } + + try { + socket.close(); + } catch { + /* already closed */ + } +} + +/** Closes with 4000+status for HttpErrors, 1011 otherwise. */ +function closeOnError(socket: WsSocket, err: unknown): void { + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + + try { + socket.close(4000 + err.status, reason); + } catch { + /* already closed */ + } + } else { + try { + socket.close(1011); + } catch { + /* already closed */ + } + } +} + +/** Runs the full per-connection lifecycle over a neutral socket capability. */ +export async function runWsConnection( + socket: WsSocket, + request: WsRequest, + route: { def: WsRouteDef; params: Record | undefined }, + bus?: Bus, + streams?: Set<() => void>, +): Promise { + const { closer } = trackConnection(socket, streams); + const name = route.def.pattern; + let iterator: AsyncIterator | undefined; + const cancelOutbound = () => void Promise.resolve(iterator?.return?.()).catch(() => {}); + socket.abort.addEventListener('abort', cancelOutbound, { once: true }); + bus?.emit('stream:open', { name }); + + try { + const outbound = await route.def.open({ + params: route.params ?? {}, + inbound: socket.inbound, + abort: socket.abort, + req: request, + }); + iterator = outbound[Symbol.asyncIterator](); + await pumpOutbound(socket, iterator); + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + closeOnError(socket, err); + } finally { + streams?.delete(closer); + bus?.emit('stream:close', { name }); + } +} diff --git a/test/ws-core.test.ts b/test/ws-core.test.ts new file mode 100644 index 0000000..e93ec66 --- /dev/null +++ b/test/ws-core.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect } from 'vitest'; +import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core'; +import { channel } from '../src/channel'; +import { HttpError } from '../src/signals'; +import type { WsRouteDef } from '../src/http/types'; + +/** A controllable fake WsSocket that records sends and closes. */ +function fakeSocket() { + const inbound = channel(); + const ac = new AbortController(); + const sent: string[] = []; + const closes: Array<{ code?: number; reason?: string }> = []; + let open = true; + const socket: WsSocket = { + inbound, + abort: ac.signal, + get isOpen() { + return open; + }, + send: (d) => sent.push(d), + close: (code, reason) => { + open = false; + closes.push({ code, reason }); + ac.abort(); + }, + terminate: () => { + open = false; + ac.abort(); + }, + }; + return { socket, inbound, sent, closes, ac }; +} + +const req: WsRequest = { url: '/ws', headers: {}, protocol: 'http', ip: '127.0.0.1' }; + +describe('runWsConnection (neutral core)', () => { + it('sends each yielded outbound value, string or JSON', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => + (async function* () { + yield 'hi'; + yield { n: 1 }; + })(), + }; + const { socket, sent } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(sent).toEqual(['hi', JSON.stringify({ n: 1 })]); + }); + + it('closes with 4000+status when the route throws an HttpError', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => { + throw new HttpError(401, 'nope'); + }, + }; + const { socket, closes } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(closes[0].code).toBe(4401); + expect(closes[0].reason).toBe('nope'); + }); + + it('closes with 1011 on a generic throw', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => { + throw new Error('boom'); + }, + }; + const { socket, closes } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(closes[0].code).toBe(1011); + }); + + it('registers a closer in the shutdown registry and removes it when done', async () => { + const streams = new Set<() => void>(); + const def: WsRouteDef = { + pattern: '/ws', + open: async () => + (async function* () { + yield 'x'; + })(), + }; + const { socket } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }, undefined, streams); + expect(streams.size).toBe(0); // added then removed + }); + + it('passes inbound + params + request to route.open', async () => { + let seen: any; + const def: WsRouteDef = { + pattern: '/ws/:id', + open: async (ctx) => { + seen = ctx; + return (async function* () {})(); + }, + }; + const { socket } = fakeSocket(); + await runWsConnection(socket, req, { def, params: { id: '7' } }); + expect(seen.params).toEqual({ id: '7' }); + expect(seen.req).toBe(req); + expect(typeof seen.inbound[Symbol.asyncIterator]).toBe('function'); + expect(seen.abort).toBeInstanceOf(AbortSignal); + }); + + it('matchWsRoute finds a pattern and captures params', () => { + const routes: WsRouteDef[] = [{ pattern: '/ws/:id', open: async () => (async function* () {})() }]; + expect(matchWsRoute(routes, '/ws/42')?.params).toEqual({ id: '42' }); + expect(matchWsRoute(routes, '/nope')).toBeUndefined(); + }); +});