diff --git a/src/app/index.ts b/src/app/index.ts index d156c21..5a80b11 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -683,7 +683,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ pattern: plan.pattern, open: async ({ params, inbound, abort, req }) => { const provided = await providedSeed(plan); - // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here + // ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter); + // trustProxy derivation for ws is out of scope here // context is intentionally `any`: each step merges arbitrary keys into it let context: any = { ...provided, @@ -694,8 +695,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ headers: req.headers, inbound, abort, - protocol: (req.socket as any).encrypted ? 'https' : 'http', - ip: req.socket.remoteAddress ?? '', + protocol: req.protocol, + ip: req.ip, }; for (const step of planSteps(plan)) { diff --git a/src/http/ws.ts b/src/http/ws.ts index a2736fe..5f0ae62 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -1,8 +1,7 @@ import http from 'http'; import { channel } from '../channel'; -import { isHttpError } from '../signals'; import type { Bus } from '../bus'; -import { matchPattern } from './router'; +import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core'; import type { WsRouteDef, MeshControl } from './types'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ @@ -43,108 +42,42 @@ function handleMeshUpgrade( return true; } -/** Finds the first ws route whose pattern matches `path`, capturing its params. */ -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); +/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */ +function nodeWsRequest(req: http.IncomingMessage): WsRequest { + return { + url: req.url ?? '/', + headers: req.headers, + protocol: (req.socket as any).encrypted ? 'https' : 'http', + ip: req.socket.remoteAddress ?? '', + }; } -/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */ -function wireInbound(ws: any): { inbound: ReturnType>; abortController: AbortController } { +/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */ +function nodeSocket(ws: any): WsSocket { const inbound = channel(); - const abortController = new AbortController(); + const ac = new AbortController(); ws.on('message', (data: Buffer) => inbound.push(data.toString())); ws.on('close', () => { inbound.close(); - abortController.abort(); + ac.abort(); }); ws.on('error', (err: unknown) => inbound.fail(err)); - - return { inbound, abortController }; -} - -/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ -function trackConnection(ws: any, streams?: Set<() => void>): void { - const closer = () => { - try { - (ws.terminate ?? ws.close).call(ws); - } catch { - /* */ - } + 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: () => (ws.terminate ?? ws.close).call(ws), }; - - streams?.add(closer); - ws.on('close', () => streams?.delete(closer)); -} - -/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */ -async function pumpOutbound(ws: any, iterator: AsyncIterator): Promise { - while (true) { - const { value, done } = await iterator.next(); - if (done) break; - if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone - ws.send(typeof value === 'string' ? value : JSON.stringify(value)); - } - - try { - ws.close(); - } catch { - /* already closed */ - } -} - -/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */ -function closeOnError(ws: any, err: unknown): void { - if (isHttpError(err)) { - const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); - - try { - ws.close(4000 + err.status, reason); - } catch { - /* already closed */ - } - } else { - try { - ws.close(1011); - } catch { - /* already closed */ - } - } -} - -/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */ -async function openWsConnection( - ws: any, - route: { def: WsRouteDef; params: Record | undefined }, - req: http.IncomingMessage, - bus?: Bus, - streams?: Set<() => void>, -): Promise { - trackConnection(ws, streams); - const { inbound, abortController } = wireInbound(ws); - - const name = route.def.pattern; - let iterator: AsyncIterator | undefined; - ws.on('close', () => { - void Promise.resolve(iterator?.return?.()).catch(() => {}); - }); // force-cancel outbound - bus?.emit('stream:open', { name }); - - try { - const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req }); - iterator = outbound[Symbol.asyncIterator](); - await pumpOutbound(ws, iterator); - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - closeOnError(ws, err); - } finally { - abortController.abort(); - bus?.emit('stream:close', { name }); - } } /** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */ @@ -175,6 +108,8 @@ export function attachWs( return; } - wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams)); + wss.handleUpgrade(req, socket, head, (ws: any) => { + void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); + }); }); }