fix(stream): report a stream's lifecycle on every adapter, not only Node
`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 <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+169
-15
No files matched your search
+49
-9
@@ -1,4 +1,5 @@
|
|||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
|
import type { Bus } from '../bus';
|
||||||
import { createRequestGate } from './request-gate';
|
import { createRequestGate } from './request-gate';
|
||||||
import {
|
import {
|
||||||
handle,
|
handle,
|
||||||
@@ -15,28 +16,66 @@ import { HttpError } from '../signals';
|
|||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
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<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
* 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<unknown>,
|
||||||
|
encoder: StreamEncoder,
|
||||||
|
bus?: Bus,
|
||||||
|
name = '',
|
||||||
|
): ReadableStream<Uint8Array> {
|
||||||
const iterator = source[Symbol.asyncIterator]();
|
const iterator = source[Symbol.asyncIterator]();
|
||||||
const te = new TextEncoder();
|
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<Uint8Array>({
|
return new ReadableStream<Uint8Array>({
|
||||||
|
start() {
|
||||||
|
bus?.emit('stream:open', { name });
|
||||||
|
},
|
||||||
async pull(controller) {
|
async pull(controller) {
|
||||||
try {
|
try {
|
||||||
const { value, done } = await iterator.next();
|
const { value, done } = await iterator.next();
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
|
close();
|
||||||
controller.close();
|
controller.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const encoded = encoder.encode(value);
|
controller.enqueue(frame(encoder.encode(value)));
|
||||||
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
|
||||||
controller.enqueue(bytes);
|
|
||||||
} catch (err) {
|
} 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() {
|
async cancel() {
|
||||||
|
close();
|
||||||
await iterator.return?.();
|
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. */
|
/** 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<string, string>;
|
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||||
|
|
||||||
if (result.outcome.kind === 'stream') {
|
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);
|
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);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -135,17 +135,12 @@ describe('the Last-Event-ID round trip', () => {
|
|||||||
const errors: unknown[] = [];
|
const errors: unknown[] = [];
|
||||||
broken.bus.on('stream:error', (e) => errors.push(e.error));
|
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 body = await (await broken.fetch(new Request('http://x/bad'))).text();
|
||||||
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
|
// 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.
|
// error payload — escaped, on one line. The claim is that no *field* was injected.
|
||||||
expect(body.split('\n')).not.toContain('data: injected');
|
expect(body.split('\n')).not.toContain('data: injected');
|
||||||
expect(body).toContain('event: error');
|
expect(body).toContain('event: error');
|
||||||
expect(errors).toHaveLength(1);
|
expect(errors).toHaveLength(1);
|
||||||
|
|
||||||
await broken.close();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -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<unknown>): 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<string> {
|
||||||
|
const server = createHttpServer(routes, [], bus, undefined, {});
|
||||||
|
await new Promise<void>((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<string> {
|
||||||
|
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<void>((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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user