diff --git a/src/bus.ts b/src/bus.ts index 8ae39c3..db83d70 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -30,6 +30,11 @@ export type LifecycleEvent = | 'request:step:enter' | 'request:step:leave' | 'request:step:error' + // A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately + // *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its + // connection may live for hours, so `request:end` fires at the handler's return and these three + // describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is + // what lets a consumer join the two rather than watch them as unrelated streams of events. | 'stream:open' | 'stream:close' | 'stream:error' diff --git a/src/http/server.ts b/src/http/server.ts index a07e50c..247cc56 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -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; } diff --git a/src/http/stream.ts b/src/http/stream.ts index f34783c..1f69ec3 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -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 { + // `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 | 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); } } diff --git a/src/http/web.ts b/src/http/web.ts index 6d3fbe0..48002a5 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -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 { 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({ 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; 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); }; } diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 6a5bd71..15414af 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -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 { 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 | 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); } } diff --git a/test/stream-lifecycle-parity.test.ts b/test/stream-lifecycle-parity.test.ts index d32dc09..3479676 100644 --- a/test/stream-lifecycle-parity.test.ts +++ b/test/stream-lifecycle-parity.test.ts @@ -95,6 +95,48 @@ describe('stream lifecycle events, on every adapter', () => { }); } + for (const adapter of ADAPTERS) { + it(`${adapter.name}: correlates every stream event with the request that opened it`, async () => { + // The split is deliberate — `request:end` fires when the handler returns, not when the + // stream it produced finishes, so an hour-long SSE connection and a 2ms reply never share a + // latency distribution. That only works if the two can be joined, and this is the join key. + const bus = new Bus(); + const ids = new Set(); + const traces = new Set(); + const routes = new Set(); + + for (const name of ['stream:open', 'stream:close'] as const) + bus.on(name, (e) => { + ids.add(e.requestId); + traces.add(e.traceId); + routes.add(e.route); + }); + + await adapter.serve(clean, bus); + + expect([...ids]).toHaveLength(1); + expect([...ids][0]).toMatch(/^[0-9a-f-]{36}$/); // one id, and it is the request's + // Bounded by the route table, which is what makes it the field to label a metric on. + expect([...routes]).toEqual(['/feed']); + expect([...traces]).toEqual([undefined]); // absent, not invented, when no traceparent arrived + }); + } + + it('fetch: adopts the gateway s x-request-id rather than opening a second identity', async () => { + const bus = new Bus(); + const ids: Array = []; + bus.on('stream:open', (e) => ids.push(e.requestId)); + bus.on('stream:close', (e) => ids.push(e.requestId)); + + await ( + await buildFetch(clean, { bus })( + new Request('http://x/feed', { headers: { 'x-request-id': 'from-the-gateway', traceparent: 'tp-1' } }), + ) + ).text(); + + expect(ids).toEqual(['from-the-gateway', 'from-the-gateway']); + }); + it('fetch: closes once when the client cancels mid-stream', async () => { // The exit `pipeStream` gets from `res.on('close')` and the ReadableStream gets from `cancel`. // Latched, because a cancel can also land after the body has already ended. diff --git a/test/ws-core.test.ts b/test/ws-core.test.ts index e93ec66..7684c49 100644 --- a/test/ws-core.test.ts +++ b/test/ws-core.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'; import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core'; import { channel } from '../src/channel'; import { HttpError } from '../src/signals'; +import { Bus } from '../src/bus'; import type { WsRouteDef } from '../src/http/types'; /** A controllable fake WsSocket that records sends and closes. */ @@ -110,3 +111,44 @@ describe('runWsConnection (neutral core)', () => { expect(matchWsRoute(routes, '/nope')).toBeUndefined(); }); }); + +describe('runWsConnection correlation', () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => + (async function* () { + yield 'hi'; + })(), + }; + + const opened = async (headers: WsRequest['headers']): Promise[]> => { + const bus = new Bus(); + const seen: Record[] = []; + for (const name of ['stream:open', 'stream:close'] as const) + bus.on(name, (e) => seen.push({ ...e })); + const { socket } = fakeSocket(); + await runWsConnection(socket, { ...req, headers }, { def, params: {} }, bus); + return seen; + }; + + it('gives the connection one identity, not one per emitter', async () => { + const seen = await opened({}); + expect(seen).toHaveLength(2); + expect(seen[0].requestId).toMatch(/^[0-9a-f-]{36}$/); + expect(seen[1].requestId).toBe(seen[0].requestId); + }); + + it('adopts a gateway s x-request-id and carries traceparent through', async () => { + // An upgrade is an HTTP request with headers like any other: a service behind a proxy must not + // open a second identity for a connection that already has one. + const seen = await opened({ 'x-request-id': 'gw-1', traceparent: 'tp-1' }); + expect(seen.map((e) => e.requestId)).toEqual(['gw-1', 'gw-1']); + expect(seen.map((e) => e.traceId)).toEqual(['tp-1', 'tp-1']); + }); + + it('labels the route pattern and names the transport', async () => { + const [open] = await opened({}); + expect(open.route).toBe('/ws'); + expect(open.transport).toBe('ws'); + }); +});