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 { 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<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 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>({
|
||||
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<string, string>;
|
||||
|
||||
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);
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user