`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>
95 lines
3.3 KiB
TypeScript
95 lines
3.3 KiB
TypeScript
import type http from 'http';
|
|
import { once } from 'events';
|
|
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
|
import type { Transport } from '../metadata';
|
|
import type { Bus, Correlation } from '../bus';
|
|
|
|
const PING_MS = 15_000;
|
|
|
|
/**
|
|
* Stream encoder per transport, or `null` for transports that never produce an HTTP stream.
|
|
* A new transport must add a row — the compiler fails until it does, so it can't silently
|
|
* inherit ndjson framing.
|
|
*/
|
|
const STREAM_ENCODERS: Record<Transport, ((accept: string) => StreamEncoder) | null> = {
|
|
buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here
|
|
ws: null, // not an HTTP response; ws routes are served via upgrade, not handle()
|
|
sse: () => sseEncoder,
|
|
ndjson: () => ndjsonEncoder,
|
|
negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder),
|
|
};
|
|
|
|
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */
|
|
export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
|
const pick = STREAM_ENCODERS[transport];
|
|
if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
|
|
|
|
return pick(accept);
|
|
}
|
|
|
|
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
|
|
export async function pipeStream(
|
|
res: http.ServerResponse,
|
|
stream: AsyncIterable<unknown>,
|
|
encoder: StreamEncoder,
|
|
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', trace);
|
|
const iterator = stream[Symbol.asyncIterator]();
|
|
let ping: ReturnType<typeof setInterval> | undefined;
|
|
|
|
if (encoder.ping) {
|
|
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
|
ping.unref?.();
|
|
}
|
|
|
|
const stop = () => {
|
|
if (ping) clearInterval(ping);
|
|
void Promise.resolve(iterator.return?.()).catch(() => {});
|
|
};
|
|
|
|
res.on('close', stop);
|
|
|
|
const closer = () => {
|
|
try {
|
|
res.destroy();
|
|
} catch {
|
|
/* */
|
|
}
|
|
};
|
|
|
|
streams?.add(closer);
|
|
const onClose = once(res, 'close');
|
|
|
|
try {
|
|
while (true) {
|
|
const { value, done } = await iterator.next();
|
|
if (done) break;
|
|
|
|
if (!res.write(encoder.encode(value))) {
|
|
await Promise.race([once(res, 'drain'), onClose]);
|
|
if (res.destroyed) break; // let finally clean up
|
|
}
|
|
}
|
|
} catch (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', trace);
|
|
}
|
|
}
|