feat(http): response compression with gzip and br (CARD-16, #112)
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:
21 files changed
+1536
-50
No files matched your search
+19
-15
@@ -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);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user