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>
This commit is contained in:
7 files changed
+134
-15
No files matched your search
@@ -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<string | undefined>();
|
||||
const traces = new Set<string | undefined>();
|
||||
const routes = new Set<string | undefined>();
|
||||
|
||||
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<string | undefined> = [];
|
||||
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.
|
||||
|
||||
@@ -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<Record<string, unknown>[]> => {
|
||||
const bus = new Bus();
|
||||
const seen: Record<string, unknown>[] = [];
|
||||
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');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user