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
+32
-96
No files matched your search
+4
-3
@@ -683,7 +683,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
|||||||
pattern: plan.pattern,
|
pattern: plan.pattern,
|
||||||
open: async ({ params, inbound, abort, req }) => {
|
open: async ({ params, inbound, abort, req }) => {
|
||||||
const provided = await providedSeed(plan);
|
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
|
// context is intentionally `any`: each step merges arbitrary keys into it
|
||||||
let context: any = {
|
let context: any = {
|
||||||
...provided,
|
...provided,
|
||||||
@@ -694,8 +695,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
|||||||
headers: req.headers,
|
headers: req.headers,
|
||||||
inbound,
|
inbound,
|
||||||
abort,
|
abort,
|
||||||
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
protocol: req.protocol,
|
||||||
ip: req.socket.remoteAddress ?? '',
|
ip: req.ip,
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const step of planSteps(plan)) {
|
for (const step of planSteps(plan)) {
|
||||||
|
|||||||
+28
-93
@@ -1,8 +1,7 @@
|
|||||||
import http from 'http';
|
import http from 'http';
|
||||||
import { channel } from '../channel';
|
import { channel } from '../channel';
|
||||||
import { isHttpError } from '../signals';
|
|
||||||
import type { Bus } from '../bus';
|
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';
|
import type { WsRouteDef, MeshControl } from './types';
|
||||||
|
|
||||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||||
@@ -43,108 +42,42 @@ function handleMeshUpgrade(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
||||||
function matchWsRoute(
|
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||||
wsRoutes: WsRouteDef[],
|
return {
|
||||||
path: string,
|
url: req.url ?? '/',
|
||||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
headers: req.headers,
|
||||||
return wsRoutes
|
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
||||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
ip: req.socket.remoteAddress ?? '',
|
||||||
.find((entry) => entry.params);
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */
|
/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */
|
||||||
function wireInbound(ws: any): { inbound: ReturnType<typeof channel<unknown>>; abortController: AbortController } {
|
function nodeSocket(ws: any): WsSocket {
|
||||||
const inbound = channel<unknown>();
|
const inbound = channel<unknown>();
|
||||||
const abortController = new AbortController();
|
const ac = new AbortController();
|
||||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||||
ws.on('close', () => {
|
ws.on('close', () => {
|
||||||
inbound.close();
|
inbound.close();
|
||||||
abortController.abort();
|
ac.abort();
|
||||||
});
|
});
|
||||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||||
|
return {
|
||||||
return { inbound, abortController };
|
inbound,
|
||||||
}
|
abort: ac.signal,
|
||||||
|
get isOpen() {
|
||||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
return ws.readyState === 1; // 1 = OPEN
|
||||||
function trackConnection(ws: any, streams?: Set<() => void>): void {
|
},
|
||||||
const closer = () => {
|
send: (data) => ws.send(data),
|
||||||
|
close: (code, reason) => {
|
||||||
try {
|
try {
|
||||||
(ws.terminate ?? ws.close).call(ws);
|
ws.close(code, reason);
|
||||||
} catch {
|
} 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. */
|
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
|
||||||
@@ -175,6 +108,8 @@ export function attachWs(
|
|||||||
return;
|
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