Files
core/src/http/stream.ts
T
chrnx d56eeafcd8 refactor: close type holes on the transport and error axes
- OpenApiRoute.transport was typed `string`, so the compiler could not check the
  transport branching at all. Type it Transport and key the documented 200 off a
  Record, so a new transport fails the build instead of silently going undocumented.
- pickEncoder fell through to ndjson for unknown transports; make the mapping
  exhaustive so a new transport cannot inherit the wrong wire format by accident.
- HttpError carries optional headers, removing the instanceof Redirect special case
  that coupled the error renderer to one subclass. Custom errors needing headers
  (retry-after, etag) no longer require touching transformers.
- Drop the module-global connSeq in mesh/link: `pending` is already per-connection,
  so a per-link counter suffices and connection ids stop depending on test order.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00

89 lines
2.9 KiB
TypeScript

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';
const PING_MS = 15_000;
/**
* Stream encoder per transport, or `null` for transports that never produce an HTTP stream.
* A new transport must add a row — the compiler fails until it does, so it can't silently
* inherit ndjson framing.
*/
const STREAM_ENCODERS: Record<Transport, ((accept: string) => StreamEncoder) | null> = {
buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here
ws: null, // not an HTTP response; ws routes are served via upgrade, not handle()
sse: () => sseEncoder,
ndjson: () => ndjsonEncoder,
negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder),
};
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */
export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
const pick = STREAM_ENCODERS[transport];
if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
return pick(accept);
}
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
export async function pipeStream(
res: http.ServerResponse,
stream: AsyncIterable<unknown>,
encoder: StreamEncoder,
bus?: Bus,
name = '',
streams?: Set<() => void>,
): Promise<void> {
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 });
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
if (encoder.ping) {
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
ping.unref?.();
}
const stop = () => {
if (ping) clearInterval(ping);
void Promise.resolve(iterator.return?.()).catch(() => {});
};
res.on('close', stop);
const closer = () => {
try {
res.destroy();
} catch {
/* */
}
};
streams?.add(closer);
const onClose = once(res, 'close');
try {
while (true) {
const { value, done } = await iterator.next();
if (done) break;
if (!res.write(encoder.encode(value))) {
await Promise.race([once(res, 'drain'), onClose]);
if (res.destroyed) break; // let finally clean up
}
}
} catch (err) {
bus?.emit('stream:error', { name, 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 });
}
}