diff --git a/bench/compare.ts b/bench/compare.ts new file mode 100644 index 0000000..4b0d46a --- /dev/null +++ b/bench/compare.ts @@ -0,0 +1,270 @@ +/** + * Compares green-tea against an earlier green-tea, on one box, in one sitting. + * + * `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release + * actually has to pass: **did the last N commits cost anything.** It is a different measurement and + * it needs a different setup, because comparing today's numbers against a table generated weeks ago + * compares two machines-in-a-mood, not two versions. + * + * Usage: + * + * git worktree add /tmp/base v26.8.0-beta.1 + * ln -s "$PWD/node_modules" /tmp/base/node_modules + * AB_BASE=/tmp/base npm run bench:compare + * + * The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has + * not moved between the two revisions — check that first, or the comparison is measuring a + * dependency bump. + * + * Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100), + * `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json). + */ +import autocannon from 'autocannon'; +import { spawn } from 'child_process'; +import { writeFileSync } from 'fs'; + +const DURATION = Number(process.env.AB_DURATION ?? 10); +const ROUNDS = Number(process.env.AB_ROUNDS ?? 3); +const CONNS = Number(process.env.AB_CONNS ?? 100); + +const HEAD = process.cwd(); +// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables. +const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare'; +const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare'; + +function requireBase(): string { + const base = process.env.AB_BASE; + if (base) return base; + console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.'); + process.exit(1); +} + +const BASE = requireBase(); + +interface Case { + name: string; + path: string; + method?: 'GET' | 'POST' | 'OPTIONS'; + body?: unknown; + headers?: Record; + env?: Record; +} + +const ORIGIN = { origin: 'http://bench.example' }; + +const CASES: Case[] = [ + { name: 'hello', path: '/hello' }, + { name: 'param', path: '/users/42' }, + { name: 'pipeline (3 steps)', path: '/pipeline' }, + { name: 'steps5', path: '/steps/5' }, + { name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } }, + { name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } }, + // The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets + // the header measures the path around it rather than the path through it. + { name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN }, + { + name: 'preflight + cors predicate', + path: '/hello', + method: 'OPTIONS', + env: { GT_CORS: '1' }, + headers: { ...ORIGIN, 'access-control-request-method': 'GET' }, + }, + // Route-table width. Every matcher cost scales with the number of candidates a request walks + // past, and the cross-framework table has six routes — so a change that saves work per candidate + // measures as noise there no matter how real it is. `/users/:id` is registered last and is not + // all-static, so it takes the full scan rather than the early exit a literal path gets. + { name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } }, + { name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } }, +]; + +const ONLY = process.env.AB_ONLY; +const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES; + +function log(m: string): void { + process.stderr.write(`[compare] ${m}\n`); +} + +async function boot(cwd: string, env: Record, server = 'compare'): Promise<{ port: number; kill: () => Promise }> { + const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], { + cwd, + env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env }, + }); + let stderr = ''; + child.stderr.on('data', (d) => (stderr += d)); + const port = await new Promise((resolve, reject) => { + const t = setTimeout(() => { + child.kill('SIGKILL'); + reject(new Error(`no READY in 15s:\n${stderr}`)); + }, 15000); + 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', (c) => { + clearTimeout(t); + reject(new Error(`exited ${c}:\n${stderr}`)); + }); + }); + const kill = (): Promise => + new Promise((r) => { + child.on('exit', () => r()); + child.kill('SIGTERM'); + setTimeout(() => { + try { + child.kill('SIGKILL'); + } catch { + /* already dead */ + } + }, 2000); + }); + return { port, kill }; +} + +async function hit(port: number, c: Case, warmup = false): Promise { + const r = (await autocannon({ + url: `http://127.0.0.1:${port}${c.path}`, + connections: CONNS, + duration: DURATION, + pipelining: 1, + method: (c.method ?? 'GET') as 'GET', + headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers }, + body: c.body ? JSON.stringify(c.body) : undefined, + })) as unknown as { + requests: { average: number }; + non2xx?: number; + errors?: number; + timeouts?: number; + }; + + // A case whose route 404s still posts a req/s number, and a run whose connections all errored + // posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this + // case claims to send before believing any of it. + // Not on the warmup: a cold server drops a handful of connections from the opening burst, and + // absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise + // it exists to discard. + if (!warmup) { + const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0); + if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`); + if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`); + } + + return r.requests.average; +} + +const median = (xs: number[]): number => { + const s = [...xs].sort((a, b) => a - b); + const m = s.length >> 1; + return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; +}; + +/** + * True when the two sides' sample ranges do not overlap at all. + * + * A weak signal on its own and stated as such: with three samples a pair of overlapping + * distributions separates by chance often enough to fool you, which it did the first time this was + * run. Treat a flagged row as "measure it again with more rounds", never as a result. + */ +const separated = (a: number[], b: number[]): boolean => { + const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)]; + return x[0] > y[y.length - 1] || y[0] > x[x.length - 1]; +}; + +/** + * Counts `cors.origins` invocations for one cross-origin GET and one preflight. + * + * Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved + * are invisible in req/s — but the option takes a function so it can be a lookup, and there the + * same saving is a network round trip. + */ +async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> { + const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server); + const base = `http://127.0.0.1:${port}`; + // The read carries no `Origin`, so asking cannot change the answer. + const read = async (): Promise => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls; + + try { + const before = await read(); + await fetch(`${base}/hello`, { headers: ORIGIN }); + const afterGet = await read(); + await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } }); + const afterPreflight = await read(); + return { get: afterGet - before, preflight: afterPreflight - afterGet }; + } finally { + await kill(); + } +} + +async function main(): Promise { + const samples: Record = {}; + for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] }; + + for (let round = 0; round < ROUNDS; round++) { + // Alternate which side goes first. Thermal drift and background load over a half-hour run are + // real; alternating spreads them across both sides instead of charging them to whichever went + // second. + const order: Array<['base' | 'head', string]> = + round % 2 === 0 + ? [ + ['base', BASE], + ['head', HEAD], + ] + : [ + ['head', HEAD], + ['base', BASE], + ]; + + for (const [side, cwd] of order) { + for (const c of RUN_CASES) { + const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER); + try { + await hit(port, c, true); // warmup, discarded + const v = await hit(port, c); + samples[c.name][side].push(v); + log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`); + } finally { + await kill(); + } + } + } + } + + const rows = RUN_CASES.map((c) => { + const b = median(samples[c.name].base); + const h = median(samples[c.name].head); + return { + name: c.name, + base: b, + head: h, + delta: ((h - b) / b) * 100, + separated: separated(samples[c.name].base, samples[c.name].head), + samples: samples[c.name], + }; + }); + + const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) }; + + writeFileSync( + process.env.AB_OUT ?? 'bench/compare-results.json', + JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2), + ); + + const f = (n: number): string => Math.round(n).toLocaleString(); + console.log('\n| Scenario | base | head | Δ | |'); + console.log('| --- | --- | --- | --- | --- |'); + for (const r of rows) { + const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps'; + console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`); + } + console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`); + console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/bench/render.ts b/bench/render.ts index f6cf4ab..8803c3d 100644 --- a/bench/render.ts +++ b/bench/render.ts @@ -37,6 +37,8 @@ export interface RenderData { scenarios: ScenarioBlock[]; stepScaling: { path: string; steps: number; reqSec: number }[]; secureCost: { label: string; reqSec: number }[]; + /** Optional: results captured before the runtime matrix existed still render. */ + runtimes?: { runtime: string; scenario: string; reqSec: number }[]; } const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US'); @@ -124,6 +126,33 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string { return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n'); } +/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */ +function renderRuntimes(runtimes: RenderData['runtimes']): string { + if (!runtimes?.length) return ''; + + const names = [...new Set(runtimes.map((row) => row.runtime))]; + const scenarios = [...new Set(runtimes.map((row) => row.scenario))]; + const at = (runtime: string, scenario: string): number | undefined => + runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec; + + const header = `| Scenario | ${names.join(' | ')} |`; + const divider = `| --- | ${names.map(() => '---').join(' | ')} |`; + const lines = scenarios.map((scenario) => { + const cells = names.map((runtime) => { + const value = at(runtime, scenario); + return value === undefined ? '—' : fmtInt(value); + }); + return `| ${scenario} | ${cells.join(' | ')} |`; + }); + + const note = + 'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' + + 'never against the cross-framework tables above: those measure other frameworks on Node, and ' + + 'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.'; + + return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n'); +} + function renderSecureCost(secureCost: RenderData['secureCost']): string { const header = '| Label | req/s |'; const divider = '| --- | --- |'; @@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string { } export function renderMarkdown(data: RenderData): string { - const { env, config, scenarios, stepScaling, secureCost } = data; + const { env, config, scenarios, stepScaling, secureCost, runtimes } = data; return [ renderLeaderboard(scenarios), @@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string { '', renderScenarios(scenarios), renderStepScaling(stepScaling), + renderRuntimes(runtimes), renderSecureCost(secureCost), renderMethodology(), ].join('\n'); diff --git a/bench/run.ts b/bench/run.ts index cf4398b..d913849 100644 --- a/bench/run.ts +++ b/bench/run.ts @@ -1,17 +1,30 @@ import autocannon from 'autocannon'; import { spawn, execSync } from 'child_process'; import os from 'os'; -import { writeFileSync } from 'fs'; +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 = ''; + 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`); } @@ -23,11 +36,25 @@ interface RunResult { 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 { 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 = {}, + runtime: 'node' | 'deno' | 'bun' = 'node', ): Promise<{ port: number; kill: () => Promise }> { - const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], { + 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 = ''; @@ -96,6 +123,7 @@ async function main(): Promise { })); const stepScaling: RenderData['stepScaling'] = []; const secureCost: RenderData['secureCost'] = []; + const runtimes: RenderData['runtimes'] = []; for (const fw of frameworks) { log(`booting ${fw}`); @@ -145,6 +173,42 @@ async function main(): Promise { } } + // 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: { @@ -160,8 +224,15 @@ async function main(): Promise { scenarios: scenarioBlocks, stepScaling, secureCost, + runtimes, }; - writeFileSync('BENCHMARKS.md', renderMarkdown(data)); + // 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'); } diff --git a/bench/servers/compare-dist.ts b/bench/servers/compare-dist.ts new file mode 100644 index 0000000..eec2173 --- /dev/null +++ b/bench/servers/compare-dist.ts @@ -0,0 +1,61 @@ +// A/B bench server. Identical file dropped into both trees, so each side compiles against its own +// `src/`. Adds the two paths the standard bench server does not exercise and this release changed: +// secure-by-default headers, and a `cors.origins` predicate. +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs'; + +const emailSchema = { + '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) => + (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } }, +}; + +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = [1, 2, 3, 4, 5].map(makeStep); + +@Route('/') +class Bench { + @Get('/hello') hello() { return { hello: 'world' }; } + @Get('/users/:id') user(@param('id') id: string) { return { id }; } + @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } + // Reads the counter without resetting it — the read itself carries no Origin, so it cannot + // change what it reports. + @Get('/cors-calls') corsCalls() { return { calls: corsCalls }; } +} + +@Module({ mountpoint: '/', steps, controllers: [Bench] }) +class BenchModule {} + +// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the +// one this release stopped evaluating two and three times per request. +const ALLOWED = new Set(['http://bench.example']); +let corsCalls = 0; +const cors = + process.env.GT_CORS === '1' + ? { + origins: (o: string) => { + corsCalls++; + return ALLOWED.has(o); + }, + } + : undefined; + +const app = createApp({ + modules: [BenchModule], + security: process.env.GT_SECURE === '1', + ...(cors ? { cors } : {}), +}); + +async function main() { + try { if (app.inspect('/hello').length === 0) throw new Error('empty'); } + catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); } + const server = await app.listen(0); + server.keepAliveTimeout = 5000; + console.log(`READY ${(server.address() as any).port}`); +} +main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/bench/servers/compare.ts b/bench/servers/compare.ts new file mode 100644 index 0000000..4ba044b --- /dev/null +++ b/bench/servers/compare.ts @@ -0,0 +1,84 @@ +// A/B bench server. Identical file dropped into both trees, so each side compiles against its own +// `src/`. Adds the two paths the standard bench server does not exercise and this release changed: +// secure-by-default headers, and a `cors.origins` predicate. +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index'; + +type Ctor = new (...args: any[]) => any; + +const emailSchema = { + '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) => + (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } }, +}; + +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = [1, 2, 3, 4, 5].map(makeStep); + +@Route('/') +class Bench { + @Get('/hello') hello() { return { hello: 'world' }; } + @Get('/users/:id') user(@param('id') id: string) { return { id }; } + @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } + // Reads the counter without resetting it — the read itself carries no Origin, so it cannot + // change what it reports. + @Get('/cors-calls') corsCalls() { return { calls: corsCalls }; } +} + +// Filler routes, so the width of the route table becomes a dimension the harness can see. +// +// Every matcher cost discussed for this file — the specificity scan, the per-candidate +// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate +// routes a request has to walk past. At the six routes the cross-framework table uses, all of them +// measure as noise, which says nothing about them and everything about the instrument. `/users/:id` +// is declared last so a request for it pays the full scan. +function fillerRoutes(count: number): Ctor[] { + return Array.from({ length: count }, (_, i) => { + @Route(`/filler${i}`) + class Filler { + @Get('/:a/:b') ab(@param('a') a: string) { + return { a }; + } + } + return Filler as Ctor; + }); +} + +const EXTRA = Number(process.env.GT_ROUTES ?? 0); + +@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] }) +class BenchModule {} + +// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the +// one this release stopped evaluating two and three times per request. +const ALLOWED = new Set(['http://bench.example']); +let corsCalls = 0; +const cors = + process.env.GT_CORS === '1' + ? { + origins: (o: string) => { + corsCalls++; + return ALLOWED.has(o); + }, + } + : undefined; + +const app = createApp({ + modules: [BenchModule], + security: process.env.GT_SECURE === '1', + ...(cors ? { cors } : {}), +}); + +async function main() { + try { if (app.inspect('/hello').length === 0) throw new Error('empty'); } + catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); } + const server = await app.listen(0); + server.keepAliveTimeout = 5000; + console.log(`READY ${(server.address() as any).port}`); +} +main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/bench/servers/green-tea-node.ts b/bench/servers/green-tea-node.ts new file mode 100644 index 0000000..732f107 --- /dev/null +++ b/bench/servers/green-tea-node.ts @@ -0,0 +1,47 @@ +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs'; + + +// Same BenchModule as green-tea.ts, but loaded from `dist/` rather than `src/`. +// +// The runtimes table exists to vary the runtime. The Deno and Bun servers import the built bundle +// because that is the only form those runtimes can load here, so a Node row reading `src/` through +// tsx would vary the load form at the same time and the table would answer neither question. +const emailSchema = { + '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) => + (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } }, +}; + +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = [1, 2, 3, 4, 5].map(makeStep); + +@Route('/') +class Bench { + @Get('/hello') hello() { return { hello: 'world' }; } + @Get('/users/:id') user(@param('id') id: string) { return { id }; } + @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/steps/0') steps0() { return { hello: 'world' }; } + @Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } +} + +@Module({ mountpoint: '/', steps, controllers: [Bench] }) +class BenchModule {} + +const app = createApp({ modules: [BenchModule], security: false }); + +async function main(): Promise { + const server = await app.listen(0); + server.keepAliveTimeout = 5000; // parity value (all servers use 5000) + console.log(`READY ${(server.address() as { port: number }).port}`); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/package.json b/package.json index e1a816d..7196497 100644 --- a/package.json +++ b/package.json @@ -102,6 +102,7 @@ "complexity:check": "node scripts/check-complexity.mjs", "complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25", "bench": "tsx bench/run.ts", + "bench:compare": "tsx bench/compare.ts", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build", "prepare": "git config core.hooksPath .githooks || true" }, diff --git a/test/bench-render.test.ts b/test/bench-render.test.ts index 5546fd9..9980d10 100644 --- a/test/bench-render.test.ts +++ b/test/bench-render.test.ts @@ -76,3 +76,46 @@ describe('renderMarkdown', () => { expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k) }); }); + +describe('renderMarkdown runtime matrix', () => { + const base = { + env: { date: '2026-09-01', commit: 'abc1234', node: 'v22', os: 'darwin', cpu: 'M4', ram: '69 GB', pinned: false }, + config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 }, + scenarios: [], + stepScaling: [], + secureCost: [], + }; + + it('renders one column per runtime and one row per scenario', () => { + const md = renderMarkdown({ + ...base, + runtimes: [ + { runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 }, + { runtime: 'bun', scenario: 'JSON hello', reqSec: 120_000 }, + ], + } as never); + + expect(md).toContain('## green-tea across runtimes'); + expect(md).toContain('| Scenario | node | bun |'); + expect(md).toContain('| JSON hello | 90,000 | 120,000 |'); + }); + + it('marks a runtime that produced no number rather than printing a zero', () => { + // A skipped runtime must not read as "it ran and scored nothing". + const md = renderMarkdown({ + ...base, + runtimes: [ + { runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 }, + { runtime: 'deno', scenario: 'Route param', reqSec: 80_000 }, + ], + } as never); + + expect(md).toContain('| JSON hello | 90,000 | — |'); + expect(md).toContain('| Route param | — | 80,000 |'); + }); + + it('omits the section entirely when no runtime was measured', () => { + expect(renderMarkdown({ ...base, runtimes: [] } as never)).not.toContain('across runtimes'); + expect(renderMarkdown(base as never)).not.toContain('across runtimes'); + }); +});