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

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 00:24:59 -05:00
1 parent fc1db2dbab
commit d5643da03a
20 files changed
+1437 -40

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
// CARD-16 (#112, D13): one app shared by the Node, Deno, Bun and edge compression tests, so every
// runtime is checked against the same routes and the same bytes (T12). Lifted from the D13 spike
// (`spike/d13-compression-b`). Import `reflect-metadata` first.
//
// Bodies are deterministic (seeded LCG), identical to the spikes' harness: a 10,205 B JSON and a
// 51,108 B HTML page — the HTML is also the body of the Deno memory check.
import { createApp, Route, Get, Head, Sse, Stream, Module, Transformer, NotModified } from '../../src/index';
function rng(seed: number): () => number {
let s = seed >>> 0;
return () => (s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32;
}
const WORDS = 'alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa'.split(' ');
export const JSON_BODY: string = (() => {
const r = rng(42);
const items: unknown[] = [];
let s = '';
for (let i = 0; s.length < 10240; i++) {
items.push({
id: i,
uuid: Array.from({ length: 4 }, () => Math.floor(r() * 2 ** 32).toString(16).padStart(8, '0')).join('-'),
name: `${WORDS[Math.floor(r() * 16)]} ${WORDS[Math.floor(r() * 16)]}`,
price: Math.round(r() * 100000) / 100,
active: r() > 0.5,
tags: [WORDS[Math.floor(r() * 16)], WORDS[Math.floor(r() * 16)]],
});
s = JSON.stringify({ items });
}
return JSON.stringify({ items: items.slice(0, items.length - 1) });
})();
export const HTML_BODY: string = (() => {
const r = rng(7);
const w = () => WORDS[Math.floor(r() * 16)];
let s =
'<!doctype html><html><head><meta charset="utf-8"><title>Spike</title><style>body{font-family:sans-serif}.row{display:flex;gap:8px}</style></head><body><main>';
let i = 0;
while (s.length < 51200 - 200) {
s += `<div class="row" data-id="${i++}"><a href="/item/${Math.floor(r() * 1e6)}">${w()} ${w()}</a><span class="price">${(r() * 1000).toFixed(2)}</span><p>${w()} ${w()} ${w()} ${w()} ${w()} ${w()}.</p></div>\n`;
}
return s + '</main></body></html>';
})();
export const SMALL_BODY = JSON.stringify({ pad: 'x'.repeat(500) }); // 512 B, under the 1024 threshold
export const BIG_BODY = HTML_BODY.repeat(2); // 102 KiB
const PNG = 'P'.repeat(4096);
const TEXT = 'y'.repeat(4096);
const raw = (headers: Record<string, string>, status = 200) => (body: unknown) => ({
status,
headers,
body: body as string,
});
/** How many frames `/c/flood` has produced, across every request. */
export const flood = { produced: 0 };
export const SSE_EVENTS = 5;
export const SSE_GAP_MS = 200;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@Route('/c')
class Compressible {
@Get('/json') @Transformer(raw({ 'content-type': 'application/json' })) json() {
return JSON_BODY;
}
@Head('/json') @Transformer(raw({ 'content-type': 'application/json' })) headJson() {
return JSON_BODY;
}
@Get('/html') @Transformer(raw({ 'Content-Type': 'text/html; charset=utf-8' })) html() {
return HTML_BODY;
}
@Get('/big') @Transformer(raw({ 'content-type': 'text/html' })) big() {
return BIG_BODY;
}
@Get('/small') @Transformer(raw({ 'content-type': 'application/json' })) small() {
return SMALL_BODY;
}
@Get('/png') @Transformer(raw({ 'content-type': 'image/png' })) png() {
return PNG;
}
@Get('/notype') @Transformer(raw({})) notype() {
return TEXT;
}
@Get('/pre') @Transformer(raw({ 'content-type': 'text/plain', 'content-encoding': 'gzip' })) pre() {
return TEXT; // not really gzip: core must leave it byte-for-byte alone
}
@Get('/range')
@Transformer(raw({ 'content-type': 'text/plain', 'content-range': 'bytes 0-4095/8192' }, 206))
range() {
return TEXT;
}
@Get('/notransform') @Transformer(raw({ 'content-type': 'text/plain', 'cache-control': 'no-transform' })) nt() {
return TEXT;
}
@Get('/vary') @Transformer(raw({ 'content-type': 'text/plain', vary: 'Origin' })) vary() {
return TEXT;
}
@Get('/empty') @Transformer(raw({ 'content-type': 'text/plain' }, 204)) empty() {
return '';
}
@Get('/etag') @Transformer(raw({ 'content-type': 'application/json', etag: '"v1"' })) etag() {
return JSON_BODY;
}
@Get('/304') notModified() {
throw new NotModified();
}
@Sse('/sse') async *sse() {
for (let n = 0; n < SSE_EVENTS; n++) {
if (n) await sleep(SSE_GAP_MS);
yield { n, t: Date.now() };
}
}
@Stream('/ndjson') async *ndjson() {
for (let n = 0; n < 3; n++) yield { n };
}
@Get('/plainjson') plainJson() {
return JSON.parse(JSON_BODY); // through the default JsonTransformer, for the ETag interplay (T10)
}
/** Large, poorly compressible frames as fast as they are pulled: the slow-client backpressure case. */
@Stream('/flood') async *flood() {
const r = rng(9);
for (;;) {
flood.produced++;
yield { pad: Array.from({ length: 4096 }, () => Math.floor(r() * 2 ** 32).toString(36)).join('') };
}
}
/** Never ends on its own: the client-disconnect case. */
@Sse('/forever') async *forever() {
for (let n = 0; ; n++) {
yield { n, pad: 'z'.repeat(256) };
await sleep(5);
}
}
}
@Module({ mountpoint: '/', controllers: [Compressible] })
class CompressionModule {}
/** The fixture app; `opts` is spread into `createApp` (`compression`, `etag`, …). */
export const compressionApp = (opts: Omit<Parameters<typeof createApp>[0], 'modules'> = {}) =>
createApp({ modules: [CompressionModule], ...opts });
+160
View File
@@ -0,0 +1,160 @@
// CARD-16 (#112): the server-runtime checks shared by test/deno/compression.test.ts and
// test/bun/compression.test.ts, run against `compressionApp({ compression: true, etag: true })`
// served by the runtime's own server. Each check throws on failure. Reads go through `node:http`,
// which decodes nothing, so a double encoding cannot hide.
import http from 'node:http';
import zlib from 'node:zlib';
import { JSON_BODY, HTML_BODY, SSE_EVENTS, SSE_GAP_MS } from './compression-app';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Uint8Array;
}
function get(port: number, path: string, headers: Record<string, string> = {}, method = 'GET'): Promise<Raw> {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, path, method, headers }, (res) => {
const chunks: Uint8Array[] = [];
res.on('data', (c: Uint8Array) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, bytes: Buffer.concat(chunks) }));
});
req.on('error', reject);
req.end();
});
}
const decode = (bytes: Uint8Array, ce: unknown): string =>
new TextDecoder().decode(
ce === 'br' ? zlib.brotliDecompressSync(bytes) : ce === 'gzip' ? zlib.gunzipSync(bytes) : bytes,
);
function check(cond: unknown, message: string): void {
if (!cond) throw new Error(message);
}
const hasVary = (r: Raw) => /accept-encoding/i.test(String(r.headers.vary ?? ''));
/** T1–T6 and T12: negotiation, one layer, original bytes. */
async function negotiation(port: number): Promise<void> {
const cases: [string, string | undefined, string | undefined, string][] = [
['/c/json', 'gzip, br', 'br', JSON_BODY], // T1
['/c/json', 'br;q=0, gzip', 'gzip', JSON_BODY], // T2
['/c/json', 'identity', undefined, JSON_BODY], // T3
['/c/json', undefined, undefined, JSON_BODY], // T3
['/c/json', '*;q=0', undefined, JSON_BODY], // T4
['/c/json', '*', 'br', JSON_BODY], // T5
['/c/html', 'gzip', 'gzip', HTML_BODY], // T12
['/c/html', 'br', 'br', HTML_BODY],
];
for (const [path, ae, ce, original] of cases) {
const r = await get(port, path, ae === undefined ? {} : { 'accept-encoding': ae });
const label = `${path} ${ae ?? '(none)'}`;
check(r.headers['content-encoding'] === ce, `${label}: content-encoding ${String(r.headers['content-encoding'])}, expected ${ce}`);
check(hasVary(r), `${label}: no Vary`);
check(decode(r.bytes, ce) === original, `${label}: body does not decode to the original bytes`);
}
}
/** T7, T8, T11, T15: skips, and the 304 shape. */
async function skips(port: number): Promise<void> {
for (const [path, vary] of [
['/c/small', true],
['/c/png', false],
['/c/notype', false],
['/c/range', false],
['/c/notransform', false],
] as const) {
const r = await get(port, path, { 'accept-encoding': 'gzip, br' });
check(r.headers['content-encoding'] === undefined, `${path}: encoded`);
check(hasVary(r) === vary, `${path}: Vary ${String(r.headers.vary)}`);
}
const head = await get(port, '/c/json', { 'accept-encoding': 'gzip' }, 'HEAD');
check(head.headers['content-encoding'] === undefined && hasVary(head), 'HEAD: encoded or no Vary');
const nm = await get(port, '/c/304', { 'accept-encoding': 'gzip' });
check(nm.status === 304 && hasVary(nm) && nm.headers['content-type'] === undefined, 'T15: 304 shape');
}
/** T10: the ETag does not change with the coding, and its 304 carries Vary. */
async function etag(port: number): Promise<void> {
const identity = await get(port, '/c/plainjson', { 'accept-encoding': 'identity' });
const gz = await get(port, '/c/plainjson', { 'accept-encoding': 'gzip' });
check(gz.headers['content-encoding'] === 'gzip', 'T10: not gzip');
check(gz.headers.etag !== undefined && gz.headers.etag === identity.headers.etag, 'T10: ETag differs by coding');
const nm = await get(port, '/c/plainjson', { 'accept-encoding': 'gzip', 'if-none-match': String(gz.headers.etag) });
check(nm.status === 304 && hasVary(nm) && nm.bytes.length === 0, 'T10: 304 without Vary or with a body');
}
/** T14: ndjson decodes to the same lines. */
async function ndjson(port: number): Promise<void> {
for (const ce of ['gzip', 'br']) {
const r = await get(port, '/c/ndjson', { 'accept-encoding': ce });
check(r.headers['content-encoding'] === ce, `T14 ${ce}: not encoded`);
check(decode(r.bytes, ce) === '{"n":0}\n{"n":1}\n{"n":2}\n', `T14 ${ce}: lines differ`);
}
}
/** T9: each SSE event decodes before the next one is produced. Returns the per-event lags. */
async function sse(port: number): Promise<Record<string, number[]>> {
const out: Record<string, number[]> = {};
for (const ce of ['gzip', 'br']) {
out[ce] = await new Promise<number[]>((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path: '/c/sse', headers: { 'accept-encoding': ce, accept: 'text/event-stream' } }, (res) => {
if (res.headers['content-encoding'] !== ce) reject(new Error(`T9 ${ce}: not encoded`));
const dec = ce === 'br' ? zlib.createBrotliDecompress() : zlib.createGunzip();
const lags: number[] = [];
let buf = '';
dec.on('data', (d: Uint8Array) => {
buf += new TextDecoder().decode(d);
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) lags.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.pipe(dec);
dec.on('end', () => resolve(lags));
dec.on('error', reject);
})
.on('error', reject);
});
check(out[ce].length === SSE_EVENTS, `T9 ${ce}: ${out[ce].length} events`);
for (const lag of out[ce]) check(lag < SSE_GAP_MS / 2, `T9 ${ce}: event lag ${lag} ms`);
}
return out;
}
export const checks = { negotiation, skips, etag, ndjson, sse };
/**
* How many 1 ms timer ticks fire while `zlib.gzip` (the async API core uses) compresses 16 MB of
* random bytes — incompressible, so the work takes a few hundred ms on any machine (repetitive
* input finished in 4 ms on a CI runner and proved nothing). When the runtime offloads zlib to a
* worker thread the loop keeps ticking, roughly one tick per ms; when it runs it on the main thread
* (Deno 2.9.7, SPIKE-COMPRESSION-B §7) almost none fire. The runtime docs state which one each
* runtime does, and the suites pin it with this.
*/
export async function ticksDuringGzip(): Promise<{ ms: number; ticks: number }> {
const bytes = new Uint8Array(16 * 1024 * 1024);
for (let i = 0; i < bytes.length; i += 65536) crypto.getRandomValues(bytes.subarray(i, i + 65536));
let ticks = 0;
const timer = setInterval(() => ticks++, 1);
const started = performance.now();
await new Promise<void>((resolve, reject) => zlib.gzip(bytes, (err) => (err ? reject(err) : resolve())));
const ms = performance.now() - started;
clearInterval(timer);
return { ms, ticks };
}
/** Compression off: the runtime's server sends identity even to a gzip client (it does not compress by itself). */
export async function serverDoesNotCompress(port: number): Promise<void> {
const r = await get(port, '/c/html', { 'accept-encoding': 'gzip, br' });
check(r.headers['content-encoding'] === undefined, `the server encoded by itself: ${String(r.headers['content-encoding'])}`);
check(decode(r.bytes, undefined) === HTML_BODY, 'body changed');
}