feat(http): response compression with gzip and br (CARD-16, #112)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
CI / runtimes (edge) (pull_request) Successful in 19s

Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 01:12:48 -05:00
1 parent c22c37e0b3
commit 3296189093
21 files changed
+1536 -50

No files matched your search

+33
View File
@@ -9,6 +9,7 @@ import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } fro
import type { HttpOptions } from '../http';
import { trustedProxyClient } from '../http/peer';
import { answerFetchProbe, buildFetch } from '../http/web';
import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression';
import {
boundInbound,
validateWsLimits,
@@ -180,6 +181,32 @@ export function createApp(opts: {
* Anything but a boolean throws.
*/
etag?: boolean;
/**
* Response compression (default: off). `true`, or `{ threshold?, encodings? }`: `threshold` is
* the smallest buffered body worth encoding (default `1024` bytes; streams ignore it) and
* `encodings` the codings core may produce, in preference order (default `['br', 'gzip']`).
*
* Negotiated on `Accept-Encoding` (q-values, `identity`, `*`, `q=0`). Text, JSON, JavaScript,
* ndjson, SVG, XML and wasm are compressed; a response that already has `Content-Encoding` or
* `Content-Range`, has no `Content-Type`, or says `Cache-Control: no-transform` is left alone.
* `Vary: Accept-Encoding` is added wherever the choice depended on the request, including every
* `304`. SSE and ndjson streams are compressed too, flushed after every event.
*
* Per runtime:
* - **Node, Bun:** `node:zlib`, async (off the event loop), br at quality 4.
* - **Deno:** the same code, but Deno runs `node:zlib`'s async API on the main thread, so core
* compression costs event-loop time there — about 4× slower than Node for a 51 KB gzip under
* load. Deno's own `automaticCompression` gzip is about 3× faster than core's, but slower for br,
* and it weakens strong ETags on what it encodes.
* - **Edge (Cloudflare Workers):** core never encodes; it sets `Vary` and Cloudflare chooses and
* applies the encoding. Detected through `edgeHandler`, or at `createApp` from
* `navigator.userAgent`. A bare `export default { fetch: app.fetch }` on a Worker with a compat
* date before 2022-03-21 (no `navigator`) is detected only if `node:zlib` fails to load there.
*
* ETags (`etag: true`) are taken on the identity body and are weak, so one tag covers every coding.
* An invalid `threshold` or `encodings` throws.
*/
compression?: boolean | CompressionOptions;
/**
* How long `close()` gives in-flight work before forcing remaining connections shut, in ms
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
@@ -367,7 +394,9 @@ export function createApp(opts: {
const staticConfig = normalizeStatic(opts.static);
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
const compression = resolveCompression(opts.compression);
const fetchOpts: HttpOptions = {
compression,
bus,
logger,
limits: opts.limits,
@@ -398,6 +427,7 @@ export function createApp(opts: {
// A getter, not an array: mesh membership can change the table after this server starts.
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
compression,
bus,
logger,
limits: opts.limits,
@@ -481,6 +511,9 @@ export function createApp(opts: {
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
[HEALTH_DRAIN]: drain,
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
[MARK_EDGE]: edgeMarker(compression),
});
}
+6
View File
@@ -1,6 +1,7 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { setProxyClient } from './http/peer';
import { MARK_EDGE } from './http/compression';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
@@ -23,10 +24,15 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*
* **`compression` never encodes here.** Cloudflare compresses in front of the Worker, so core sets
* only `Vary: Accept-Encoding`; wrapping the app in `edgeHandler` marks it as edge explicitly.
*/
export function edgeHandler(
app: App,
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
return (request, _env, ctx) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
+414
View File
@@ -0,0 +1,414 @@
// src/http/compression.ts — response compression (CARD-16, #112, D13 strategy B).
//
// The per-runtime contract, as measured in SPIKE-COMPRESSION.md and SPIKE-COMPRESSION-B.md:
// - Node, Deno, Bun: `node:zlib` only, loaded lazily. Buffered bodies always go through the async
// API: at 32 connections the sync API stalled the event loop for 9–13 ms even below 64 KiB, and
// async gave 4× (Node) to 8× (Bun) the throughput. Streams go through createGzip /
// createBrotliCompress, flushed after every frame, error frame and ping, so each event is
// decodable the moment it arrives. br quality is fixed at 4 (zlib's default 11 stalls 6–33 ms).
// - Deno runs `node:zlib`'s async API on the main thread (2.9.7), so there core compression is
// CPU work on the event loop. That is documented, not worked around: no Deno branch here.
// - Edge (workerd): core never encodes. Cloudflare compresses in front of the Worker, an encoded
// body plus `Content-Encoding` is encoded a second time, and a bundled Worker cannot even
// `require('node:zlib')`. Core sets `Vary` and nothing else.
// - No `CompressionStream` anywhere: it cannot flush, so it would hold SSE frames back.
import { mergeVary } from '../security';
import { nodeRequire } from '../node-require';
import { findHeader } from './conditional';
import type { NeutralOutcome } from './core';
/** A content-coding core can produce. */
export type Encoding = 'br' | 'gzip';
/** The public `createApp({ compression })` object form. */
export interface CompressionOptions {
/** Smallest buffered body, in bytes, worth encoding. Default `1024`. Streams ignore it. */
threshold?: number;
/** Encodings core may produce, in server preference order. Default `['br', 'gzip']`. */
encodings?: Array<'br' | 'gzip'>;
}
/** Resolved, validated configuration. `encode: false` is the edge mode: `Vary` only. */
export interface CompressionConfig {
threshold: number;
encodings: Encoding[];
encode: boolean;
}
/** Fixed brotli quality. See the module comment. */
export const BR_QUALITY = 4;
const KNOWN: readonly Encoding[] = ['br', 'gzip'];
/**
* Marks an app as running on the edge, so core never encodes for it. `edgeHandler` calls it: that
* covers the official adapter whatever the Worker's compat flags, including the case detection
* cannot see (an old compat date without `navigator`, unbundled so `node:zlib` loads). A property
* on the app rather than on the public `App` type, and `Symbol.for` because each tsup entry carries
* its own copy of this module — the same arrangement as `WS_MAX_MESSAGE_BYTES`.
*/
export const MARK_EDGE: unique symbol = Symbol.for('green-tea.mark-edge');
/** The `[MARK_EDGE]` hook for an app: turns encoding off for good. A no-op when compression is off. */
export function edgeMarker(cfg: CompressionConfig | undefined): () => void {
return () => {
if (cfg) cfg.encode = false;
};
}
/**
* Whether this process is a Cloudflare Workers isolate. workerd sets `navigator.userAgent` to
* exactly this string under the `global_navigator` compat flag, on by default since 2022-03-21.
* Detected in `createApp` so `export default { fetch: app.fetch }`, which never passes through
* `edgeHandler`, is covered too.
*/
export function isWorkerd(): boolean {
const nav = (globalThis as { navigator?: { userAgent?: string } }).navigator;
return nav?.userAgent === 'Cloudflare-Workers';
}
interface ZlibStream {
write(chunk: Uint8Array | string): boolean;
flush(kind: number, cb: () => void): void;
end(): void;
destroy(): void;
on(event: string, fn: (...args: never[]) => void): this;
once(event: string, fn: (...args: never[]) => void): this;
pipe<T>(dest: T): T;
}
interface Zlib {
gzip(b: Uint8Array, cb: (e: Error | null, r: Buffer) => void): void;
brotliCompress(b: Uint8Array, o: object, cb: (e: Error | null, r: Buffer) => void): void;
createGzip(): ZlibStream;
createBrotliCompress(o: object): ZlibStream;
constants: Record<string, number>;
}
let zlibModule: Zlib | undefined;
/** Lazy, so the edge bundle never evaluates `node:zlib`. */
const zlib = (): Zlib => (zlibModule ??= nodeRequire<Zlib>('node:zlib'));
/**
* Encode only off workerd, and only where `node:zlib` actually loads. In a bundled Worker
* `nodeRequire` throws, and without this probe every compressible edge response was a 500
* (SPIKE-COMPRESSION-B §6.1). Evaluated once, at `createApp`.
*/
function canEncode(): boolean {
if (isWorkerd()) return false;
try {
return typeof zlib().gzip === 'function';
} catch {
return false;
}
}
/** Validates `createApp({ compression })`. Returns `undefined` when compression is off. */
export function resolveCompression(
option: boolean | CompressionOptions | undefined,
encode: () => boolean = canEncode,
): CompressionConfig | undefined {
if (option === undefined || option === false) return undefined;
if (option !== true && (typeof option !== 'object' || option === null))
throw new TypeError('createApp({ compression }): expected a boolean or { threshold?, encodings? }');
const opts: CompressionOptions = option === true ? {} : option;
const threshold = opts.threshold ?? 1024;
if (!Number.isInteger(threshold) || threshold < 0)
throw new TypeError(
`createApp({ compression }): threshold must be a non-negative integer, got ${String(threshold)}`,
);
const encodings = opts.encodings ?? ['br', 'gzip'];
if (!Array.isArray(encodings) || encodings.length === 0)
throw new TypeError('createApp({ compression }): encodings must be a non-empty array');
for (const e of encodings)
if (!KNOWN.includes(e))
throw new TypeError(`createApp({ compression }): unknown encoding '${String(e)}' — expected 'br' or 'gzip'`);
return { threshold, encodings: [...new Set(encodings)], encode: encode() };
}
/**
* The qvalue grammar of RFC 9110 §12.4.2: `0` with up to three decimals, or `1` with up to three
* zeros. `Number()` alone would admit `2`, `1e0` or `-1`, and a `q=2` would outrank the server's
* preference.
*/
const QVALUE = /^(0(\.\d{0,3})?|1(\.0{0,3})?)$/;
/** `q` of one `Accept-Encoding` member, or 1 when absent. A malformed or out-of-range `q` excludes it. */
function weightOf(params: string[]): number {
for (const param of params) {
const eq = param.indexOf('=');
if (eq !== -1 && param.slice(0, eq).trim().toLowerCase() === 'q') {
const raw = param.slice(eq + 1).trim();
return QVALUE.test(raw) ? Number(raw) : 0;
}
}
return 1;
}
/**
* `Accept-Encoding` negotiation (RFC 9110 §12.5.3). Returns the encoding to use, or `undefined` for
* identity. Highest `q` wins; a tie goes to server preference, the order of `encodings`. `*` covers
* every encoding not named explicitly, and `q=0` excludes. An absent header means identity:
* §12.5.3 allows any coding then, but an absent header is overwhelmingly a client that would not
* decode one.
*/
export function negotiate(accept: string | undefined, encodings: Encoding[]): Encoding | undefined {
if (!accept) return undefined;
const q = new Map<string, number>();
for (const part of accept.split(',')) {
const [rawName, ...params] = part.split(';');
const name = rawName.trim().toLowerCase();
if (name) q.set(name, weightOf(params));
}
let best: Encoding | undefined;
let bestQ = 0;
for (const e of encodings) {
const weight = q.get(e) ?? q.get('*') ?? 0;
if (weight > bestQ) {
best = e;
bestQ = weight;
}
}
return best;
}
const COMPRESSIBLE =
/^\s*(text\/|application\/(json|javascript|xml|wasm|x-ndjson)\s*(;|$)|image\/svg\+xml\s*(;|$)|application\/[^;\s]+\+(json|xml)\s*(;|$))/i;
type Headers = Record<string, string | string[]>;
/** A header's value as one string, case-insensitively, or `undefined`. */
function read(headers: Headers, name: string): string | undefined {
const key = findHeader(headers, name);
if (key === undefined) return undefined;
const value = headers[key];
return Array.isArray(value) ? value.join(', ') : value;
}
/**
* Whether the response's representation could vary by `Accept-Encoding` at all. When it cannot —
* already encoded, a range, no or an incompressible type, `no-transform` — core neither encodes
* nor adds `Vary`. Request-side reasons (HEAD, the client's header) do not appear here: those
* responses still get `Vary`, so a shared cache keys them correctly.
*/
function eligible(headers: Headers): boolean {
if (read(headers, 'content-encoding') !== undefined || read(headers, 'content-range') !== undefined) return false;
const type = read(headers, 'content-type');
if (!type || !COMPRESSIBLE.test(type)) return false;
return !/(^|[\s,])no-transform\s*(,|$)/i.test(read(headers, 'cache-control') ?? '');
}
function withVary(headers: Headers): Headers {
const key = findHeader(headers, 'vary');
const out = { ...headers };
let existing: string | undefined;
if (key !== undefined) {
const value = out[key];
existing = Array.isArray(value) ? value.join(', ') : value;
delete out[key];
}
out.vary = mergeVary(existing, 'Accept-Encoding');
return out;
}
/** Headers for an encoded body: `Vary` merged, `Content-Encoding` set, `Content-Length` dropped (it described the identity body). */
function encodedHeaders(headers: Headers, encoding: Encoding): Headers {
const out = withVary(headers);
const length = findHeader(out, 'content-length');
if (length !== undefined) delete out[length];
out['content-encoding'] = encoding;
return out;
}
const brParams = (size?: number) => {
const c = zlib().constants;
const params: Record<number, number> = { [c.BROTLI_PARAM_QUALITY]: BR_QUALITY };
if (size !== undefined) params[c.BROTLI_PARAM_SIZE_HINT] = size;
return { params };
};
/** Encodes one buffered body with the async zlib API — never the sync one (see the module comment). */
function encodeBody(body: Uint8Array, encoding: Encoding): Promise<Buffer> {
const z = zlib();
return new Promise((resolve, reject) => {
const done = (err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out));
if (encoding === 'br') z.brotliCompress(body, brParams(body.byteLength), done);
else z.gzip(body, done);
});
}
/** A fresh compressing stream plus the flush mode that makes it emit everything written so far. */
function createEncoderStream(encoding: Encoding): { stream: ZlibStream; flushKind: number } {
const z = zlib();
if (encoding === 'br')
return { stream: z.createBrotliCompress(brParams()), flushKind: z.constants.BROTLI_OPERATION_FLUSH };
return { stream: z.createGzip(), flushKind: z.constants.Z_SYNC_FLUSH };
}
/** The request facts compression needs. */
export interface CompressionRequest {
method: string;
headers: Record<string, string | string[] | undefined>;
}
const acceptOf = (req: CompressionRequest): string | undefined => {
const v = req.headers['accept-encoding'];
return Array.isArray(v) ? v.join(', ') : v;
};
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
type Streamed = Extract<NeutralOutcome, { kind: 'stream' }>;
/** Decides a buffered outcome. Returns it untouched, with `Vary` only, or encoded. */
function compressBuffered(
cfg: CompressionConfig,
req: CompressionRequest,
outcome: Buffered,
): Buffered | Promise<Buffered> {
const { status, headers, body } = outcome;
// A 304 carries `Vary` whatever else it has: it usually has no `Content-Type`, so the
// eligibility test would drop it, and a cache needs the same key it stored the 200 under.
if (status === 304) return { ...outcome, headers: withVary(headers) };
if (status === 204 || !eligible(headers)) return outcome;
const vary = { ...outcome, headers: withVary(headers) };
if (status < 200 || req.method === 'HEAD' || !cfg.encode) return vary;
const bytes = typeof body === 'string' ? Buffer.from(body) : body;
if (bytes.byteLength < cfg.threshold) return vary;
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return vary;
return encodeBody(bytes, encoding).then((encoded) => ({
...outcome,
headers: encodedHeaders(headers, encoding),
body: encoded,
}));
}
/** Decides a stream: its headers, and the encoding the adapter applies frame by frame. `threshold` does not apply. */
function compressStream(cfg: CompressionConfig, req: CompressionRequest, outcome: Streamed): Streamed {
if (!eligible(outcome.headers)) return outcome;
if (req.method === 'HEAD' || !cfg.encode) return { ...outcome, headers: withVary(outcome.headers) };
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return { ...outcome, headers: withVary(outcome.headers) };
return { ...outcome, headers: encodedHeaders(outcome.headers, encoding), encoding };
}
/**
* Applies `createApp({ compression })` to an outcome, after `handle()` and before the adapter
* writes it. One function for both adapters, so Node and the fetch runtimes cannot diverge. The
* ETag (CARD-15) was taken in `dispatch` on the identity body and is not touched: it is weak, so
* one tag describes every coding.
*/
export function compressOutcome(
cfg: CompressionConfig | undefined,
req: CompressionRequest,
outcome: NeutralOutcome,
): NeutralOutcome | Promise<NeutralOutcome> {
if (!cfg) return outcome;
return outcome.kind === 'stream' ? compressStream(cfg, req, outcome) : compressBuffered(cfg, req, outcome);
}
/**
* Wraps a web byte stream so every chunk is compressed and flushed on its own: one SSE frame in,
* one decodable compressed chunk out. This is the thing `CompressionStream` cannot do.
*/
export function compressWebStream(source: ReadableStream<Uint8Array>, encoding: Encoding): ReadableStream<Uint8Array> {
const { stream: z, flushKind } = createEncoderStream(encoding);
const reader = source.getReader();
let pending: Uint8Array[] = [];
let failure: unknown;
z.on('data', (c: Uint8Array) => pending.push(c));
// Without a listener a zlib error is an uncaught exception that takes the process down.
z.on('error', (err: unknown) => (failure ??= err));
const take = (): Uint8Array | undefined => {
if (pending.length === 0) return undefined;
const chunk = pending.length === 1 ? pending[0] : Buffer.concat(pending);
pending = [];
return new Uint8Array(chunk.buffer as ArrayBuffer, chunk.byteOffset, chunk.byteLength);
};
return new ReadableStream<Uint8Array>({
async pull(controller) {
const { value, done } = await reader.read();
if (done) {
await new Promise<void>((resolve) => {
z.once('end', resolve);
z.once('error', () => resolve());
z.end();
});
} else {
z.write(value);
await new Promise<void>((resolve) => z.flush(flushKind, resolve));
}
if (failure !== undefined) {
controller.error(failure);
await reader.cancel(failure).catch(() => {});
return;
}
const out = take();
if (out) controller.enqueue(out);
if (done) controller.close();
},
async cancel(reason) {
z.destroy();
await reader.cancel(reason);
},
});
}
/** Where `pipeStream` writes frames: `res` itself, or a flushing compressor piped into it. */
export interface FrameSink {
write(chunk: string | Buffer): boolean;
/** The emitter whose `drain` ends a backpressure wait. */
drains: NodeJS.EventEmitter;
end(): void;
destroy(): void;
}
/** The Node stream path's sink. Without an encoding it is `res`, unchanged. */
export function frameSink(res: NodeJS.WritableStream & { destroy(): void }, encoding?: Encoding): FrameSink {
if (!encoding) return { write: (c) => res.write(c), drains: res, end: () => void res.end(), destroy: () => {} };
const { stream: zs, flushKind } = createEncoderStream(encoding);
zs.on('error', () => res.destroy());
zs.pipe(res);
return {
write(chunk) {
const ok = zs.write(chunk);
// Flushed per frame: the point of an event stream is that each event arrives when it happens.
zs.flush(flushKind, () => {});
return ok;
},
drains: zs as unknown as NodeJS.EventEmitter,
end: () => zs.end(), // `pipe` ends `res` once the compressor has drained
destroy: () => zs.destroy(),
};
}
+3
View File
@@ -8,6 +8,7 @@ import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views';
import type { Encoding } from './compression';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
@@ -95,6 +96,8 @@ export type NeutralOutcome =
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
route: string;
/** Set by `compressOutcome`: the adapter encodes each frame with it and flushes. */
encoding?: Encoding;
};
/** {@link handle}'s result for a normal (non-preflight) request. */
+39 -22
View File
@@ -2,7 +2,7 @@ import type http from 'http';
import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
@@ -22,6 +22,7 @@ import { currentRoutes } from './router';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
import { answerProbe } from './health';
import { compressOutcome } from './compression';
interface HandlerConfig {
routes: RouteTable;
@@ -183,30 +184,46 @@ function createRequestHandler(cfg: HandlerConfig) {
}
}
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
if (result.outcome.kind === 'stream') {
await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return;
}
res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body);
await writeResult(req, res, result, { opts, bus, correlation });
}
}
/**
* Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16).
* Module scope rather than inside `serve`, whose closure would charge every branch here again.
*/
async function writeResult(
req: http.IncomingMessage,
res: http.ServerResponse,
result: HandleResult | Preflight,
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
): Promise<void> {
const { opts, bus, correlation } = ctx;
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
// Not awaited unless compression actually returned a promise: an app without it keeps the
// synchronous write it had.
const decided = compressOutcome(
opts?.compression,
{ method: req.method ?? 'GET', headers: req.headers },
result.outcome,
);
const outcome = decided instanceof Promise ? await decided : decided;
if (outcome.kind === 'stream') {
await pipeStream(res, outcome, bus, opts?.streams, correlation);
return;
}
res.writeHead(outcome.status, outcome.headers);
res.end(outcome.body);
}
/**
* Answers a health probe and returns true, or returns false for any other request. Runs before the
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
+18 -10
View File
@@ -3,6 +3,8 @@ import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
import type { Bus, Correlation } from '../bus';
import type { NeutralOutcome } from './core';
import { frameSink } from './compression';
const PING_MS = 15_000;
@@ -27,34 +29,40 @@ export function pickEncoder(transport: Transport, accept: string): StreamEncoder
return pick(accept);
}
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
/**
* Pipes a stream outcome to the response, with keep-alive pings and backpressure handling. With
* `outcome.encoding` set (CARD-16), frames go through a `node:zlib` stream piped into `res`, flushed
* after every frame, error frame and ping, so each event is decodable on arrival.
*/
export async function pipeStream(
res: http.ServerResponse,
stream: AsyncIterable<unknown>,
encoder: StreamEncoder,
outcome: Extract<NeutralOutcome, { kind: 'stream' }>,
bus?: Bus,
name = '',
streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> {
const { stream, encoder, route: name } = outcome;
// `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.writeHead(200, outcome.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', trace);
const sink = frameSink(res, outcome.encoding);
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
if (encoder.ping) {
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
ping = setInterval(() => sink.write(encoder.ping!()), PING_MS);
ping.unref?.();
}
const stop = () => {
if (ping) clearInterval(ping);
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
sink.destroy();
void Promise.resolve(iterator.return?.()).catch(() => {});
};
@@ -76,19 +84,19 @@ export async function pipeStream(
const { value, done } = await iterator.next();
if (done) break;
if (!res.write(encoder.encode(value))) {
await Promise.race([once(res, 'drain'), onClose]);
if (!sink.write(encoder.encode(value))) {
await Promise.race([once(sink.drains, 'drain'), onClose]);
if (res.destroyed) break; // let finally clean up
}
}
} catch (err) {
bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame);
if (frame && !res.writableEnded) sink.write(frame);
} finally {
if (ping) clearInterval(ping);
streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end();
if (!res.writableEnded && !res.destroyed) sink.end();
bus?.emit('stream:close', trace);
}
}
+3
View File
@@ -7,6 +7,7 @@ import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { CompressionConfig } from './compression';
/** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits {
@@ -70,6 +71,8 @@ export interface HttpOptions {
health?: HealthProbe;
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
etag?: boolean;
/** Resolved `createApp({ compression })`; absent when compression is off. */
compression?: CompressionConfig;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
+19 -15
View File
@@ -18,6 +18,8 @@ import { renderError, type ErrorRequest } from '../transformers';
import type { RouteTable, HttpOptions } from './types';
import { answerProbe } from './health';
import { currentRoutes } from './router';
import { compressOutcome, compressWebStream } from './compression';
import type { NeutralOutcome } from './core';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -202,23 +204,22 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
/** Converts an outcome (already through `compressOutcome`) into a web `Response`, buffered or streamed. */
function outcomeToResponse(
outcome: NeutralOutcome,
injected: Record<string, string>,
bus?: Bus,
correlation: Correlation = {},
): Response {
const headers = toWebHeaders(mergeInjectedHeaders(outcome.headers, injected));
if (result.outcome.kind === 'stream') {
const body = asReadableStream(
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
correlation,
);
return new Response(body, { headers });
if (outcome.kind === 'stream') {
const frames = asReadableStream(outcome.stream, outcome.encoder, bus, outcome.route, correlation);
return new Response(outcome.encoding ? compressWebStream(frames, outcome.encoding) : frames, { headers });
}
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
return new Response(body, { status: result.outcome.status, headers });
const body = [204, 205, 304].includes(outcome.status) ? null : toBodyInit(outcome.body);
return new Response(body, { status: outcome.status, headers });
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
@@ -329,7 +330,10 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
});
}
return outcomeToResponse(result, opts?.bus, correlation);
const decided = compressOutcome(opts?.compression, { method: request.method, headers }, result.outcome);
return decided instanceof Promise
? decided.then((outcome) => outcomeToResponse(outcome, injected, opts?.bus, correlation))
: outcomeToResponse(decided, injected, opts?.bus, correlation);
};
}
+1
View File
@@ -98,6 +98,7 @@ export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation
export type { RequestLimits } from './http';
export type { CompressionOptions } from './http/compression';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart';