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

+36
View File
@@ -0,0 +1,36 @@
// CARD-16 (#112) under the real Bun runtime: `Bun.serve` does not compress by itself, so every
// encoding here is core's, through `node:zlib`. Run with: npm run test:bun
import 'reflect-metadata';
import { test } from 'bun:test';
import { serveBun } from '../../src/bun.ts';
import { compressionApp } from '../fixtures/compression-app.ts';
import { checks, serverDoesNotCompress, ticksDuringGzip } from '../fixtures/compression-checks.ts';
for (const [name, run] of Object.entries(checks)) {
test(`compression on Bun.serve: ${name}`, async () => {
const server = await serveBun(compressionApp({ compression: true, etag: true }), { hostname: '127.0.0.1', port: 0 });
try {
await run(server.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
}
// The documented Bun facts (CARD-16; `guides/runtimes.md`).
test('documented: Bun.serve does not compress by itself (core compression off → identity)', async () => {
const server = await serveBun(compressionApp(), { hostname: '127.0.0.1', port: 0 });
try {
await serverDoesNotCompress(server.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
test("documented: node:zlib's async gzip is off the main thread on Bun", async () => {
const { ms, ticks } = await ticksDuringGzip();
if (ms < 50) throw new Error(`gzip took ${Math.round(ms)} ms — too fast to tell; enlarge the input`);
if (ticks < ms / 4) throw new Error(`only ${ticks} ticks in ${Math.round(ms)} ms: Bun blocked the loop — update the docs`);
});
+377
View File
@@ -0,0 +1,377 @@
// CARD-16 (#112, D13): response compression on the Node adapter (`listen()`) and `app.fetch`.
// Negotiation T1–T6, skips T7/T8/T11, round trip T12, ETag interplay T10, 304 T15, ndjson T14, SSE
// per event T9, the edge rule through both signals (detection and `edgeHandler`), validation, and
// a client leaving mid-stream. Deno, Bun and workerd repeat what applies to them in their suites.
import 'reflect-metadata';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import * as http from 'node:http';
import * as zlib from 'node:zlib';
import type { AddressInfo } from 'node:net';
import { compressionApp, flood, JSON_BODY, HTML_BODY, BIG_BODY, SSE_EVENTS, SSE_GAP_MS } from './fixtures/compression-app';
import { negotiate, resolveCompression } from '../src/http/compression';
import { ticksDuringGzip } from './fixtures/compression-checks';
import { edgeHandler } from '../src/edge';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Buffer;
}
/** Raw bytes off the socket: no client-side decoding, so a double encoding cannot hide. */
function get(port: number, path: string, headers: Record<string, string> = {}, method = 'GET'): Promise<Raw> {
return new Promise((resolve, reject) => {
const req = http.request({ port, path, method, headers }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => 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: Buffer, ce: string | undefined): string =>
(ce === 'br' ? zlib.brotliDecompressSync(bytes) : ce === 'gzip' ? zlib.gunzipSync(bytes) : bytes).toString('utf8');
const ae = (value?: string): Record<string, string> => (value === undefined ? {} : { 'accept-encoding': value });
describe('negotiate() (RFC 9110 §12.5.3)', () => {
const both = ['br', 'gzip'] as ('br' | 'gzip')[];
it.each([
['gzip, br', 'br'], // T1: tie → server preference
['br;q=0, gzip', 'gzip'], // T2
['identity', undefined], // T3
[undefined, undefined], // T3 (absent)
['*;q=0', undefined], // T4
['*', 'br'], // T5: first configured
['gzip;q=1, br;q=0.5', 'gzip'],
['gzip;q=0.5, *', 'br'],
['br;q=bogus, gzip', 'gzip'],
// RFC 9110 §12.4.2 qvalues only: a malformed or out-of-range q excludes the member.
['gzip;q=2, br;q=1', 'br'],
['gzip;q=1e0', undefined],
['gzip;q=0.5000', undefined],
['gzip;q=-1', undefined],
['gzip;q=0.500, br;q=0.4', 'gzip'],
['gzip;q=1.000, br;q=1.', 'br'],
['GZIP', 'gzip'],
])('%s → %s', (header, expected) => {
expect(negotiate(header, both)).toBe(expected);
});
it('T6: encodings [gzip], client accepts only br → identity', () => {
expect(negotiate('br', ['gzip'])).toBeUndefined();
});
});
describe('option validation (at createApp)', () => {
it.each([
{ threshold: -1 },
{ threshold: 1.5 },
{ threshold: '1' },
{ encodings: [] },
{ encodings: ['zstd'] },
{ encodings: 'gzip' },
])('%j throws', (o) => {
expect(() => compressionApp({ compression: o as never })).toThrow(TypeError);
});
it('a non-object throws; off by default', () => {
expect(() => compressionApp({ compression: 'yes' as never })).toThrow(TypeError);
expect(resolveCompression(undefined)).toBeUndefined();
expect(resolveCompression(false)).toBeUndefined();
expect(resolveCompression(true, () => true)).toEqual({ threshold: 1024, encodings: ['br', 'gzip'], encode: true });
});
});
for (const adapter of ['node', 'fetch'] as const) {
describe(`${adapter} adapter, compression: true`, () => {
let close: () => Promise<void> = async () => {};
let call: (path: string, headers?: Record<string, string>, method?: string) => Promise<Raw>;
beforeAll(async () => {
const app = compressionApp({ compression: true, etag: true });
if (adapter === 'node') {
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
close = () => app.close();
call = (p, h, m) => get(port, p, h, m);
} else {
call = async (p, h = {}, method = 'GET') => {
const res = await app.fetch(new Request(`http://x${p}`, { method, headers: h }));
const headers: http.IncomingHttpHeaders = {};
res.headers.forEach((v, k) => (headers[k] = v));
return { status: res.status, headers, bytes: Buffer.from(await res.arrayBuffer()) };
};
}
});
afterAll(() => close());
it.each([
['/c/json', 'gzip, br', 'br', JSON_BODY],
['/c/json', 'br;q=0, gzip', 'gzip', JSON_BODY],
['/c/json', '*', 'br', JSON_BODY],
['/c/html', 'gzip', 'gzip', HTML_BODY],
['/c/html', 'br', 'br', HTML_BODY],
['/c/big', 'gzip', 'gzip', BIG_BODY],
['/c/big', 'br', 'br', BIG_BODY],
])('T1/T2/T5/T12 %s with %s → %s, decodes to the original bytes', async (path, accept, ce, original) => {
const r = await call(path, ae(accept));
expect(r.headers['content-encoding']).toBe(ce);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.headers['content-length'] === undefined || Number(r.headers['content-length']) === r.bytes.length).toBe(
true,
);
expect(decode(r.bytes, ce)).toBe(original); // one layer only: a second would not decode to this
});
it.each([['identity'], [undefined], ['*;q=0']])('T3/T4 Accept-Encoding %s → identity + Vary', async (accept) => {
const r = await call('/c/json', ae(accept));
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.bytes.toString()).toBe(JSON_BODY);
});
it.each([
['/c/small', 'T7 under threshold', true],
['/c/png', 'T8 image/png', false],
['/c/notype', 'T8 missing content-type', false],
['/c/range', 'T8 content-range', false],
['/c/notransform', 'T11 no-transform', false],
])('%s (%s) is sent identity', async (path, _why, vary) => {
const r = await call(path, ae('gzip, br'));
expect(r.headers['content-encoding']).toBeUndefined();
expect(/accept-encoding/i.test(String(r.headers.vary ?? ''))).toBe(vary);
});
it('T8 handler-set content-encoding is passed through untouched (no double encoding)', async () => {
const r = await call('/c/pre', ae('gzip, br'));
expect(r.headers['content-encoding']).toBe('gzip');
expect(r.bytes.toString()).toBe('y'.repeat(4096));
});
it('T8 HEAD and 204 are not encoded; HEAD keeps Vary, 204 gets none', async () => {
const head = await call('/c/json', ae('gzip'), 'HEAD');
expect(head.headers['content-encoding']).toBeUndefined();
expect(head.headers.vary).toMatch(/Accept-Encoding/i);
const empty = await call('/c/empty', ae('gzip'));
expect(empty.status).toBe(204);
expect(empty.headers['content-encoding']).toBeUndefined();
expect(empty.headers.vary).toBeUndefined();
});
it('merges Vary with a handler Vary', async () => {
const r = await call('/c/vary', ae('gzip'));
expect(r.headers.vary).toBe('Origin, Accept-Encoding');
});
it('T15: a 304 (NotModified) carries Vary, no Content-Type and no body', async () => {
const r = await call('/c/304', ae('gzip'));
expect(r.status).toBe(304);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.headers['content-type']).toBeUndefined();
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.bytes.length).toBe(0);
});
it('T10: etag + gzip → the same ETag as identity; the 304 carries Vary', async () => {
const identity = await call('/c/plainjson', ae('identity'));
const gz = await call('/c/plainjson', ae('gzip'));
expect(gz.headers['content-encoding']).toBe('gzip');
expect(gz.headers.etag).toMatch(/^W\//);
expect(gz.headers.etag).toBe(identity.headers.etag);
const nm = await call('/c/plainjson', { ...ae('gzip'), 'if-none-match': String(gz.headers.etag) });
expect(nm.status).toBe(304);
expect(nm.headers.vary).toMatch(/Accept-Encoding/i);
expect(nm.headers.etag).toBe(gz.headers.etag);
expect(nm.bytes.length).toBe(0);
});
it('a handler strong ETag stays strong on the encoded variant', async () => {
const r = await call('/c/etag', ae('gzip'));
expect(r.headers['content-encoding']).toBe('gzip');
expect(r.headers.etag).toBe('"v1"');
});
it.each(['gzip', 'br'])('T14 ndjson stream is encoded with %s and decodes to the same lines', async (ce) => {
const r = await call('/c/ndjson', ae(ce));
expect(r.headers['content-encoding']).toBe(ce);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(decode(r.bytes, ce)).toBe('{"n":0}\n{"n":1}\n{"n":2}\n');
});
it('a stream to an identity client gets Vary and is not encoded', async () => {
const r = await call('/c/ndjson', ae('identity'));
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.bytes.toString()).toBe('{"n":0}\n{"n":1}\n{"n":2}\n');
});
});
}
describe('custom options', () => {
it('T6 encodings [gzip] with a br-only client → identity; threshold lowers the floor', async () => {
const app = compressionApp({ compression: { encodings: ['gzip'], threshold: 0 } });
const br = await app.fetch(new Request('http://x/c/small', { headers: ae('br') }));
expect(br.headers.get('content-encoding')).toBeNull();
const gz = await app.fetch(new Request('http://x/c/small', { headers: ae('gzip') }));
expect(gz.headers.get('content-encoding')).toBe('gzip');
});
});
describe('edge: core never encodes, Vary only', () => {
const identityWithVary = async (app: ReturnType<typeof compressionApp>) => {
for (const path of ['/c/json', '/c/ndjson']) {
const res = await app.fetch(new Request(`http://x${path}`, { headers: ae('gzip, br') }));
expect(res.headers.get('content-encoding'), path).toBeNull();
expect(res.headers.get('vary'), path).toMatch(/Accept-Encoding/i);
await res.arrayBuffer();
}
};
it('detected at createApp from navigator.userAgent (bare app.fetch)', async () => {
vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' });
try {
await identityWithVary(compressionApp({ compression: true }));
} finally {
vi.unstubAllGlobals();
}
});
it('marked by edgeHandler even when detection sees nothing', async () => {
const app = compressionApp({ compression: true });
edgeHandler(app);
await identityWithVary(app);
});
it('edgeHandler on an app without compression is harmless', async () => {
const app = compressionApp();
const res = await edgeHandler(app)(new Request('http://x/c/json', { headers: ae('gzip') }));
expect(res.headers.get('content-encoding')).toBeNull();
expect(res.headers.get('vary')).toBeNull();
});
});
describe('T9 SSE per-event delivery with compression (Node listen())', () => {
it.each(['gzip', 'br'])('%s: event n is readable before event n+1 is produced', async (ce) => {
const app = compressionApp({ compression: true });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
const lags = await new Promise<number[]>((resolve, reject) => {
http
.get({ port, path: '/c/sse', headers: { 'accept-encoding': ce, accept: 'text/event-stream' } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
const dec = ce === 'br' ? zlib.createBrotliDecompress() : zlib.createGunzip();
const out: number[] = [];
let buf = '';
dec.on('data', (d: Buffer) => {
buf += d.toString();
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) out.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.pipe(dec);
dec.on('end', () => resolve(out));
dec.on('error', reject);
})
.on('error', reject);
});
expect(lags).toHaveLength(SSE_EVENTS);
// Each event decodes well inside the gap before the next one is even produced.
for (const lag of lags) expect(lag).toBeLessThan(SSE_GAP_MS / 2);
} finally {
await app.close();
}
});
});
describe('client disconnect mid-stream', () => {
it.each(['gzip', 'br'])('Node %s: the stream closes and the compressor is torn down', async (ce) => {
const app = compressionApp({ compression: true });
const closed = new Promise<void>((resolve) => app.bus.on('stream:close', () => resolve()));
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
await new Promise<void>((resolve, reject) => {
const req = http.get({ port, path: '/c/forever', headers: { 'accept-encoding': ce } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
res.once('data', () => {
req.destroy();
resolve();
});
});
req.on('error', () => {});
setTimeout(() => reject(new Error('no data')), 2000);
});
await closed;
} finally {
await app.close();
}
});
it.each(['gzip', 'br'])('app.fetch %s: cancelling the body cancels the source', async (ce) => {
const app = compressionApp({ compression: true });
const closed = new Promise<void>((resolve) => app.bus.on('stream:close', () => resolve()));
const res = await app.fetch(new Request('http://x/c/forever', { headers: ae(ce) }));
expect(res.headers.get('content-encoding')).toBe(ce);
const reader = res.body!.getReader();
const first = await reader.read();
expect(first.done).toBe(false);
await reader.cancel();
await closed;
});
});
describe('slow client backpressure (Node)', () => {
it.each(['gzip', 'br'])('%s: a client that stops reading stops the producer', async (ce) => {
const app = compressionApp({ compression: true });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
const req = http.get({ port, path: '/c/flood', headers: { 'accept-encoding': ce } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
res.pause(); // never read
});
req.on('error', () => {});
// Each frame is ~28 KB of nearly incompressible text. Without backpressure the generator never
// stops; with it, it stops once the socket, the response and the compressor's buffers are full.
// How many frames that takes depends on the kernel's socket buffers (Linux auto-tunes them to
// several MB), so wait for production to stall rather than for a fixed time.
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
let previous = -1;
for (let waited = 0; flood.produced !== previous; waited += 200) {
expect(waited, `still producing after ${waited} ms: ${flood.produced} frames`).toBeLessThan(10_000);
previous = flood.produced;
await sleep(200);
}
const stalled = flood.produced;
await sleep(500);
expect(flood.produced - stalled).toBeLessThanOrEqual(1);
expect(stalled).toBeLessThan(2000);
req.destroy();
} finally {
flood.produced = 0;
await app.close();
}
}, 20_000);
});
describe('documented runtime behaviour (Node)', () => {
it("node:zlib's async gzip runs off the main thread, so the loop keeps ticking", async () => {
const { ms, ticks } = await ticksDuringGzip();
expect(ms).toBeGreaterThan(50);
expect(ticks).toBeGreaterThan(ms / 4);
});
});
+43
View File
@@ -0,0 +1,43 @@
// CARD-16 (#112) under the real Deno runtime, importing `src/` the way JSR serves it — so `node:zlib`
// is reached through `nodeRequire`'s `process.getBuiltinModule` path. Deno runs zlib's async API on
// the main thread (documented limitation); these checks cover correctness, not throughput.
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { serveDeno } from '../../src/deno.ts';
import { compressionApp } from '../fixtures/compression-app.ts';
import { checks, serverDoesNotCompress, ticksDuringGzip } from '../fixtures/compression-checks.ts';
for (const [name, run] of Object.entries(checks)) {
Deno.test(`compression on Deno.serve: ${name}`, async () => {
const server = await serveDeno(compressionApp({ compression: true, etag: true }), {
hostname: '127.0.0.1',
port: 0,
onListen: () => {},
});
try {
await run((server as unknown as { addr: { port: number } }).addr.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
}
// The documented Deno facts (CARD-16; `guides/runtimes.md`). If one of these starts failing, Deno
// changed and the docs have to change with it — not the assertion.
Deno.test('documented: Deno.serve does not compress by itself (core compression off → identity)', async () => {
const server = await serveDeno(compressionApp(), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
try {
await serverDoesNotCompress((server as unknown as { addr: { port: number } }).addr.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
Deno.test("documented: node:zlib's async gzip runs on Deno's main thread", async () => {
const { ms, ticks } = await ticksDuringGzip();
if (ms < 50) throw new Error(`gzip took ${Math.round(ms)} ms — too fast to tell; enlarge the input`);
if (ticks > Math.max(5, ms / 10))
throw new Error(`timers kept firing (${ticks} ticks in ${Math.round(ms)} ms): Deno now offloads zlib — update the docs`);
});
+13
View File
@@ -0,0 +1,13 @@
// CARD-16 (#112): the compression fixture served from real workerd, twice — through `edgeHandler`
// (T13) and as a bare `app.fetch` export (T16, reached with `Host: bare`). Core must never encode
// in either; the platform (miniflare locally, Cloudflare when deployed) may. See compression.ts.
import { edgeHandler } from '../../src/edge';
import { compressionApp } from '../fixtures/compression-app';
const viaHandler = edgeHandler(compressionApp({ compression: true }));
const bare = compressionApp({ compression: true });
export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof viaHandler>[2]) =>
new URL(request.url).hostname === 'bare' ? bare.fetch(request) : viaHandler(request, env, ctx),
};
+155
View File
@@ -0,0 +1,155 @@
// CARD-16 (#112) on real workerd via miniflare: T1 (edge), T12, T13, T16 and SSE. Reads raw bytes
// off a real socket with node:http — `dispatchFetch` would decode and hide a double encoding — and
// peels encodings by magic bytes, requiring at most one layer and the original bytes. Run twice:
// with the default compat flags (workerd detected through `navigator.userAgent`) and with
// `no_global_navigator` (no `navigator` at all), so neither signal alone carries the result.
//
// Run with: tsx test/edge/compression.ts (chained from `npm run test:edge`)
import 'reflect-metadata';
import { strict as assert } from 'node:assert';
import * as http from 'node:http';
import * as zlib from 'node:zlib';
import { build } from 'esbuild';
import { Miniflare } from 'miniflare';
import { JSON_BODY, HTML_BODY, SSE_EVENTS, SSE_GAP_MS } from '../fixtures/compression-app';
const BUNDLE = 'test/edge/_compression-worker.mjs';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Buffer;
}
function get(url: URL, path: string, host: string, ae?: string): Promise<Raw> {
return new Promise((resolve, reject) => {
http
.get(new URL(path, url), { headers: { host, ...(ae ? { 'accept-encoding': ae } : {}) } }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, bytes: Buffer.concat(chunks) }));
})
.on('error', reject);
});
}
/** Decodes by magic bytes, not by header, so a second layer is counted even if the header lies. */
function peel(bytes: Buffer): { layers: string[]; text: string } {
const layers: string[] = [];
let b = bytes;
for (let k = 0; k < 4; k++) {
if (b[0] === 0x1f && b[1] === 0x8b) {
b = zlib.gunzipSync(b);
layers.push('gzip');
continue;
}
const first = b.toString('utf8', 0, 1);
if (b.length === 0 || first === '{' || first === '<') break;
try {
b = zlib.brotliDecompressSync(b);
layers.push('br');
} catch {
layers.push('??');
break;
}
}
return { layers, text: b.toString('utf8') };
}
function sseLags(url: URL, host: string): Promise<number[]> {
return new Promise((resolve, reject) => {
http
.get(new URL('/c/sse', url), { headers: { host, 'accept-encoding': 'gzip, br', accept: 'text/event-stream' } }, (res) => {
assert.equal(res.headers['content-encoding'], undefined, 'edge SSE: encoded');
const out: number[] = [];
let buf = '';
res.on('data', (d: Buffer) => {
buf += d.toString();
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) out.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.on('end', () => resolve(out));
})
.on('error', reject);
});
}
async function run(flags: string[]): Promise<void> {
const mf = new Miniflare({
modules: true,
scriptPath: BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: flags,
host: '127.0.0.1',
port: 0,
});
const url = await mf.ready;
try {
for (const host of ['handler', 'bare']) {
for (const [path, original] of [
['/c/json', JSON_BODY],
['/c/html', HTML_BODY],
] as const) {
for (const ae of ['gzip, br', 'gzip', 'br', 'br;q=0, gzip', 'identity', undefined]) {
const label = `[${flags.join(',')}] ${host} ${path} ${ae ?? '(none)'}`;
const r = await get(url, path, host, ae);
const { layers, text } = peel(r.bytes);
assert.equal(r.status, 200, `${label}: status ${r.status}`);
assert.ok(layers.length <= 1, `${label}: ${layers.join('+')} — doubly encoded`);
assert.equal(text, original, `${label}: body mismatch`);
assert.equal(r.headers['content-encoding'], layers[0], `${label}: header does not match the payload`);
assert.match(String(r.headers.vary), /accept-encoding/i, `${label}: no Vary`);
if (!ae || ae === 'identity') assert.equal(layers.length, 0, `${label}: identity client got an encoding`);
}
}
const lags = await sseLags(url, host);
assert.equal(lags.length, SSE_EVENTS, `${host}: SSE events`);
for (const lag of lags) assert.ok(lag < SSE_GAP_MS / 2, `${host}: SSE lag ${lag} ms`);
}
} finally {
await mf.dispose();
}
}
async function main() {
await build({
entryPoints: ['test/edge/compression-worker.ts'],
bundle: true,
format: 'esm',
outfile: BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
await run(['nodejs_compat']);
await run(['nodejs_compat', 'no_global_navigator']);
console.log(
'edge (workerd): compression — edgeHandler and bare app.fetch, with and without navigator: identity from core, ≤ 1 layer on the wire, Vary set, SSE on time — PASS',
);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+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');
}
+50
View File
@@ -311,3 +311,53 @@ describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
}
});
});
describe('mesh: compression of remote routes (CARD-16)', () => {
it('a remote buffered response is compressed by the teacup like a local one', async () => {
const { gunzipSync } = await import('node:zlib');
const http = await import('node:http');
const payload = { rows: Array.from({ length: 200 }, (_, i) => ({ i, name: `row ${i}` })) };
@Route('/big')
class BigCtl {
@Get('/json', { export: true })
json() {
return payload;
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class BigTeapotModule {}
const teapot = createApp({ modules: [BigTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
compression: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const cServer = await teacup.listen(0);
try {
const raw = await new Promise<{ headers: Record<string, unknown>; bytes: Buffer }>((resolve, reject) => {
http
.get(
{ port: (cServer.address() as any).port, path: '/api/big/json', headers: { 'accept-encoding': 'gzip' } },
(res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ headers: res.headers, bytes: Buffer.concat(chunks) }));
},
)
.on('error', reject);
});
expect(raw.headers['content-encoding']).toBe('gzip');
expect(String(raw.headers.vary)).toMatch(/Accept-Encoding/);
expect(JSON.parse(gunzipSync(raw.bytes).toString())).toEqual(payload);
} finally {
tServer.close();
cServer.close();
}
});
});