From ccd329d12b8a92a802b514ebca5446f9cabcd34c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:32:17 -0500 Subject: [PATCH 1/5] perf(boot): run independent providers concurrently MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bootProviders` was a `for...of` with an `await` inside, so three providers that share nothing took the sum of their latencies rather than the longest one. Measured on the issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after. The graph already knew. `topoSort` proves which nodes cannot constrain each other and then throws that away by returning a flat list; `topoLevels` groups the sorted list back into dependency levels in one forward pass, and boot runs a level with `Promise.all`. Nothing else about the ordering changes: level N is fully registered and warmed before level N+1 starts, which is the same guarantee the sequential walk gave. This is the second thing users get for declaring `needs`/`provides` instead of ordering `app.use` calls by hand. Pruning was the first. An Express app cannot parallelize its middleware because nothing declares what is independent — we have that declaration and were not spending it. Three things had to survive the change, and each has a test: - **Teardown stays deterministic.** Registration follows level order, not completion order, so the registry running in reverse still gives dependants teardown before their dependencies. Following whichever provider settled first would have turned that from a guarantee into luck. - **A failed sibling does not strand the level.** `bootProvider` returns an outcome instead of rejecting, and successful teardowns are registered before any failure is raised — so a boot aborted by a required provider still leaves whatever its siblings opened closeable. Previously they had not started at all; now they may be in flight. - **A provider that threw gets no teardown**, unchanged: it never provided anything, and `dispose()` on a half-constructed one is how a teardown finds a null connection. Behaviour visible to a bus consumer: `boot:provider:start` no longer strictly alternates with `:ok`. A level emits its starts together, then its results. That is the truth about what is happening rather than a change in what is reported. Verified non-vacuous: reverting `src/` fails the overlap assertion and all five `topoLevels` cases, and puts the benchmark back at 616ms. Closes #71 Signed-off-by: Diego Resendez --- src/app/index.ts | 80 +++++++++---- src/graph.ts | 29 +++++ test/boot-concurrency.test.ts | 205 ++++++++++++++++++++++++++++++++++ test/graph.test.ts | 30 ++++- 4 files changed, 319 insertions(+), 25 deletions(-) create mode 100644 test/boot-concurrency.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 926e141..71ae619 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -2,7 +2,7 @@ import type http from 'http'; import { Bus, type Events } from '../bus'; import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { Container } from '../container'; -import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; +import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; @@ -937,8 +937,41 @@ function applyOverrides(overrides: Record | undefined, registry } } +/** What a provider's boot produced: nothing to say, or the error it failed with. */ +interface BootOutcome { + node: GraphNode; + error?: Error; +} + +/** Boots one provider and registers its value. Never rejects — the caller decides what a failure means. */ +async function bootProvider( + node: GraphNode, + deps: { runners: Map; container: Container; bus: Bus }, +): Promise { + const { runners, container, bus } = deps; + bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); + + try { + const value = await runners.get(node.name)!(await snapshot(container, node.needs)); + container.register(node.name, 'app', () => value); + await container.resolve(node.name); // warm the cache + bus.emit('boot:provider:ok', { name: node.name }); + return { node }; + } catch (error) { + bus.emit('boot:provider:fail', { name: node.name, error }); + return { node, error: error as Error }; + } +} + /** - * Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn. + * Runs app-scoped providers level by level — concurrently within a level, sequentially between + * them; required failures abort, optional ones warn. + * + * The topo sort already proved nothing in a level can order anything else in it, so serializing a + * level only ever bought latency: an app paid the sum of its providers' boot times instead of its + * longest chain. Concurrency is the second thing the graph earns its users, after pruning, and the + * one a middleware chain structurally cannot offer. + * * @returns The names of optional providers that failed and are running degraded (unregistered). */ async function bootProviders( @@ -953,40 +986,39 @@ async function bootProviders( logger: Logger; }, ): Promise { - const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps; + const { providerMeta, providerInstances, teardown, logger } = deps; const degraded: string[] = []; - for (const node of orderedProviders) { - bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); + for (const level of topoLevels(orderedProviders)) { + // Outcomes rather than rejections: a sibling that throws must not strand the ones that + // succeeded, or a provider that opened a pool would never get its dispose() registered. + const outcomes = await Promise.all(level.map((node) => bootProvider(node, deps))); - try { - const value = await runners.get(node.name)!(await snapshot(container, node.needs)); - container.register(node.name, 'app', () => value); - await container.resolve(node.name); // warm the cache - // Registered here, as it boots, rather than where it was collected. `orderedProviders` is - // topologically sorted, so registration order *is* boot order — and the registry running in - // reverse then gives dependants teardown before their dependencies for free, with no second - // sort to keep in step with this one. - // - // Inside the try on purpose: a provider that threw never provided anything, and calling - // dispose() on a half-constructed one is how a teardown finds a null connection. + // Teardown in level order, not completion order. `orderedProviders` is topologically sorted and + // the registry runs in reverse, which is what gives dependants teardown before their + // dependencies for free — a guarantee that would have become luck if this followed whichever + // provider happened to settle first. Registered before the failure pass so a level that aborts + // the boot still leaves its successful siblings closeable. + // + // Skipped for a failure on purpose: a provider that threw never provided anything, and calling + // dispose() on a half-constructed one is how a teardown finds a null connection. + for (const { node, error } of outcomes) { + if (error) continue; const instance = providerInstances.get(node.name); if (instance?.dispose) teardown.add(() => instance.dispose!()); - bus.emit('boot:provider:ok', { name: node.name }); - } catch (error) { - bus.emit('boot:provider:fail', { name: node.name, error }); + } + + for (const { node, error } of outcomes) { + if (!error) continue; if (!providerMeta.get(node.name)?.optional) { - throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`); + throw new Error(`provider '${node.name}' failed: ${error.message}`); } // optional: warn, leave it unregistered; routes needing it fail at request time // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here degraded.push(node.name); - logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, { - provider: node.name, - error, - }); + logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error }); } } diff --git a/src/graph.ts b/src/graph.ts index b576dfd..75e22e4 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -78,6 +78,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { return ordered; } +/** + * Groups an already topo-sorted list into dependency levels: nothing in a level can constrain + * anything else in it, and a level depends only on the levels before it — so a level can run + * concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain + * nothing and are ignored. + */ +export function topoLevels(ordered: GraphNode[]): GraphNode[][] { + const producedBy = new Map(); + for (const node of ordered) for (const key of node.provides) producedBy.set(key, node); + const depthOf = new Map(); + const levels: GraphNode[][] = []; + + // One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's + // needs already has its depth by the time the node is reached. + for (const node of ordered) { + let depth = 0; + + for (const key of node.needs) { + const producer = producedBy.get(key); + if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1); + } + + depthOf.set(node, depth); + (levels[depth] ??= []).push(node); + } + + return levels; +} + /** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { const producedBy = new Map(); diff --git a/test/boot-concurrency.test.ts b/test/boot-concurrency.test.ts new file mode 100644 index 0000000..d12e4ed --- /dev/null +++ b/test/boot-concurrency.test.ts @@ -0,0 +1,205 @@ +// Independent providers boot concurrently; dependent ones still wait. +// +// The graph already proved which providers cannot constrain each other — that is what the topo +// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies +// instead of its longest chain, for no ordering anyone declared. +// +// Timing is asserted structurally rather than by clock: "all three entered before any left" is +// the same claim as "they overlapped" and does not get flaky on a loaded CI box. +import 'reflect-metadata'; +import { describe, expect, it, vi } from 'vitest'; +import { Get, Module, Provider, Route, type Ctor } from '../src/metadata'; +import { createApp } from '../src/app'; +import type { Logger } from '../src/logger'; + +const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }); +const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); + +@Route('/') +class Ctl { + @Get('/ping') ping() { + return { ok: true }; + } +} + +/** Boots the app by serving one request — providers are lazy until something is actually served. */ +async function boot(module: Ctor, logger = silentLogger()): Promise { + const app = createApp({ modules: [module], logger }); + await app.fetch(new Request('http://x/ping')); + await app.close(); +} + +describe('provider boot concurrency', () => { + it('overlaps providers that do not depend on each other', async () => { + const log: string[] = []; + + const independent = (name: string): Ctor => { + @Provider({ provides: name }) + class P { + async provide() { + log.push(`${name}:in`); + await sleep(10); + log.push(`${name}:out`); + return { [name]: name }; + } + } + return P; + }; + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] }) + class M {} + await boot(M); + + // Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit. + expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']); + expect(log).toHaveLength(6); + }); + + it('still waits for a provider its dependant needs', async () => { + const log: string[] = []; + + @Provider({ provides: 'base' }) + class Base { + async provide() { + log.push('base:in'); + await sleep(10); + log.push('base:out'); + return { base: 1 }; + } + } + + @Provider({ provides: 'derived', needs: ['base'] }) + class Derived { + provide(ctx: { base: number }) { + log.push('derived:in'); + return { derived: ctx.base + 1 }; + } + } + + // Declared out of order on purpose: the wait is the graph's doing, not the array's. + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] }) + class M {} + await boot(M); + + expect(log).toEqual(['base:in', 'base:out', 'derived:in']); + }); + + it('gives a dependant every value from its level, not just the one that finished first', async () => { + @Provider({ provides: 'slow' }) + class Slow { + async provide() { + await sleep(15); + return { slow: 'slow' }; + } + } + + @Provider({ provides: 'fast' }) + class Fast { + provide() { + return { fast: 'fast' }; + } + } + + let seen: Record = {}; + @Provider({ provides: 'joined', needs: ['slow', 'fast'] }) + class Joined { + provide(ctx: Record) { + seen = { slow: ctx.slow, fast: ctx.fast }; + return { joined: true }; + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] }) + class M {} + await boot(M); + + expect(seen).toEqual({ slow: 'slow', fast: 'fast' }); + }); + + it('tears down in reverse boot order even though boot is concurrent', async () => { + const disposed: string[] = []; + + const independent = (name: string, delay: number): Ctor => { + @Provider({ provides: name }) + class P { + async provide() { + await sleep(delay); + return { [name]: name }; + } + dispose() { + disposed.push(name); + } + } + return P; + }; + + // `c` finishes first and `a` last — completion order is the reverse of declaration order, so a + // teardown registered as each one lands would come out in a different order than this. + @Module({ + mountpoint: '/', + controllers: [Ctl], + providers: [independent('a', 20), independent('b', 10), independent('c', 1)], + }) + class M {} + await boot(M); + + expect(disposed).toEqual(['c', 'b', 'a']); + }); + + it('fails the boot on a required provider, and still registers its siblings for teardown', async () => { + const disposed: string[] = []; + + @Provider({ provides: 'ok' }) + class Ok { + async provide() { + await sleep(10); // still in flight when its sibling rejects + return { ok: true }; + } + dispose() { + disposed.push('ok'); + } + } + + @Provider({ provides: 'broken' }) + class Broken { + provide(): never { + throw new Error('no pool'); + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + + await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool"); + // The sibling booted — it was already in flight — so whatever it opened has to be closeable. + await app.close(); + expect(disposed).toEqual(['ok']); + }); + + it('degrades an optional provider without taking its level down', async () => { + const logger = silentLogger(); + + @Provider({ provides: 'flaky', optional: true }) + class Flaky { + provide(): never { + throw new Error('nope'); + } + } + + @Provider({ provides: 'solid' }) + class Solid { + provide() { + return { solid: true }; + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] }) + class M {} + const app = createApp({ modules: [M], logger }); + await app.fetch(new Request('http://x/ping')); + + expect(app.degraded()).toEqual(['flaky']); + await app.close(); + }); +}); diff --git a/test/graph.test.ts b/test/graph.test.ts index dc5e825..41cd419 100644 --- a/test/graph.test.ts +++ b/test/graph.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, test } from 'vitest'; -import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph'; +import { topoSort, topoLevels, GraphNode, subgraphFor, nearest } from '../src/graph'; const node = (name: string, needs: string[], provides: string[]): GraphNode => ({ name, needs, provides, origin: 'test' }); @@ -42,6 +42,34 @@ describe('subgraphFor', () => { }); }); +describe('topoLevels', () => { + const levels = (ordered: GraphNode[]): string[][] => topoLevels(ordered).map((l) => l.map((n) => n.name)); + + it('puts nodes that cannot constrain each other in the same level', () => { + expect(levels([N('a'), N('b'), N('c')])).toEqual([['a', 'b', 'c']]); + }); + + it('pushes a node past every producer it needs, not just its first', () => { + // `late` needs a depth-0 and a depth-1 node, so it belongs at 2 — taking the max, not the first. + const ordered = [N('config'), N('db', ['config']), N('late', ['config', 'db'])]; + expect(levels(ordered)).toEqual([['config'], ['db'], ['late']]); + }); + + it('ignores needs nothing here produces, so a seed does not push a node down a level', () => { + expect(levels([N('a'), N('user', ['req', 'params'])])).toEqual([['a', 'user']]); + }); + + it('leaves no gaps, so every level has something to run', () => { + const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []); + expect(topoLevels(ordered).every((level) => level.length > 0)).toBe(true); + }); + + it('keeps every node exactly once', () => { + const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []); + expect(topoLevels(ordered).flat().map((n) => n.name).sort()).toEqual(['a', 'b', 'c', 'solo']); + }); +}); + describe('nearest', () => { it('suggests a close candidate (edit distance <= 2)', () => { expect(nearest('usr', ['user', 'config', 'db'])).toBe('user'); -- 2.54.1 From 7b3fe57590d839599f2d4a3ab42cbd790a9c23b7 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:47:14 -0500 Subject: [PATCH 2/5] feat(sse): emit id:, so an EventSource reconnect has something to resume from MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `sseEncoder` wrote one field. With no `id:` on the wire the browser had nothing to put in `Last-Event-ID`, so every automatic reconnect rebuilt the route's iterable from its start and lost the gap in silence — a healthy-looking stream that had simply skipped events. Half of this already worked and it was worth checking before designing anything: the request envelope has always carried every header, so a handler could already read `@header('last-event-id')`. It just always arrived empty, because we never gave the browser an id to send. `sse(data, { id, event, retry })` tags a stream item; `sseEncoder` writes the fields ahead of `data:`. An app that never calls it sees byte-identical output. `event:` and `retry:` come along because the envelope carries them for free and neither was reachable before. **green-tea stores nothing.** No buffer, no retention window, no replay. The framework carries the marker in both directions and the handler decides what the gap means, because only the source knows: a paged log re-reads from an offset, a live sensor has no past worth delivering. Framework-managed replay would need a stream identity that survives a disconnect — which does not exist, since every request builds a fresh iterable — plus a retention policy no default can get right and an in-process buffer that breaks the moment there are two instances. This commit is also the prerequisite for any of that: whatever replay might land later keys on these ids. An id with a newline is rejected, not stripped. An id is exactly the value most likely to be derived from a request — a cursor, a page token — and the SSE format is line-based, so one newline lets a caller append arbitrary fields to somebody else's stream. Stripping would resume from the wrong place invisibly, which is the failure this whole feature exists to close, so it throws where the stream can report it. `ndjsonEncoder` unwraps the payload and drops the fields: a `negotiate` route yields the same items to both encoders, and NDJSON has no frame to carry them and no resumption protocol to use them. Verified non-vacuous: reverting just the two `encode` functions fails the six framing and round-trip assertions and leaves the validation ones passing, which is the right split. Closes #46 Signed-off-by: Diego Resendez --- src/encoders.ts | 102 ++++++++++++++++++++++++++- src/index.ts | 4 +- test/sse-events.test.ts | 151 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 test/sse-events.test.ts diff --git a/src/encoders.ts b/src/encoders.ts index 9819a88..2e4d687 100644 --- a/src/encoders.ts +++ b/src/encoders.ts @@ -11,10 +11,106 @@ export interface StreamEncoder { const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); +// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw +// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped +// being recognised across them would silently degrade back to an id-less `data:` frame. +const SSE_EVENT = Symbol.for('green-tea.sse-event'); + +/** Optional SSE fields carried alongside a payload. See {@link sse}. */ +export interface SseFields { + /** + * The event's id, written as `id:`. The browser echoes the last one it saw back as the + * `Last-Event-ID` request header when `EventSource` reconnects — read it with + * `@header('last-event-id')` and resume from there. + */ + id?: string; + /** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */ + event?: string; + /** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */ + retry?: number; +} + +/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */ +export interface SseEvent extends SseFields { + readonly [SSE_EVENT]: true; + data: T; +} + +/** Type guard: true when a stream item was built by {@link sse}. */ +export function isSseEvent(item: unknown): item is SseEvent { + return typeof item === 'object' && item !== null && (item as Record)[SSE_EVENT] === true; +} + +// The SSE wire format is line-based, so a newline inside a field value ends the field — and a +// value that reaches `id:` from a request (a cursor, a page token) would let a caller append +// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped: +// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place, +// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits +// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event. +function assertFieldSafe(field: string, value: string): void { + if (!/[\r\n\0]/.test(value)) return; + + throw new Error( + `sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` + + 'one would end the field and let the rest of the value be read as further SSE fields. ' + + `Received ${JSON.stringify(value)}.`, + ); +} + +/** + * Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:` + * instead of a bare `data:` frame. + * + * The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it + * saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the + * marker in both directions and stores nothing — a source that can resume, resumes; one that + * cannot keeps streaming from now, which is the honest behaviour for a live feed. + * + * On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are + * dropped, because NDJSON has no frame to carry them and no resumption protocol to use them. + * + * @example + * ```ts + * @Sse('/feed') + * feed(@header('last-event-id') from: string) { + * return (async function* () { + * for await (const row of rows({ after: from })) yield sse(row, { id: row.seq }); + * })(); + * } + * ``` + */ +export function sse(data: T, fields: SseFields = {}): SseEvent { + if (fields.id !== undefined) assertFieldSafe('id', fields.id); + if (fields.event !== undefined) assertFieldSafe('event', fields.event); + + // Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the + // reconnection delay at the default rather than at the value the app asked for. + if (fields.retry !== undefined && !Number.isInteger(fields.retry)) { + throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`); + } + + return { [SSE_EVENT]: true, data, ...fields }; +} + +/** + * Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event. + * `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction. + */ +function sseFrame(item: unknown): string { + if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`; + let frame = ''; + + if (item.retry !== undefined) frame += `retry: ${item.retry}\n`; + if (item.event !== undefined) frame += `event: ${item.event}\n`; + if (item.id !== undefined) frame += `id: ${item.id}\n`; + + return `${frame}data: ${JSON.stringify(item.data)}\n\n`; +} + /** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */ export const sseEncoder: StreamEncoder = { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }, - encode: (item) => `data: ${JSON.stringify(item)}\n\n`, + encode: sseFrame, encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`, ping: () => ': ping\n\n', }; @@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = { /** Newline-delimited JSON encoder: one JSON object per line. */ export const ndjsonEncoder: StreamEncoder = { headers: { 'content-type': 'application/x-ndjson' }, - encode: (item) => `${JSON.stringify(item)}\n`, + // Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both + // encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it. + encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`, encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`, }; diff --git a/src/index.ts b/src/index.ts index cd6c794..347598a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -76,8 +76,8 @@ export type { Logger, LogLevel, LogFields } from './logger'; export { channel, isAsyncIterable } from './channel'; export type { Channel } from './channel'; export { Rooms } from './rooms'; -export { sseEncoder, ndjsonEncoder } from './encoders'; -export type { StreamEncoder } from './encoders'; +export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders'; +export type { StreamEncoder, SseEvent, SseFields } from './encoders'; // HTTP, security & validation export type { RequestLimits } from './http'; diff --git a/test/sse-events.test.ts b/test/sse-events.test.ts new file mode 100644 index 0000000..8b499a4 --- /dev/null +++ b/test/sse-events.test.ts @@ -0,0 +1,151 @@ +// `id:` on the wire, and the `Last-Event-ID` round-trip it exists to enable. +// +// `EventSource` reconnects on its own — that is the reason to pick SSE over a raw WebSocket. Until +// an `id:` was written the browser had nothing to send back, so every reconnect restarted the +// iterable from its beginning and lost the gap in silence. green-tea carries the marker both ways +// and stores nothing: what the gap means is the handler's call, because only the source knows +// whether it is replayable. +import 'reflect-metadata'; +import { describe, expect, it } from 'vitest'; +import { ndjsonEncoder, sse, sseEncoder } from '../src/encoders'; +import { Module, Route, Sse } from '../src/metadata'; +import { header } from '../src/params'; +import { createApp } from '../src/app'; + +const frame = (item: unknown): string => String(sseEncoder.encode(item)); + +describe('sse() framing', () => { + it('writes id: before data:', () => { + expect(frame(sse({ t: 1 }, { id: '7' }))).toBe('id: 7\ndata: {"t":1}\n\n'); + }); + + it('writes every field it was given, fields before data', () => { + expect(frame(sse({ t: 1 }, { id: '7', event: 'tick', retry: 5000 }))).toBe( + 'retry: 5000\nevent: tick\nid: 7\ndata: {"t":1}\n\n', + ); + }); + + it('leaves a plain item exactly as it was', () => { + // The whole point of the marker: an app that never calls sse() sees no change on the wire. + expect(frame({ t: 1 })).toBe('data: {"t":1}\n\n'); + }); + + it('keeps an empty id, which is how the spec resets the client s last event id', () => { + expect(frame(sse({ t: 1 }, { id: '' }))).toBe('id: \ndata: {"t":1}\n\n'); + }); + + it('cannot be talked into extra fields by a newline in the payload', () => { + // JSON.stringify escapes the newline, so the data line stays single by construction. + expect(frame({ note: 'a\nid: 99' })).toBe('data: {"note":"a\\nid: 99"}\n\n'); + }); +}); + +describe('sse() rejects a field that would break the frame', () => { + // An id is exactly the value most likely to come from a request — a cursor, a page token — so + // this is a boundary, not a formatting nicety. Stripping would resume from the wrong place + // silently, which is the bug this feature exists to close. + for (const [label, id] of [ + ['newline', 'a\nid: 99'], + ['carriage return', 'a\rid: 99'], + ['NUL', 'a\0b'], + ] as const) { + it(`throws on a ${label} in id`, () => { + expect(() => sse({ t: 1 }, { id })).toThrow(/may not contain a newline or a NUL/); + }); + } + + it('throws on a newline in event', () => { + expect(() => sse({ t: 1 }, { event: 'a\ndata: fake' })).toThrow(/'event' may not contain/); + }); + + it('throws on a fractional retry, which a browser would ignore', () => { + expect(() => sse({ t: 1 }, { retry: 1.5 })).toThrow(/whole number of milliseconds/); + }); +}); + +describe('ndjson', () => { + it('unwraps the payload and drops the SSE fields', () => { + // A `negotiate` route yields the same items to both encoders. NDJSON has no frame to carry + // id/event/retry and no resumption protocol to use them, so the client gets what it asked for. + expect(String(ndjsonEncoder.encode(sse({ t: 1 }, { id: '7' })))).toBe('{"t":1}\n'); + }); + + it('leaves a plain item alone', () => { + expect(String(ndjsonEncoder.encode({ t: 1 }))).toBe('{"t":1}\n'); + }); +}); + +describe('the Last-Event-ID round trip', () => { + const app = (): ReturnType => { + @Route('/') + class Ctl { + // Reading the header needs nothing new — the envelope has always carried it. What was + // missing was the `id:` that gives the browser something to put in it. + @Sse('/feed') feed(@header('last-event-id') from: string) { + const start = from ? Number(from) + 1 : 1; + return (async function* () { + for (let n = start; n < start + 2; n++) yield sse({ n }, { id: String(n) }); + })(); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + return createApp({ modules: [M] }); + }; + + it('serves ids, and resumes from the one the client sends back', async () => { + const feed = app(); + + const first = await (await feed.fetch(new Request('http://x/feed'))).text(); + expect(first).toBe('id: 1\ndata: {"n":1}\n\nid: 2\ndata: {"n":2}\n\n'); + + // What EventSource does by itself on reconnect, spelled out. + const resumed = await ( + await feed.fetch(new Request('http://x/feed', { headers: { 'last-event-id': '2' } })) + ).text(); + expect(resumed).toBe('id: 3\ndata: {"n":3}\n\nid: 4\ndata: {"n":4}\n\n'); + }); + + it('serves the same bytes over the Node adapter', async () => { + // A different write path — `pipeStream` to a socket rather than a web ReadableStream — so + // passing on `fetch` proves nothing about the runtime most apps deploy on. + const feed = app(); + const server = await feed.listen(0); + const { port } = server.address() as import('net').AddressInfo; + + const res = await fetch(`http://127.0.0.1:${port}/feed`, { headers: { 'last-event-id': '9' } }); + expect(res.headers.get('content-type')).toBe('text/event-stream'); + expect(await res.text()).toBe('id: 10\ndata: {"n":10}\n\nid: 11\ndata: {"n":11}\n\n'); + + await feed.close(); + }); + + it('refuses an id that would inject fields, rather than writing it', async () => { + @Route('/') + class Ctl { + @Sse('/bad') bad() { + return (async function* () { + yield sse({ t: 1 }, { id: 'cursor\ndata: injected' }); + })(); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} + const broken = createApp({ modules: [M] }); + const errors: unknown[] = []; + broken.bus.on('stream:error', (e) => errors.push(e.error)); + + // The Node adapter turns a mid-stream throw into a bus event and a trailing `error` frame. + const server = await broken.listen(0); + const { port } = server.address() as import('net').AddressInfo; + const body = await (await fetch(`http://127.0.0.1:${port}/bad`)).text(); + + // Not `toContain`: the rejection quotes the offending value, so the text appears inside the + // error payload — escaped, on one line. The claim is that no *field* was injected. + expect(body.split('\n')).not.toContain('data: injected'); + expect(body).toContain('event: error'); + expect(errors).toHaveLength(1); + + await broken.close(); + }); +}); -- 2.54.1 From 7d39aebfaba99e0e04ff7e7d54f12aed9adaebc8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:52:42 -0500 Subject: [PATCH 3/5] fix(stream): report a stream's lifecycle on every adapter, not only Node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `pipeStream` emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame. `asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and `app.fetch()` on Node — emitted nothing and called `controller.error(err)`. Both halves of that were silent. A consumer counting `stream:error` saw zero on three of the four runtimes while the streams were failing normally, and the client got a truncated body with no explanation, which from the outside is indistinguishable from a clean end of stream. The observability guide documents these three events without qualification; on three runtimes they did not exist. The error path now frames rather than breaks. Enqueue `encodeError`'s frame, then close cleanly — the Node behaviour, and the better one: an SSE consumer that received an `error` event knows what happened, where a transport-level failure looks exactly like the connection dropping. `controller.error` is kept for an encoder with no error frame to offer, because then breaking the stream is the only signal left. `stream:close` is latched. A `cancel` can land after the body already ended, and the three exits — done, error, cancel — must not each emit their own. The test drives both adapters from one route table rather than asserting them in separate blocks, since a table that describes one and then the other is how the two drifted in the first place. Verified non-vacuous: reverting `src/http/web.ts` fails all four fetch rows and leaves the three Node ones green, which is the split that says the test is measuring the adapter and not the framework. The `sse()` injection test from the previous commit went back to `app.fetch`. It had been written against `listen()` only because the fetch path swallowed the error — that was a workaround for this bug, and it is no longer needed. Closes #83 Signed-off-by: Diego Resendez --- src/http/web.ts | 58 +++++++++++-- test/sse-events.test.ts | 7 +- test/stream-lifecycle-parity.test.ts | 119 +++++++++++++++++++++++++++ 3 files changed, 169 insertions(+), 15 deletions(-) create mode 100644 test/stream-lifecycle-parity.test.ts diff --git a/src/http/web.ts b/src/http/web.ts index ab09644..6d3fbe0 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,4 +1,5 @@ import type { StreamEncoder } from '../encoders'; +import type { Bus } from '../bus'; import { createRequestGate } from './request-gate'; import { handle, @@ -15,28 +16,66 @@ import { HttpError } from '../signals'; import { renderError, type ErrorRequest } from '../transformers'; import type { RouteDef, HttpOptions } from './types'; -/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */ -export function asReadableStream(source: AsyncIterable, encoder: StreamEncoder): ReadableStream { +/** + * Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream + * cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the + * lifecycle of a stream must not depend on which adapter is serving it. + */ +export function asReadableStream( + source: AsyncIterable, + encoder: StreamEncoder, + bus?: Bus, + name = '', +): ReadableStream { const iterator = source[Symbol.asyncIterator](); const te = new TextEncoder(); + 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. + let closed = false; + + const close = (): void => { + if (closed) return; + closed = true; + bus?.emit('stream:close', { name }); + }; + return new ReadableStream({ + start() { + bus?.emit('stream:open', { name }); + }, async pull(controller) { try { const { value, done } = await iterator.next(); if (done) { + close(); controller.close(); return; } - const encoded = encoder.encode(value); - const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded; - controller.enqueue(bytes); + controller.enqueue(frame(encoder.encode(value))); } catch (err) { - controller.error(err); + bus?.emit('stream:error', { name, error: err }); + const errorFrame = encoder.encodeError(err); + close(); + + // Framed and closed cleanly, which is what the Node adapter does and the better answer for + // the client: an SSE consumer that received an `error` event knows what happened, where a + // transport-level failure is indistinguishable from the connection simply dropping. + // `controller.error` is kept for the encoder that has no error frame to offer, because + // then breaking the stream is the only signal left. + if (errorFrame === null) { + controller.error(err); + return; + } + + controller.enqueue(frame(errorFrame)); + controller.close(); } }, async cancel() { + close(); await iterator.return?.(); }, }); @@ -115,11 +154,12 @@ export function toBodyInit(body: string | Buffer): ResponseBody { } /** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ -function outcomeToResponse(result: HandleResult): Response { +function outcomeToResponse(result: HandleResult, bus?: Bus): Response { const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record; if (result.outcome.kind === 'stream') { - return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); + const body = asReadableStream(result.outcome.stream, result.outcome.encoder, bus, result.outcome.route); + return new Response(body, { headers }); } const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body); @@ -222,6 +262,6 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { }); } - return outcomeToResponse(result); + return outcomeToResponse(result, opts?.bus); }; } diff --git a/test/sse-events.test.ts b/test/sse-events.test.ts index 8b499a4..d52ba6d 100644 --- a/test/sse-events.test.ts +++ b/test/sse-events.test.ts @@ -135,17 +135,12 @@ describe('the Last-Event-ID round trip', () => { const errors: unknown[] = []; broken.bus.on('stream:error', (e) => errors.push(e.error)); - // The Node adapter turns a mid-stream throw into a bus event and a trailing `error` frame. - const server = await broken.listen(0); - const { port } = server.address() as import('net').AddressInfo; - const body = await (await fetch(`http://127.0.0.1:${port}/bad`)).text(); + const body = await (await broken.fetch(new Request('http://x/bad'))).text(); // Not `toContain`: the rejection quotes the offending value, so the text appears inside the // error payload — escaped, on one line. The claim is that no *field* was injected. expect(body.split('\n')).not.toContain('data: injected'); expect(body).toContain('event: error'); expect(errors).toHaveLength(1); - - await broken.close(); }); }); diff --git a/test/stream-lifecycle-parity.test.ts b/test/stream-lifecycle-parity.test.ts new file mode 100644 index 0000000..d32dc09 --- /dev/null +++ b/test/stream-lifecycle-parity.test.ts @@ -0,0 +1,119 @@ +// A stream's lifecycle must not depend on which adapter is serving it. +// +// `pipeStream` (Node) emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame. +// `asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and `app.fetch()` +// on Node — emitted nothing and called `controller.error`. A consumer counting `stream:error` saw +// zero on three of the four runtimes, and the client got a truncated body indistinguishable from a +// clean end. Both halves are silent, which is what made it worth its own issue. +// +// Both adapters are driven from the same route table here on purpose: a table asserting one and +// then the other is how the two drift again. +import 'reflect-metadata'; +import { describe, expect, it } from 'vitest'; +import { Bus } from '../src/bus'; +import { createHttpServer } from '../src/http'; +import { buildFetch } from '../src/http/web'; +import type { RouteDef } from '../src/http/types'; + +const events = (bus: Bus): string[] => { + const seen: string[] = []; + for (const name of ['stream:open', 'stream:close', 'stream:error'] as const) + bus.on(name, () => seen.push(name)); + return seen; +}; + +const route = (handler: () => AsyncIterable): RouteDef[] => [ + { method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: handler() }) }, +]; + +const clean = route(async function* () { + yield { t: 1 }; +}); +const broken = route(async function* () { + yield { t: 1 }; + throw new Error('source died'); +}); + +/** Serves one request through the Node adapter and returns the body it wrote. */ +async function overNode(routes: RouteDef[], bus: Bus): Promise { + const server = createHttpServer(routes, [], bus, undefined, {}); + await new Promise((r) => server.listen(0, r)); + const { port } = server.address() as { port: number }; + + try { + return await (await fetch(`http://127.0.0.1:${port}/feed`)).text(); + } finally { + server.close(); + } +} + +/** Serves one request through the Fetch adapter and returns the body it wrote. */ +async function overFetch(routes: RouteDef[], bus: Bus): Promise { + return await (await buildFetch(routes, { bus })(new Request('http://x/feed'))).text(); +} + +const ADAPTERS = [ + { name: 'node', serve: overNode }, + { name: 'fetch', serve: overFetch }, +] as const; + +describe('stream lifecycle events, on every adapter', () => { + for (const adapter of ADAPTERS) { + it(`${adapter.name}: opens and closes a stream that ends normally`, async () => { + const bus = new Bus(); + const seen = events(bus); + + expect(await adapter.serve(clean, bus)).toBe('data: {"t":1}\n\n'); + expect(seen).toEqual(['stream:open', 'stream:close']); + }); + + it(`${adapter.name}: reports a source that throws, and frames it for the client`, async () => { + const bus = new Bus(); + const seen = events(bus); + const errors: unknown[] = []; + bus.on('stream:error', (e) => errors.push(e.error)); + + const body = await adapter.serve(broken, bus); + + // Framed rather than dropped: an SSE consumer can see this, where a truncated body is + // indistinguishable from the connection dropping. + expect(body).toContain('data: {"t":1}\n\n'); + expect(body).toContain('event: error'); + expect(body).toContain('source died'); + + expect(seen).toEqual(['stream:open', 'stream:error', 'stream:close']); + expect((errors[0] as Error).message).toBe('source died'); + }); + + it(`${adapter.name}: names the route pattern, not the path that arrived`, async () => { + const bus = new Bus(); + const names: string[] = []; + bus.on('stream:open', (e) => names.push(e.name)); + + await adapter.serve(clean, bus); + expect(names).toEqual(['/feed']); + }); + } + + 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. + const bus = new Bus(); + const seen = events(bus); + let released!: () => void; + const blocked = new Promise((r) => (released = r)); + + const endless = route(async function* () { + yield { t: 1 }; + await blocked; + }); + + const res = await buildFetch(endless, { bus })(new Request('http://x/feed')); + const reader = res.body!.getReader(); + await reader.read(); + await reader.cancel(); + released(); + + expect(seen).toEqual(['stream:open', 'stream:close']); + }); +}); -- 2.54.1 From 86a0d9c91b8a273dd6e1794bb15788d4c1828f50 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:57:39 -0500 Subject: [PATCH 4/5] fix(observability): correlate stream events with the request that opened them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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 --- src/bus.ts | 5 ++++ src/http/server.ts | 10 ++++++- src/http/stream.ts | 14 +++++++--- src/http/web.ts | 24 +++++++++++----- src/http/ws-core.ts | 12 ++++++-- test/stream-lifecycle-parity.test.ts | 42 ++++++++++++++++++++++++++++ test/ws-core.test.ts | 42 ++++++++++++++++++++++++++++ 7 files changed, 134 insertions(+), 15 deletions(-) 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'); + }); +}); -- 2.54.1 From a84960a46ae3bec062cd83bb41b0c4cbb3dee1c0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:59:40 -0500 Subject: [PATCH 5/5] docs(changelog): record the tier-3 work in Unreleased MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Concurrent provider boot, `sse()` and the `id:` it writes, and the stream events that three of the four runtimes never emitted. #83 and #84 share one entry. They are two defects but one symptom — the stream events were not usable — and a reader looking for "can I build a stream gauge on this" is served better by one entry than by two bullets that both open with `stream:`. The boot entry carries its two consequences rather than only its number, because "616ms becomes 210ms" is not the part that can surprise someone: a required provider's independent siblings now start, and `boot:provider:start` stops alternating with `:ok`. Heading still `[Unreleased]`. The version and the date belong to the cut. Signed-off-by: Diego Resendez --- CHANGELOG.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9acbf26..d453236 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,25 @@ npm treats versions as semver and semver forbids leading zeros. to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request and would add a listener each time. +- **`@Sse` can emit an `id:`, so an `EventSource` reconnect has something to resume from.** + `sse(data, { id, event, retry })` tags a stream item and the encoder writes the fields ahead of + `data:`; an app that never calls it produces byte-identical output. Until now the encoder wrote one + field, so the browser had nothing to put in `Last-Event-ID` and every automatic reconnect — the + reason to choose SSE over a raw WebSocket — rebuilt the route's iterable from its start and lost + the gap in silence. The other half already worked: the request envelope has always carried every + header, so a handler could already read `@header('last-event-id')`; it simply always arrived empty. + `event:` and `retry:` come along because the same envelope carries them, and neither was reachable + before. + + **green-tea stores nothing** — no buffer, no retention window, no replay. It carries the marker in + both directions and the handler decides what the gap means, because only the source knows: a paged + log re-reads from an offset, a live sensor has no past worth delivering. An `id` containing a + newline is rejected rather than stripped, since the SSE format is line-based and an id is exactly + the value most likely to be built from a request — a cursor, a page token — so one newline would + let a caller append fields to somebody else's stream. On an `ndjson` or `negotiate`-to-ndjson route + the payload is unwrapped and the fields dropped. New exports: `sse`, `isSseEvent`, `SseEvent`, + `SseFields`. + ### Changed - **A request's security and CORS headers are computed once.** They were derived twice per request @@ -112,6 +131,23 @@ npm treats versions as semver and semver forbids leading zeros. for a feature that was off. Unchanged where a budget *is* configured: the listener is what releases a slot when a client disconnects mid-handler. +- **Independent providers boot concurrently.** Boot walked the topological order one node at a time, + so an application paid the *sum* of its providers' latencies rather than its longest chain — three + providers with no edges between them and 200ms of work each took 616ms for a graph whose critical + path is 200ms; it now takes 210ms. The graph already proved which nodes cannot constrain each + other, and flattening the sort was the only thing throwing that away: the ordered list is grouped + back into dependency levels and each level runs together, with level *N* fully registered and + warmed before *N+1* starts. Nothing the graph derives changes, and this is the second thing users + get for declaring `needs`/`provides` rather than ordering calls by hand — pruning was the first, + and neither is available to a middleware chain, where nothing declares what is independent. + + Two consequences worth knowing. Teardown still runs in the exact reverse of boot: registration + follows level order rather than completion order, which is what keeps that a guarantee instead of + a race. And a required provider that fails no longer prevents its independent siblings from + starting — they are already in flight — so whatever they opened is registered for teardown before + the boot is aborted. On the bus, `boot:provider:start` no longer strictly alternates with `:ok`; a + level emits its starts together and then its results. + ### Fixed - **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on @@ -150,6 +186,26 @@ npm treats versions as semver and semver forbids leading zeros. which is exactly what the option overrides — so the original error still gets its response, and the renderer's own failure is logged separately, naming both. +- **A stream's lifecycle is reported on every runtime, and joins back to its request.** `stream:open`, + `stream:close` and `stream:error` were emitted only by the Node adapter. Every Fetch runtime — Deno, + Bun, workerd, and `app.fetch()` on Node — emitted none of them and broke the response with a + transport error instead of writing the encoder's error frame. Both halves were silent: a consumer + counting `stream:error` saw zero on three of the four runtimes while streams were failing normally, + and the client got a truncated body indistinguishable from a clean end of stream. The Fetch path now + emits all three and frames the error before closing cleanly, which is what the Node adapter always + did and the better answer for the client — an SSE consumer that received an `error` event knows what + happened, where a dropped connection tells it nothing. + + All three events now also carry the opening request's `requestId` and `traceId`, plus a bounded + `route`. `src/http/core.ts` had documented them as carrying the id since the stream landed; they + never did. The split they exist for is deliberate — 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 hour-long connections stay out of the same latency distribution as 2ms replies — but it only + works if the two can be *joined*, and without the id an exporter could not say which request opened + the connection still holding a slot. A WebSocket upgrade correlates itself: it is an HTTP request + with headers like any other, so it adopts a gateway's `x-request-id` rather than opening a second + identity, and carries `transport: 'ws'`. + ## [26.8.0-beta.1] - 2026-08-19 ### Added -- 2.54.1