About: how pages are checked

tests/sims/wire.test.ts

The automated tests for the /simulators/grpc-vs-rest simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. HPACK output is byte for byte the request examples in RFC 7541 Appendix C.3 (no Huffman) and C.4 (Huffman).
  2. Python's hpack decoder reads back every header block the simulator writes, including the dynamic table evicting old entries.
  3. The order message encodes to exactly the bytes Google's protobuf runtime writes, and each gRPC message carries a 5-byte prefix.
// /simulators/grpc-vs-rest: HPACK header compression, Protocol Buffers and gRPC framing, byte for byte.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { Hpack, pbEncode, calls, makeOrder, ORDER, GET_REQ } from '../../src/lib/sims/wire.ts';
import { lcg } from './check.ts';

const has = (mod: string) => { try { execFileSync('python3', ['-c', `import ${mod}`], { stdio: 'ignore' }); return true; } catch { return false; } };
const hex = (b: number[]) => Buffer.from(b).toString('hex');
const block = (h: Hpack, headers: [string, string][]) => hex(h.encode(headers).flatMap((f) => f.bytes));

test('HPACK output is byte for byte the request examples in RFC 7541 Appendix C.3 (no Huffman) and C.4 (Huffman)', () => {
	const reqs: [string, string][][] = [
		[[':method', 'GET'], [':scheme', 'http'], [':path', '/'], [':authority', 'www.example.com']],
		[[':method', 'GET'], [':scheme', 'http'], [':path', '/'], [':authority', 'www.example.com'], ['cache-control', 'no-cache']],
		[[':method', 'GET'], [':scheme', 'https'], [':path', '/index.html'], [':authority', 'www.example.com'], ['custom-key', 'custom-value']]
	];
	const c3 = new Hpack(4096, 'never');
	assert.deepEqual(reqs.map((r) => block(c3, r)), [
		'828684410f7777772e6578616d706c652e636f6d',
		'828684be58086e6f2d6361636865',
		'828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565'
	]);
	const c4 = new Hpack(4096, 'shorter');
	assert.deepEqual(reqs.map((r) => block(c4, r)), [
		'828684418cf1e3c2e5f23a6ba0ab90f4ff',
		'828684be5886a8eb10649cbf',
		'828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf'
	]);
});

test("Python's hpack decoder reads back every header block the simulator writes, including the dynamic table evicting old entries", { skip: !has('hpack') && 'python hpack is not installed' }, () => {
	const r = lcg(19);
	const names = ['x-request-id', 'authorization', 'cookie', 'accept', 'user-agent', 'x-trace', 'content-type'];
	const lists: [string, string][][] = Array.from({ length: 300 }, () => Array.from({ length: 1 + Math.floor(r() * 6) }, () => {
		const n = names[Math.floor(r() * names.length)];
		const len = r() < 0.1 ? 1500 + Math.floor(r() * 2000) : 1 + Math.floor(r() * 40);
		return [n, Array.from({ length: len }, (_, i) => 'abcdefghijklmnopqrstuvwxyz0123456789-_./ '[(i * 7 + Math.floor(r() * 41)) % 41]).join('').trim() || 'v'] as [string, string];
	}));
	for (const mode of ['always', 'shorter', 'never'] as const) {
		const h = new Hpack(4096, mode);
		const blocks = lists.map((l) => block(h, l));
		const got = JSON.parse(execFileSync('python3', ['-c', 'import json, sys\nfrom hpack import Decoder\nd = Decoder()\nprint(json.dumps([[list(x) for x in d.decode(bytes.fromhex(b))] for b in json.loads(sys.stdin.read())]))'], { input: JSON.stringify(blocks), maxBuffer: 1 << 26 }).toString());
		assert.deepEqual(got, lists, `mode ${mode}`);
	}
	for (const proto of ['h2json', 'grpc'] as const) {
		const cs = calls(proto, 6, 5);
		const reqFields = cs.map((c) => c.reqHpack!);
		const resFields = cs.flatMap((c) => [c.resHpack!, ...(c.trailerHpack ? [c.trailerHpack] : [])]);
		for (const fields of [reqFields, resFields]) {
			const blocks = fields.map((x) => hex(x.flatMap((f) => f.bytes)));
			const got = JSON.parse(execFileSync('python3', ['-c', 'import json, sys\nfrom hpack import Decoder\nd = Decoder()\nprint(json.dumps([[list(x) for x in d.decode(bytes.fromhex(b))] for b in json.loads(sys.stdin.read())]))'], { input: JSON.stringify(blocks) }).toString());
			assert.deepEqual(got, fields.map((x) => x.map((f) => [f.name, f.value])), `${proto}: decoded headers differ`);
		}
	}
});

test("the order message encodes to exactly the bytes Google's protobuf runtime writes, and each gRPC message carries a 5-byte prefix", { skip: !has('google.protobuf') && 'python protobuf is not installed' }, () => {
	const cases = [0, 1, 3, 20, 120].map((n) => ({ schema: ORDER, obj: makeOrder(n) })).concat([{ schema: GET_REQ, obj: { id: 8120 } as any }]);
	const want = JSON.parse(execFileSync('python3', [fileURLToPath(new URL('./protobuf_ref.py', import.meta.url))], { input: JSON.stringify({ mode: 'encode', cases }) }).toString());
	cases.forEach((c, i) => assert.equal(hex(pbEncode(c.schema, c.obj as Record<string, unknown>)), want[i], `${c.schema.name} ${i}`));
	for (const c of calls('grpc', 1, 5)) {
		assert.equal(c.req.find((p) => p.label.startsWith('gRPC message prefix'))?.bytes, 5);
		assert.equal(c.res.find((p) => p.label.startsWith('gRPC message prefix'))?.bytes, 5);
	}
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published