refactor(ws): Node adapter builds WsSocket over the neutral core
Also fixes buildWsRoutes (app/index.ts) to read the pre-derived protocol/ip off the neutral WsRequest instead of req.socket, which no longer exists now that WsOpenCtx.req is WsRequest — without this every real @Ws route throws on open() and the connection hangs. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+35
-99
No files matched your search
+4
-3
@@ -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)) {
|
||||
|
||||
+31
-96
@@ -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<string, string> | 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<typeof channel<unknown>>; 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<unknown>();
|
||||
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<unknown>): Promise<void> {
|
||||
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<string, string> | undefined },
|
||||
req: http.IncomingMessage,
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
trackConnection(ws, streams);
|
||||
const { inbound, abortController } = wireInbound(ws);
|
||||
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user