Files
core/src/http/ws-core.ts
T
chrnx 86a0d9c91b
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 13s
fix(observability): correlate stream events with the request that opened them
`src/http/core.ts` documented the design as "`stream:open`/`stream:close` already describe
the connection, and now carry the same `requestId`". They carried `{ name }` and nothing
else, on all three emitters, and `Bus.emit` forwards a payload verbatim — so there was
nowhere else it could have been arriving from. The comment described an intent that was
never carried out.

The split it describes is right: a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so ending the request span at the
handler's return keeps hour-long SSE connections out of the same latency distribution as
2ms replies. But the split only works if the two can be **joined**, and `requestId` is the
join key — it is what `EventPayload` defines itself as. Without it an exporter could not
say which request opened the connection still holding a slot, and `traceId`, carried
verbatim so an exporter can hand it to OTLP, never reached the longest-lived thing the
server does.

`route` comes along for a second reason. The contract this beta settled says label on
`route`, never on `name` — and `route` was absent from precisely the events a stream gauge
is built from, leaving a correct consumer with nothing to label. On a stream event `name`
is always the route pattern rather than the concrete path, so the two are the same value
here; both are emitted because the rule a consumer follows is written against `route`.

A WebSocket upgrade correlates itself. It is an HTTP request with headers like any other,
so `runWsConnection` derives its own correlation and adopts a gateway's `x-request-id`
rather than opening a second identity for a connection that already has one. Deriving it
in the one place a ws connection is set up is what keeps it one identity per connection
instead of one per emitter, and it also carries `transport: 'ws'`, which nothing on that
path previously distinguished.

Verified non-vacuous: reverting `src/` fails exactly the six new correlation assertions
across the three emitters and leaves the thirteen lifecycle ones green.

Closes #84

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:57:39 -05:00

144 lines
4.4 KiB
TypeScript

import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
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<string, string | string[] | undefined>;
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<unknown>;
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<string, string> | undefined } | undefined {
return wsRoutes
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
.find((entry) => entry.params);
}
/**
* Runs `connection` with the socket registered for force-close on shutdown, unregistering it
* when the connection ends. Without this a long-lived socket keeps `server.close()` waiting for
* a peer that has no reason to hang up — the mesh control channel is exactly that shape.
*/
export async function trackUntil(
socket: WsSocket,
connection: Promise<void>,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
try {
await connection;
} finally {
streams?.delete(closer);
}
}
/** 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<unknown>): Promise<void> {
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 = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
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<string, string> | undefined },
bus?: Bus,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
const name = route.def.pattern;
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
// keeps one identity per connection instead of one per emitter.
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => {
streams?.delete(closer);
void Promise.resolve(iterator?.return?.()).catch(() => {});
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', trace);
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', { ...trace, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', trace);
}
}