Two things the release run surfaced, neither of them visible from CI. `npm run typecheck:bench` has been failing since serveDeno and serveBun became async: the bench servers gained a top-level await, which `module: commonjs` rejects outright, and bench/tsconfig.json inherited commonjs from the root config it extends. The servers are ES modules run by tsx, Deno and Bun and never by the CommonJS build, so the config was describing the wrong thing even before the await arrived. CI runs `typecheck`, not `typecheck:bench`, which is why a break in the harness waited for someone to run it by hand. The date came from the runner's clock through toISOString, which is UTC. The table was measured on the evening of the 22nd over ssh against a box keeping UTC and dated itself the 23rd, a day ahead of the commit and of the changelog entry it sits beside. It now reads project time. tsx transpiles with this tsconfig too, so the module change was verified by running the smoke pass again on that box: all six frameworks, the secure run and all three runtimes still boot, and the regenerated header reads 2026-09-22. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
247 lines
9.2 KiB
TypeScript
247 lines
9.2 KiB
TypeScript
import autocannon from 'autocannon';
|
|
import { spawn, execSync } from 'child_process';
|
|
import os from 'os';
|
|
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
|
import { aggregate } from './stats';
|
|
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
|
|
|
/** Hand-written notes start here and are carried across regenerations verbatim. */
|
|
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
|
|
|
|
const SMOKE = process.env.BENCH_SMOKE === '1';
|
|
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
|
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
|
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
|
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
|
|
|
/** Whether a runtime is on PATH. */
|
|
function which(cmd: string): boolean {
|
|
try {
|
|
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function log(msg: string): void {
|
|
process.stderr.write(`[bench] ${msg}\n`);
|
|
}
|
|
|
|
interface RunResult {
|
|
reqSec: number;
|
|
p50: number;
|
|
p99: number;
|
|
p999: number;
|
|
}
|
|
|
|
/**
|
|
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
|
|
* are handed to their own runtime, which is the whole point of measuring them.
|
|
*/
|
|
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
|
|
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
|
|
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
|
|
// missing flag fails as a boot timeout that reads like a framework problem.
|
|
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
|
|
bun: (file) => ({ cmd: 'bun', args: [file] }),
|
|
};
|
|
|
|
async function spawnServer(
|
|
name: string,
|
|
extraEnv: Record<string, string> = {},
|
|
runtime: 'node' | 'deno' | 'bun' = 'node',
|
|
): Promise<{ port: number; kill: () => Promise<void> }> {
|
|
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
|
|
const child = spawn(cmd, args, {
|
|
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
|
});
|
|
let stderr = '';
|
|
child.stderr.on('data', (d) => (stderr += d));
|
|
const port = await new Promise<number>((resolve, reject) => {
|
|
const t = setTimeout(() => {
|
|
child.kill('SIGKILL');
|
|
reject(new Error(`${name} failed to boot (no READY in 10s):\n${stderr}`));
|
|
}, 10000);
|
|
let buf = '';
|
|
child.stdout.on('data', (d) => {
|
|
buf += d;
|
|
const m = /READY (\d+)/.exec(buf);
|
|
if (m) {
|
|
clearTimeout(t);
|
|
resolve(Number(m[1]));
|
|
}
|
|
});
|
|
child.on('exit', (code) => {
|
|
clearTimeout(t);
|
|
reject(new Error(`${name} exited early (code ${code}):\n${stderr}`));
|
|
});
|
|
});
|
|
const kill = (): Promise<void> =>
|
|
new Promise<void>((resolve) => {
|
|
child.on('exit', () => resolve());
|
|
child.kill('SIGTERM');
|
|
setTimeout(() => {
|
|
try {
|
|
child.kill('SIGKILL');
|
|
} catch {
|
|
/* already dead */
|
|
}
|
|
}, 2000);
|
|
});
|
|
return { port, kill };
|
|
}
|
|
|
|
async function bench(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult> {
|
|
const r: any = await autocannon({
|
|
url: `http://127.0.0.1:${port}${path}`,
|
|
connections: CONNS,
|
|
duration: DURATION,
|
|
pipelining: 1,
|
|
method,
|
|
headers: body ? { 'content-type': 'application/json' } : undefined,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
return { reqSec: r.requests.average, p50: r.latency.p50, p99: r.latency.p99, p999: r.latency.p99_9 };
|
|
}
|
|
|
|
async function measure(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult[]> {
|
|
for (let i = 0; i < WARMUP; i++) await bench(port, path, method, body); // discarded
|
|
const runs: RunResult[] = [];
|
|
for (let i = 0; i < RUNS; i++) runs.push(await bench(port, path, method, body));
|
|
return runs;
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const frameworks = ['raw-http', 'fastify', 'express', 'green-tea', 'nestjs-express', 'nestjs-fastify'];
|
|
const scenarioBlocks: ScenarioBlock[] = SCENARIOS.map((s) => ({
|
|
title: s.title,
|
|
name: s.name,
|
|
approximation: s.approximation,
|
|
rows: [],
|
|
}));
|
|
const stepScaling: RenderData['stepScaling'] = [];
|
|
const secureCost: RenderData['secureCost'] = [];
|
|
const runtimes: RenderData['runtimes'] = [];
|
|
|
|
for (const fw of frameworks) {
|
|
log(`booting ${fw}`);
|
|
const { port, kill } = await spawnServer(fw);
|
|
try {
|
|
for (const s of SCENARIOS) {
|
|
log(`${fw} / ${s.name}`);
|
|
const runs = await measure(port, s.path, s.method, s.body);
|
|
const agg = aggregate(runs.map((r) => r.reqSec));
|
|
const last = runs[runs.length - 1];
|
|
const row: Row = {
|
|
framework: fw,
|
|
reqSec: { median: agg.median, min: agg.min, max: agg.max, stddev: agg.stddev, cv: agg.cv },
|
|
p50: last.p50,
|
|
p99: last.p99,
|
|
p999: last.p999,
|
|
};
|
|
scenarioBlocks.find((b) => b.name === s.name)!.rows.push(row);
|
|
}
|
|
if (fw === 'green-tea') {
|
|
for (const sr of STEP_ROUTES) {
|
|
const runs = await measure(port, sr.path, 'GET');
|
|
stepScaling.push({ path: sr.path, steps: sr.steps, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
|
}
|
|
// Reuse the hello scenario's already-computed median so the parity row exactly matches
|
|
// the green-tea hello-table number (rather than re-measuring the same server/config).
|
|
const helloMedian = scenarioBlocks
|
|
.find((b) => b.name === 'hello')!
|
|
.rows.find((r) => r.framework === 'green-tea')!.reqSec.median;
|
|
secureCost.push({ label: 'security:false (parity)', reqSec: helloMedian });
|
|
}
|
|
} finally {
|
|
await kill();
|
|
}
|
|
}
|
|
|
|
log('booting green-tea (GT_SECURE=1)');
|
|
{
|
|
const { port, kill } = await spawnServer('green-tea', { GT_SECURE: '1' });
|
|
try {
|
|
secureCost.push({
|
|
label: 'security:true (default)',
|
|
reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
|
|
});
|
|
} finally {
|
|
await kill();
|
|
}
|
|
}
|
|
|
|
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
|
|
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
|
|
// fastify-on-Node would read as a comparison nobody made.
|
|
//
|
|
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
|
|
// runtime is not installed — a contributor without Bun should still get every other table.
|
|
for (const { runtime, server } of [
|
|
{ runtime: 'node', server: 'green-tea-node' },
|
|
{ runtime: 'deno', server: 'green-tea-deno' },
|
|
{ runtime: 'bun', server: 'green-tea-bun' },
|
|
] as const) {
|
|
if (runtime !== 'node' && !which(runtime)) {
|
|
log(`skipping ${runtime}: not installed`);
|
|
continue;
|
|
}
|
|
|
|
log(`booting green-tea on ${runtime}`);
|
|
|
|
try {
|
|
const { port, kill } = await spawnServer(server, {}, runtime);
|
|
|
|
try {
|
|
for (const s of SCENARIOS) {
|
|
const runs = await measure(port, s.path, s.method, s.body);
|
|
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
|
}
|
|
} finally {
|
|
await kill();
|
|
}
|
|
} catch (error) {
|
|
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
|
|
// of the run over.
|
|
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
|
|
}
|
|
}
|
|
|
|
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
|
const data: RenderData = {
|
|
env: {
|
|
// Project time, not the runner's. A benchmark is often driven over ssh against a box that
|
|
// keeps UTC, and a run made on the evening of the 22nd then dates itself the 23rd — which
|
|
// reads as a day of drift against the commit and the changelog entry beside it.
|
|
date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }),
|
|
commit,
|
|
node: process.version,
|
|
os: os.platform(),
|
|
cpu: `${os.cpus()[0].model} (${os.cpus().length} cores)`,
|
|
ram: `${Math.round(os.totalmem() / 1e9)} GB`,
|
|
pinned: false,
|
|
},
|
|
config: { conns: CONNS, duration: DURATION, runs: RUNS, warmup: WARMUP, pipelining: 1 },
|
|
scenarios: scenarioBlocks,
|
|
stepScaling,
|
|
secureCost,
|
|
runtimes,
|
|
};
|
|
// Everything below the marker is written by hand and survives a re-run. The generated tables
|
|
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
|
|
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
|
|
// history this file exists to keep gets lost a second time.
|
|
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
|
|
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
|
|
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
|
|
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
|
log('wrote BENCHMARKS.md + bench/results.json');
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|