fix(observability): correlate stream events with the request that opened them
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

`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>
This commit is contained in:
chrnx committed 2026-09-01 11:57:39 -05:00
1 parent 7d39aebfab
commit 86a0d9c91b
7 files changed
+134 -15

No files matched your search

+9 -1
View File
@@ -178,7 +178,15 @@ function createRequestHandler(cfg: HandlerConfig) {
}
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return;
}
+10 -4
View File
@@ -2,7 +2,7 @@ import type http from 'http';
import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
const PING_MS = 15_000;
@@ -35,10 +35,16 @@ export async function pipeStream(
bus?: Bus,
name = '',
streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> {
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
// is always the route pattern, never the concrete path the request events can carry — but a
// consumer following the documented contract labels on `route` and would otherwise find it
// absent on the longest-lived thing the server does. See `EventPayload.name`.
const trace = { name, route: name, ...correlation };
res.writeHead(200, encoder.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
@@ -76,13 +82,13 @@ export async function pipeStream(
}
}
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame);
} finally {
if (ping) clearInterval(ping);
streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end();
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}
+17 -7
View File
@@ -1,5 +1,5 @@
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
import { createRequestGate } from './request-gate';
import {
handle,
@@ -26,9 +26,13 @@ export function asReadableStream(
encoder: StreamEncoder,
bus?: Bus,
name = '',
correlation: Correlation = {},
): ReadableStream<Uint8Array> {
const iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder();
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
// says label on `route`, so both are carried.
const trace = { name, route: name, ...correlation };
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
// its own path — so the close is latched rather than emitted from each of the three exits.
@@ -37,12 +41,12 @@ export function asReadableStream(
const close = (): void => {
if (closed) return;
closed = true;
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
};
return new ReadableStream<Uint8Array>({
start() {
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
},
async pull(controller) {
try {
@@ -56,7 +60,7 @@ export function asReadableStream(
controller.enqueue(frame(encoder.encode(value)));
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
const errorFrame = encoder.encodeError(err);
close();
@@ -154,11 +158,17 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus): Response {
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') {
const body = asReadableStream(result.outcome.stream, result.outcome.encoder, bus, result.outcome.route);
const body = asReadableStream(
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
correlation,
);
return new Response(body, { headers });
}
@@ -262,6 +272,6 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
});
}
return outcomeToResponse(result, opts?.bus);
return outcomeToResponse(result, opts?.bus, correlation);
};
}
+9 -3
View File
@@ -1,5 +1,6 @@
import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
@@ -109,6 +110,11 @@ export async function runWsConnection(
): 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 = () => {
@@ -117,7 +123,7 @@ export async function runWsConnection(
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
try {
const outbound = await route.def.open({
@@ -129,9 +135,9 @@ export async function runWsConnection(
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}