`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>
155 lines
5.0 KiB
TypeScript
155 lines
5.0 KiB
TypeScript
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. */
|
|
function fakeSocket() {
|
|
const inbound = channel<unknown>();
|
|
const ac = new AbortController();
|
|
const sent: string[] = [];
|
|
const closes: Array<{ code?: number; reason?: string }> = [];
|
|
let open = true;
|
|
const socket: WsSocket = {
|
|
inbound,
|
|
abort: ac.signal,
|
|
get isOpen() {
|
|
return open;
|
|
},
|
|
send: (d) => sent.push(d),
|
|
close: (code, reason) => {
|
|
open = false;
|
|
closes.push({ code, reason });
|
|
ac.abort();
|
|
},
|
|
terminate: () => {
|
|
open = false;
|
|
ac.abort();
|
|
},
|
|
};
|
|
return { socket, inbound, sent, closes, ac };
|
|
}
|
|
|
|
const req: WsRequest = { url: '/ws', headers: {}, protocol: 'http', ip: '127.0.0.1' };
|
|
|
|
describe('runWsConnection (neutral core)', () => {
|
|
it('sends each yielded outbound value, string or JSON', async () => {
|
|
const def: WsRouteDef = {
|
|
pattern: '/ws',
|
|
open: async () =>
|
|
(async function* () {
|
|
yield 'hi';
|
|
yield { n: 1 };
|
|
})(),
|
|
};
|
|
const { socket, sent } = fakeSocket();
|
|
await runWsConnection(socket, req, { def, params: {} });
|
|
expect(sent).toEqual(['hi', JSON.stringify({ n: 1 })]);
|
|
});
|
|
|
|
it('closes with 4000+status when the route throws an HttpError', async () => {
|
|
const def: WsRouteDef = {
|
|
pattern: '/ws',
|
|
open: async () => {
|
|
throw new HttpError(401, 'nope');
|
|
},
|
|
};
|
|
const { socket, closes } = fakeSocket();
|
|
await runWsConnection(socket, req, { def, params: {} });
|
|
expect(closes[0].code).toBe(4401);
|
|
expect(closes[0].reason).toBe('nope');
|
|
});
|
|
|
|
it('closes with 1011 on a generic throw', async () => {
|
|
const def: WsRouteDef = {
|
|
pattern: '/ws',
|
|
open: async () => {
|
|
throw new Error('boom');
|
|
},
|
|
};
|
|
const { socket, closes } = fakeSocket();
|
|
await runWsConnection(socket, req, { def, params: {} });
|
|
expect(closes[0].code).toBe(1011);
|
|
});
|
|
|
|
it('registers a closer in the shutdown registry and removes it when done', async () => {
|
|
const streams = new Set<() => void>();
|
|
const def: WsRouteDef = {
|
|
pattern: '/ws',
|
|
open: async () =>
|
|
(async function* () {
|
|
yield 'x';
|
|
})(),
|
|
};
|
|
const { socket } = fakeSocket();
|
|
await runWsConnection(socket, req, { def, params: {} }, undefined, streams);
|
|
expect(streams.size).toBe(0); // added then removed
|
|
});
|
|
|
|
it('passes inbound + params + request to route.open', async () => {
|
|
let seen: any;
|
|
const def: WsRouteDef = {
|
|
pattern: '/ws/:id',
|
|
open: async (ctx) => {
|
|
seen = ctx;
|
|
return (async function* () {})();
|
|
},
|
|
};
|
|
const { socket } = fakeSocket();
|
|
await runWsConnection(socket, req, { def, params: { id: '7' } });
|
|
expect(seen.params).toEqual({ id: '7' });
|
|
expect(seen.req).toBe(req);
|
|
expect(typeof seen.inbound[Symbol.asyncIterator]).toBe('function');
|
|
expect(seen.abort).toBeInstanceOf(AbortSignal);
|
|
});
|
|
|
|
it('matchWsRoute finds a pattern and captures params', () => {
|
|
const routes: WsRouteDef[] = [{ pattern: '/ws/:id', open: async () => (async function* () {})() }];
|
|
expect(matchWsRoute(routes, '/ws/42')?.params).toEqual({ id: '42' });
|
|
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');
|
|
});
|
|
});
|