4 Commits
Author SHA1 Message Date
chrnx 7ccb55d07a Merge pull request 'Route ranking at build time, and a benchmark that can measure a release' (#87) from perf/matcher-and-benchmarks into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 31s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-02 03:07:37 +00:00
chrnx e61771077c docs(bench): refresh the tables and record what moved between releases
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
The tables were measured on 2026-07-07 at `fe1831a`, two releases ago. Re-measured at
`8c5855c` with the runtime matrix included, every row under 1.2% CV.

The headline is not in the cross-framework tables. green-tea sits within 2% of fastify on
`hello` and `param` and second only to `raw-http` on `validate` — but the same application
on Deno serves 153,408 req/s against Node's 90,976, and on Bun 131,674. Node's own `http`
module with no framework manages 119,357. The runtime-neutral boundary that costs on Node
is what makes those rows possible, and until this run nothing measured them.

The notes below the marker say what a table cannot. In order: the release gate — this
release is neutral against `26.8.0-beta.1` on every scenario but the CORS preflight, which
gains 2.7%; the interval against `26.7`, which is roughly −5% to −8% and is **not** a
regression, because July matched routes by splitting a string in one flat file and had no
constraints, no specificity, no correlation and one adapter; the figures recorded in the
code when each change landed, including one that reached 45% of a request before it was
fixed; and what is still unattributed, which is most of it.

That last part is the point. Three candidates were measured and none of them explain the
interval: `randomUUID` is 0.7% and lands within noise, replacing specificity ranking with
July's first-match-wins is noise, and the bundle versus the source is noise. A section that
explained everything would be a defence. This one says what was found and what was not.

The measurements were always there — `core.ts`, `bus.ts`, `pipeline.ts`, `headers.ts`,
`body.ts`, `router.ts` all carry them, with alternatives compared and rejected. They cite
different baselines, 4.4 µs to 10.19 µs, because each was taken against whatever a request
cost that day, so they cannot be added up. What was missing was never rigour. It was a
number per version against a fixed baseline, in the file where the question gets asked.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 21:26:27 -05:00
chrnx 9c78842684 test(bench): measure a release against the last one, and every runtime it claims
`BENCHMARKS.md` answered "how does this compare to fastify" and nothing answered "did the
last two months cost anything". Those are different questions and the second one is the
one a release has to pass, so it needed its own tool rather than a second reading of the
first one's table.

`npm run bench:compare` runs two worktrees of this repository against each other on one
box in one sitting, alternating which side goes first each round so drift lands on both
rather than on whichever ran second. It shares one `node_modules` and one byte-identical
server file, which holds everything except `src/` constant — and is only sound while
`package.json` has not moved between the revisions, which the header says out loud.

Three things it refuses to do quietly, each of which it did once before being taught not
to:

- A run whose connections all errored reports 0 req/s, and a median absorbs that without
  complaint. Non-2xx, errors and timeouts now fail the case, and so does a zero. Not on
  the warmup, which exists to absorb exactly the cold-start noise a fresh server produces.
- A range-overlap check flags a row as directional, and its own documentation says to
  treat that as "measure it again", never as a result. Three samples of two overlapping
  distributions separate by chance often enough to have produced a regression report that
  five rounds then erased.
- `cors.origins` invocations are counted rather than timed. The benchmark's predicate is a
  `Set` lookup, 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.

**The runtime servers finally run.** `bench/servers/green-tea-deno.ts` and `-bun.ts` were
written in July and referenced by nothing — not the runner, not a script, not CI. The
runner only knew how to launch Node, so both sat there looking like coverage the table did
not have. Launchers are per runtime now and they get their own section, kept out of the
cross-framework tables because a green-tea-on-Bun row beside fastify-on-Node reads as a
comparison nobody made.

`green-tea-node.ts` is new and loads `dist/` like its Deno and Bun counterparts. The
runtimes table exists to vary the runtime, and a Node row reading `src/` through tsx would
have varied the load form at the same time.

A route-table-width dimension, because every matcher cost scales with how many candidates
a request walks past and the tables here use six routes. Three separate matcher findings
measured as noise before this existed, which said nothing about them and everything about
the instrument.

Finally, `run.ts` preserves whatever sits below a marker instead of overwriting the file
whole. The tables answer what is true today; the notes below them carry which release moved
a number and what the move bought, and regenerating used to delete that silently.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 21:26:11 -05:00
chrnx 8c5855c59e perf(router): settle route ranking when the table is built, not per request
Route matching scanned every method-matching route on every request and ranked the
candidates as it went, calling `moreSpecific` — two `compilePattern` lookups each — per
candidate. Both the scan and the ranking scale with the size of the route table, and the
answer they compute cannot change between requests: the table is assembled once, after the
graph is prepared, and handed to the adapter unchanged.

So the ranking moves to where the table is built. Routes are compiled, bucketed by method
and sorted most-specific-first, and matching walks until the first match and returns it.
`sort` is stable, so patterns of equal specificity keep registration order — which is what
the old scan produced by refusing to replace its best on a tie.

Measured on a request to a parameterised route registered last, against the same tree
without these changes, medians of five and seven rounds:

      6 routes      no change (every row overlaps)
     50 routes      +3.3%, +3.5% across two runs
    200 routes      +14.9%, +12.0% — twelve rounds, not one crossing sample

The shape is the point rather than any single number: the saving is proportional to how
many candidates a request walks past, so it is invisible on a small table by construction.
That is also why it went unnoticed. The benchmark had no route-table-width dimension until
this commit added one, so every matcher change measured as noise no matter how real.

Two smaller savings on the same path. `decodeSegment` now skips `decodeURIComponent` when
the segment holds no `%`, the same gate `normalizeRequestPath` already applies to the whole
path for the same reason. And decoding memoizes per request rather than per candidate: a
scan reaching the same parameter position on several routes used to decode the same string
once per route, and position is all decoding depends on.

`allStatic` is deleted. It short-circuited the scan on an all-literal match, which sorting
subsumes — such a pattern now sorts first and wins by position.

The index is keyed by the identity of the route array, so it is built once and collected
with the table it describes. A table assembled fresh — mesh splicing a teapot's exports in
at boot — is a different array and gets its own index, so no caller has to invalidate
anything.

`matchRoute precedence` already covered the ordering this rewrite had to preserve, and it
passes unchanged. Two cases were missing and are added: that equal specificity keeps
registration order, which is the property the stable sort now carries, and that a parameter
decodes to the same value however many candidates the scan walks. Both pass against the
previous implementation too — they describe behaviour that already existed, which is what
makes them evidence the rewrite preserved it rather than evidence of the change.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 15:48:01 -05:00
12 changed files with 1075 additions and 216 deletions

No files matched your search

+161 -34
View File
@@ -4,14 +4,14 @@
## Environment ## Environment
- **Date**: 2026-07-07 - **Date**: 2026-09-02
- **Commit**: fe1831a - **Commit**: 8c5855c
- **Node**: v22.22.2 - **Node**: v22.22.2
- **OS**: darwin - **OS**: darwin
- **CPU**: Apple M4 Max (16 cores) - **CPU**: Apple M4 Max (16 cores)
- **RAM**: 69 GB - **RAM**: 69 GB
- **Core-pinned**: no - **Core-pinned**: no
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1 - **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over > **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
> loopback on the same machine, sharing the same cores as the server processes they measured. That > loopback on the same machine, sharing the same cores as the server processes they measured. That
@@ -29,64 +29,74 @@
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 | | raw-http | 119,357 | 0.00 | 1.00 | 1.00 | 0.4% | 118,560–120,067 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 | | nestjs-fastify | 98,039 | 0.00 | 1.00 | 2.00 | 1.2% | 96,073–99,680 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 | | fastify | 89,097 | 1.00 | 1.00 | 2.00 | 0.1% | 88,864–89,207 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 | | green-tea | 87,473 | 1.00 | 2.00 | 2.00 | 0.3% | 86,903–87,607 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 | | express | 24,677 | 3.00 | 5.00 | 8.00 | 0.2% | 24,647–24,769 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 | | nestjs-express | 21,879 | 4.00 | 6.00 | 9.00 | 0.2% | 21,845–21,953 |
### Route param ### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 | | raw-http | 120,905 | 0.00 | 1.00 | 1.00 | 0.5% | 119,927–121,713 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 | | nestjs-fastify | 91,849 | 1.00 | 1.00 | 2.00 | 0.3% | 91,825–92,599 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 | | fastify | 88,317 | 1.00 | 1.00 | 2.00 | 0.2% | 87,997–88,439 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 | | green-tea | 86,595 | 1.00 | 2.00 | 2.00 | 0.2% | 86,368–86,880 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 | | express | 24,200 | 3.00 | 5.00 | 8.00 | 0.2% | 24,158–24,260 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 | | nestjs-express | 21,182 | 4.00 | 6.00 | 9.00 | 0.7% | 21,150–21,518 |
### Pipeline (3 steps) (approximation) ### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 | | raw-http | 118,996 | 0.00 | 1.00 | 1.00 | 0.3% | 118,583–119,584 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 | | nestjs-fastify | 89,527 | 1.00 | 2.00 | 2.00 | 1.0% | 87,572–90,028 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 | | fastify | 86,671 | 1.00 | 1.00 | 2.00 | 0.1% | 86,490–86,793 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 | | green-tea | 80,079 | 1.00 | 2.00 | 2.00 | 0.2% | 80,026–80,375 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 | | express | 24,325 | 3.00 | 5.00 | 8.00 | 0.2% | 24,281–24,407 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 | | nestjs-express | 20,872 | 4.00 | 6.00 | 9.00 | 0.2% | 20,801–20,940 |
### POST JSON + validation ### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 | | raw-http | 104,288 | 0.00 | 1.00 | 1.00 | 0.4% | 103,776–104,916 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 | | green-tea | 70,298 | 1.00 | 2.00 | 3.00 | 1.0% | 68,972–70,607 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 | | fastify | 65,905 | 1.00 | 2.00 | 3.00 | 0.3% | 65,725–66,367 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 | | nestjs-fastify | 63,318 | 1.00 | 2.00 | 3.00 | 0.9% | 62,454–63,747 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 | | express | 20,297 | 4.00 | 6.00 | 10.00 | 0.5% | 20,158–20,414 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 | | nestjs-express | 18,788 | 5.00 | 7.00 | 10.00 | 0.3% | 18,684–18,862 |
## Step-scaling (green-tea) ## Step-scaling (green-tea)
| Path | Steps | req/s | | Path | Steps | req/s |
| --- | --- | --- | | --- | --- | --- |
| /steps/0 | 0 | 92,282 | | /steps/0 | 0 | 88,108 |
| /steps/3 | 3 | 81,530 | | /steps/3 | 3 | 79,951 |
| /steps/5 | 5 | 71,994 | | /steps/5 | 5 | 74,127 |
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box. Each additional pipeline step costs roughly 2,796 req/s (-15.9% over 5 steps), on this box.
## green-tea across runtimes
| Scenario | node | deno | bun |
| --- | --- | --- | --- |
| JSON hello (overhead) | 90,976 | 153,408 | 131,674 |
| Route param | 88,905 | 146,368 | 126,909 |
| Pipeline (3 steps) | 82,045 | 136,256 | 117,489 |
| POST JSON + validation | 72,236 | 106,662 | 95,124 |
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.
## Cost of secure-by-default (green-tea) ## Cost of secure-by-default (green-tea)
| Label | req/s | | Label | req/s |
| --- | --- | | --- | --- |
| security:false (parity) | 98,093 | | security:false (parity) | 87,473 |
| security:true (default) | 92,998 | | security:true (default) | 83,773 |
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box. The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.2% req/s on this box.
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs > Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately > `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
@@ -116,3 +126,120 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters. on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
<!-- keep-below: hand-written, survives `npm run bench` -->
## What moved between releases
These figures were measured per function and never per version. Every change on the request path
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
`npm run bench:compare` exist to close.
### The release gate: `26.8.0-beta.1` → `26.9.0-beta.1`
Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
one `node_modules` and one byte-identical server file. Medians of five rounds:
| Scenario | 26.8.0-beta.1 | 26.9.0-beta.1 | Δ |
| --- | --- | --- | --- |
| hello | 91,343 | 90,371 | −1.1% |
| param | 88,113 | 87,921 | −0.2% |
| pipeline (3 steps) | 80,934 | 80,893 | −0.1% |
| validate (POST) | 72,340 | 72,241 | −0.1% |
| hello + security | 85,967 | 86,426 | +0.5% |
| hello + cors predicate | 82,609 | 83,401 | +1.0% |
| preflight + cors predicate | 112,055 | 115,069 | **+2.7%** |
Every row but the last overlaps between the two sides and is noise. The preflight row does not: the
new tree wins all three rounds, which is where a `cors.origins` predicate stopped being evaluated
three times per request.
That change is a call count, not a rate, and the benchmark's predicate is a `Set` lookup — so the
saving is invisible in req/s here and would be two or three network round trips in the lookup the
option exists for:
| | per cross-origin GET | per preflight |
| --- | --- | --- |
| 26.8.0-beta.1 | 2 | 3 |
| 26.9.0-beta.1 | **1** | **1** |
### Against `26.7`, and why it is not a regression
The table this file carried until today was measured at `fe1831a`, before `26.8.0-beta.1`
shipped. Re-running
that tree today, under the same toolchain and dependencies, gives 94,403 req/s on `hello` and
93,361 on `param` against 89,527 and 85,839 for the current tree — roughly −5% and −8%. Against
`fastify` as a control, which moved +1.2% to +1.8% across the same scenarios, green-tea's ratio to
it fell 6.6% to 11.7%.
**That number is real and it is not a regression, because it is not the same program.** July matched
routes by splitting the path and comparing segments, returning on the first hit, in one flat file.
It had no route constraints, no specificity ranking, no per-request correlation, no lifecycle
stream, and one adapter. It was fast the way something is fast before it does anything.
What the interval bought, in the order it costs: a runtime-neutral request and response boundary,
which is what serves Deno, Bun and workerd from one core rather than one adapter; constraint and
specificity matching; a correlated event stream; and per-request identity.
The first of those is now measurable, because the runtimes table above did not exist either. The
same boundary that costs on Node is what puts the same application on Deno at 153,408 req/s and Bun
at 131,674 against Node's 90,976 — and above the 119,357 that Node's own `http` module manages with
no framework at all. Whether the trade is worth it is the reader's call. This file's job is to say
what it cost and what it bought.
### Figures recorded when each change landed
Measured at the time, in the code, against a microbenchmark rather than this harness:
| Where | Finding |
| --- | --- |
| `src/http/core.ts:63` | a per-request derivation that reached **45% of a whole request** before it was fixed |
| `src/http/core.ts:89` | six request-id generators compared; `crypto.randomUUID` at 76 ns was the fastest cross-runtime option, and the only alternatives that beat it are Node-only |
| `src/http/core.ts:229` | wrapping `dispatch` in a second async frame: 0.43 µs per request |
| `src/bus.ts:173` | spreading request identity into an event payload: ~197 ns on a two-step pipeline |
| `src/pipeline.ts:58` | one timestamp per step boundary instead of two: 25.2 ns against 45.3 ns per step |
| `src/http/headers.ts:30` | 146.4 ns against 55.9 ns for the same header answer |
| `src/http/body.ts:39` | 250 ns per request for a closure and the error context it captured |
| `src/http/router.ts:232` | per-segment decoding on a path nobody decodes: 95.8 ns for `/hello`, 342.7 ns for six segments |
**These do not add up to the release delta, and cannot.** They cite different baselines — 4.4 µs,
4.5 µs, 10.19 µs — because each was taken against whatever a request cost on the day. A dozen
findings in nanoseconds against inconsistent references is a discussion, not a total. A version-level
number measured against a fixed baseline is what was missing, not rigour.
### What is still unattributed
Three candidates for the `26.7` → `26.9` interval were measured and none of them account for it:
- **`crypto.randomUUID` per request** — removing it entirely lands within noise on every scenario,
and one row moves the wrong way. At 76 ns against a ~11 µs request it is ~0.7%, below what a load
test at this CV can resolve.
- **Specificity ranking in the matcher** — replacing it with July's first-match-wins is noise on all
four rows at this route-table size.
- **The bundle versus the TypeScript source** — every row overlaps, so the form the table loads does
not explain it either.
No single culprit was found. The remaining candidates are the neutral request and response objects
and the several small per-request allocations around them, which is a shape that resists a single
measurement.
## What this file does not measure
- **Route-table width was invisible until `26.9`.** Every matcher cost scales with how many
candidates a request walks past, and the cross-framework tables use six routes — so any matcher
change measures as noise there regardless of its size. `npm run bench:compare` carries 50- and
200-route cases for this reason. Settling route ranking when the table is built rather than per
request is worth nothing at six routes, +3.4% at fifty, and **+12% to +14.9% at two hundred**,
across twelve rounds without a crossing sample.
- **Boot time is absent.** Independent providers began booting concurrently in `26.9`: three
providers with no edges and 200 ms of work each went from 616 ms to 210 ms. No table here shows it.
- **Streaming is absent.** Every scenario is a buffered response. SSE framing, the encoder's
per-item work, and the stream lifecycle events are not exercised.
- **The cross-framework tables are Node-only**, and they load green-tea from `src/` through `tsx`
while the other frameworks load their published JavaScript. Measured today, that difference is
within noise — but it is a difference, and the runtimes table above avoids it by loading the built
bundle on all three.
- **The runtimes table compares each runtime's HTTP server, not its JavaScript engine.** `Deno.serve`
and `Bun.serve` are native stacks; Node's `http` is JavaScript. "green-tea on this runtime" is the
claim, and it is the one an application actually experiences.
+270
View File
@@ -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<string, string>;
env?: Record<string, string>;
}
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<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
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<number>((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<void> =>
new Promise<void>((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<number> {
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<number> => ((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<void> {
const samples: Record<string, { base: number[]; head: number[] }> = {};
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);
});
+31 -1
View File
@@ -37,6 +37,8 @@ export interface RenderData {
scenarios: ScenarioBlock[]; scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[]; stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; 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'); 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'); 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 { function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |'; const header = '| Label | req/s |';
const divider = '| --- | --- |'; const divider = '| --- | --- |';
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
} }
export function renderMarkdown(data: RenderData): string { export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data; const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
return [ return [
renderLeaderboard(scenarios), renderLeaderboard(scenarios),
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
'', '',
renderScenarios(scenarios), renderScenarios(scenarios),
renderStepScaling(stepScaling), renderStepScaling(stepScaling),
renderRuntimes(runtimes),
renderSecureCost(secureCost), renderSecureCost(secureCost),
renderMethodology(), renderMethodology(),
].join('\n'); ].join('\n');
+206 -144
View File
@@ -1,7 +1,7 @@
{ {
"env": { "env": {
"date": "2026-07-07", "date": "2026-09-02",
"commit": "fe1831a", "commit": "8c5855c",
"node": "v22.22.2", "node": "v22.22.2",
"os": "darwin", "os": "darwin",
"cpu": "Apple M4 Max (16 cores)", "cpu": "Apple M4 Max (16 cores)",
@@ -10,8 +10,8 @@
}, },
"config": { "config": {
"conns": 100, "conns": 100,
"duration": 5, "duration": 10,
"runs": 3, "runs": 5,
"warmup": 1, "warmup": 1,
"pipelining": 1 "pipelining": 1
}, },
@@ -23,11 +23,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 115398.4, "median": 119357.1,
"min": 114822.4, "min": 118560,
"max": 115539.2, "max": 120066.91,
"stddev": 310.09010876768724, "stddev": 484.9030139151553,
"cv": 0.0026905088104554075 "cv": 0.0040636145553490976
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -36,24 +36,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86764.8, "median": 89096.73,
"min": 86496, "min": 88864,
"max": 87123.2, "max": 89207.28,
"stddev": 256.9227813090051, "stddev": 111.97759400880093,
"cv": 0.002960121758353106 "cv": 0.001257219726589825
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24366.4, "median": 24677.1,
"min": 24283.2, "min": 24646.55,
"max": 24417.6, "max": 24768.73,
"stddev": 55.38455460585383, "stddev": 43.02015834466458,
"cv": 0.002273984274990166 "cv": 0.0017417832565876405
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -62,39 +62,39 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 98092.8, "median": 87473.46,
"min": 98054.4, "min": 86903.28,
"max": 98668.8, "max": 87607.28,
"stddev": 281.0175795212842, "stddev": 280.84365746087286,
"cv": 0.002859589501804015 "cv": 0.0032155347907296527
}, },
"p50": 0, "p50": 1,
"p99": 1, "p99": 2,
"p999": 2 "p999": 2
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 21761.6, "median": 21878.55,
"min": 21697.6, "min": 21845.1,
"max": 21896, "max": 21952.73,
"stddev": 82.67870880032535, "stddev": 41.00873789816055,
"cv": 0.0037952010918943873 "cv": 0.0018731606009975037
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 10 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 95033.6, "median": 98039.28,
"min": 94240, "min": 96072.73,
"max": 95264, "max": 99680,
"stddev": 438.6166536839312, "stddev": 1215.4038343760499,
"cv": 0.00462452048886261 "cv": 0.012396669934655963
}, },
"p50": 1, "p50": 0,
"p99": 1, "p99": 1,
"p999": 2 "p999": 2
} }
@@ -107,11 +107,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 116332.8, "median": 120904.73,
"min": 115974.4, "min": 119927.28,
"max": 116409.6, "max": 121713.46,
"stddev": 189.66281191162406, "stddev": 658.0250991747977,
"cv": 0.001631663389130871 "cv": 0.005441723483024015
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -120,24 +120,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86278.4, "median": 88317.1,
"min": 86137.6, "min": 87997.1,
"max": 86764.8, "max": 88439.28,
"stddev": 268.69839349476365, "stddev": 182.99174422907566,
"cv": 0.003110165492522174 "cv": 0.00207430857941761
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23835.2, "median": 24200,
"min": 23803.2, "min": 24157.82,
"max": 24046.4, "max": 24259.64,
"stddev": 107.89690552662897, "stddev": 39.43298619176589,
"cv": 0.004515472130491916 "cv": 0.0016290899720752198
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -146,11 +146,11 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 93433.6, "median": 86594.91,
"min": 93152, "min": 86368,
"max": 93612.8, "max": 86880,
"stddev": 189.6628119116206, "stddev": 179.11650003279965,
"cv": 0.002030662686635119 "cv": 0.002068552609808656
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -159,27 +159,27 @@
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20955.2, "median": 21181.82,
"min": 20948.8, "min": 21149.82,
"max": 21201.6, "max": 21517.82,
"stddev": 117.69157432317111, "stddev": 139.0670808494951,
"cv": 0.005594982425799189 "cv": 0.006540068168697097
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 11 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 89312, "median": 91848.73,
"min": 89235.2, "min": 91825.46,
"max": 89529.6, "max": 92599.28,
"stddev": 124.68598780759793, "stddev": 296.55679952413783,
"cv": 0.001395338811201841 "cv": 0.00322222064035544
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
} }
] ]
@@ -192,11 +192,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 113491.2, "median": 118996.37,
"min": 112531.2, "min": 118583.28,
"max": 114809.6, "max": 119584,
"stddev": 933.9810324031724, "stddev": 341.82644850274596,
"cv": 0.008220892102882115 "cv": 0.002872466494470492
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -205,24 +205,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 85024, "median": 86670.55,
"min": 84512, "min": 86490.19,
"max": 85177.6, "max": 86792.73,
"stddev": 284.55819947576623, "stddev": 97.03476704769095,
"cv": 0.003351507726431956 "cv": 0.0011197471063834074
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23950.4, "median": 24325.1,
"min": 23902.4, "min": 24281.46,
"max": 24011.2, "max": 24406.55,
"stddev": 44.519758410046, "stddev": 50.44878456414985,
"cv": 0.0018585004345727763 "cv": 0.002073096921615235
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -231,11 +231,11 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 84896, "median": 80078.55,
"min": 84243.2, "min": 80026.19,
"max": 85267.2, "max": 80375.28,
"stddev": 423.2825796347192, "stddev": 126.5427427235537,
"cv": 0.004991414284012342 "cv": 0.00157915416330658
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -244,24 +244,24 @@
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20824, "median": 20872,
"min": 20804.8, "min": 20800.73,
"max": 20878.41, "max": 20940.37,
"stddev": 31.17605954717337, "stddev": 44.78034640330492,
"cv": 0.001496278247605678 "cv": 0.0021458031999967474
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 11 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 87328, "median": 89527.28,
"min": 86867.2, "min": 87572.37,
"max": 87660.8, "max": 90027.64,
"stddev": 325.38753646827104, "stddev": 867.875358507201,
"cv": 0.0037278603866430907 "cv": 0.009726340137622384
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -276,24 +276,24 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 100140.8, "median": 104288,
"min": 99846.4, "min": 103776,
"max": 100294.4, "max": 104916.37,
"stddev": 185.88177843875883, "stddev": 371.6125197245094,
"cv": 0.0018570746103533369 "cv": 0.0035614220793380035
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
"p999": 2 "p999": 1
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 63721.6, "median": 65905.46,
"min": 63574.4, "min": 65725.1,
"max": 63760, "max": 66366.55,
"stddev": 79.99288857281053, "stddev": 217.1439762369652,
"cv": 0.0012560645345785087 "cv": 0.0032914527300013986
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -302,53 +302,53 @@
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 20097.6, "median": 20297.46,
"min": 20056, "min": 20157.82,
"max": 20174.41, "max": 20413.82,
"stddev": 49.04789518646266, "stddev": 99.50819415505447,
"cv": 0.0024390608203285337 "cv": 0.004902635960088364
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 12 "p999": 10
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 77177.61, "median": 70298.19,
"min": 77126.4, "min": 68971.64,
"max": 77254.4, "max": 70606.55,
"stddev": 52.602458962379814, "stddev": 704.8749988359651,
"cv": 0.0006815013839797027 "cv": 0.01008804689681251
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
"p999": 2 "p999": 3
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 18856, "median": 18787.64,
"min": 18852.8, "min": 18684.37,
"max": 19067.2, "max": 18861.82,
"stddev": 100.32338821143516, "stddev": 57.13389375843402,
"cv": 0.005301010367660728 "cv": 0.0030419312672842124
}, },
"p50": 5, "p50": 5,
"p99": 7, "p99": 7,
"p999": 30 "p999": 10
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 59145.6, "median": 63317.82,
"min": 59004.8, "min": 62453.82,
"max": 59376, "max": 63746.91,
"stddev": 153.00625985741647, "stddev": 543.811870536126,
"cv": 0.002585636725423652 "cv": 0.00860786685722159
}, },
"p50": 1, "p50": 1,
"p99": 3, "p99": 2,
"p999": 3 "p999": 3
} }
] ]
@@ -358,27 +358,89 @@
{ {
"path": "/steps/0", "path": "/steps/0",
"steps": 0, "steps": 0,
"reqSec": 92281.6 "reqSec": 88107.64
}, },
{ {
"path": "/steps/3", "path": "/steps/3",
"steps": 3, "steps": 3,
"reqSec": 81529.61 "reqSec": 79950.55
}, },
{ {
"path": "/steps/5", "path": "/steps/5",
"steps": 5, "steps": 5,
"reqSec": 71993.61 "reqSec": 74126.55
} }
], ],
"secureCost": [ "secureCost": [
{ {
"label": "security:false (parity)", "label": "security:false (parity)",
"reqSec": 98092.8 "reqSec": 87473.46
}, },
{ {
"label": "security:true (default)", "label": "security:true (default)",
"reqSec": 92998.4 "reqSec": 83773.1
}
],
"runtimes": [
{
"runtime": "node",
"scenario": "JSON hello (overhead)",
"reqSec": 90976
},
{
"runtime": "node",
"scenario": "Route param",
"reqSec": 88904.73
},
{
"runtime": "node",
"scenario": "Pipeline (3 steps)",
"reqSec": 82045.1
},
{
"runtime": "node",
"scenario": "POST JSON + validation",
"reqSec": 72235.64
},
{
"runtime": "deno",
"scenario": "JSON hello (overhead)",
"reqSec": 153408
},
{
"runtime": "deno",
"scenario": "Route param",
"reqSec": 146368
},
{
"runtime": "deno",
"scenario": "Pipeline (3 steps)",
"reqSec": 136256
},
{
"runtime": "deno",
"scenario": "POST JSON + validation",
"reqSec": 106661.82
},
{
"runtime": "bun",
"scenario": "JSON hello (overhead)",
"reqSec": 131674.19
},
{
"runtime": "bun",
"scenario": "Route param",
"reqSec": 126909.1
},
{
"runtime": "bun",
"scenario": "Pipeline (3 steps)",
"reqSec": 117489.46
},
{
"runtime": "bun",
"scenario": "POST JSON + validation",
"reqSec": 95124.37
} }
] ]
} }
+74 -3
View File
@@ -1,17 +1,30 @@
import autocannon from 'autocannon'; import autocannon from 'autocannon';
import { spawn, execSync } from 'child_process'; import { spawn, execSync } from 'child_process';
import os from 'os'; import os from 'os';
import { writeFileSync } from 'fs'; import { existsSync, readFileSync, writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios'; import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats'; import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render'; 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 SMOKE = process.env.BENCH_SMOKE === '1';
const CONNS = Number(process.env.BENCH_CONNS ?? 100); const CONNS = Number(process.env.BENCH_CONNS ?? 100);
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10); const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5); const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1); 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 { function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`); process.stderr.write(`[bench] ${msg}\n`);
} }
@@ -23,11 +36,25 @@ interface RunResult {
p999: 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( async function spawnServer(
name: string, name: string,
extraEnv: Record<string, string> = {}, extraEnv: Record<string, string> = {},
runtime: 'node' | 'deno' | 'bun' = 'node',
): Promise<{ port: number; kill: () => Promise<void> }> { ): Promise<{ port: number; kill: () => Promise<void> }> {
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 }, env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
}); });
let stderr = ''; let stderr = '';
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
})); }));
const stepScaling: RenderData['stepScaling'] = []; const stepScaling: RenderData['stepScaling'] = [];
const secureCost: RenderData['secureCost'] = []; const secureCost: RenderData['secureCost'] = [];
const runtimes: RenderData['runtimes'] = [];
for (const fw of frameworks) { for (const fw of frameworks) {
log(`booting ${fw}`); log(`booting ${fw}`);
@@ -145,6 +173,42 @@ async function main(): Promise<void> {
} }
} }
// 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 commit = execSync('git rev-parse --short HEAD').toString().trim();
const data: RenderData = { const data: RenderData = {
env: { env: {
@@ -160,8 +224,15 @@ async function main(): Promise<void> {
scenarios: scenarioBlocks, scenarios: scenarioBlocks,
stepScaling, stepScaling,
secureCost, 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)); writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
log('wrote BENCHMARKS.md + bench/results.json'); log('wrote BENCHMARKS.md + bench/results.json');
} }
+61
View File
@@ -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); });
+84
View File
@@ -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); });
+47
View File
@@ -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<void> {
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);
});
+1
View File
@@ -102,6 +102,7 @@
"complexity:check": "node scripts/check-complexity.mjs", "complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25", "complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts", "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", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true" "prepare": "git config core.hooksPath .githooks || true"
}, },
+80 -34
View File
@@ -13,8 +13,6 @@ export interface CompiledPattern {
segments: CompiledSegment[]; segments: CompiledSegment[];
kinds: number[]; kinds: number[];
catchAll: boolean; catchAll: boolean;
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
allStatic: boolean;
} }
const compiledCache = new Map<string, CompiledPattern>(); const compiledCache = new Map<string, CompiledPattern>();
@@ -160,7 +158,6 @@ export function compilePattern(pattern: string): CompiledPattern {
.filter((segment) => segment.kind !== 'catchAll') .filter((segment) => segment.kind !== 'catchAll')
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)), .map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
catchAll: segments.at(-1)?.kind === 'catchAll', catchAll: segments.at(-1)?.kind === 'catchAll',
allStatic: segments.every((segment) => segment.kind === 'static'),
}; };
compiledCache.set(pattern, compiled); compiledCache.set(pattern, compiled);
return compiled; return compiled;
@@ -248,7 +245,10 @@ export function normalizeRequestPath(path: string): string {
} }
function decodeSegment(value: string): string { function decodeSegment(value: string): string {
return decodeURIComponent(value); // Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
// runs for every param segment of every candidate route the scan reaches.
return value.includes('%') ? decodeURIComponent(value) : value;
} }
/** /**
@@ -262,7 +262,18 @@ function splitPath(path: string): string[] {
return path.split('/').filter(Boolean); return path.split('/').filter(Boolean);
} }
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined { /**
* Matches one compiled pattern against a request's segments.
*
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
* several routes decoded the same string once per route. Position is all decoding depends on, so one
* array shared across the scan is the same answer for less work.
*/
function matchCompiled(
compiled: CompiledPattern,
pathSegs: string[],
decoded?: Array<string | undefined>,
): Record<string, string> | undefined {
const params: Record<string, string> = {}; const params: Record<string, string> = {};
for (let index = 0; index < compiled.segments.length; index++) { for (let index = 0; index < compiled.segments.length; index++) {
@@ -280,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<st
continue; continue;
} }
const value = decodeSegment(pathSegs[index]); const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined; if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value; params[segment.name] = value;
} }
@@ -293,10 +304,15 @@ export function matchPattern(pattern: string, path: string): Record<string, stri
return matchCompiled(compilePattern(pattern), splitPath(path)); return matchCompiled(compilePattern(pattern), splitPath(path));
} }
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */ /**
function moreSpecific(a: string, b: string): number { * Orders patterns by exactness, then static/constrained/plain segment specificity.
const scoreA = compilePattern(a); *
const scoreB = compilePattern(b); * Takes compiled patterns rather than their source strings: it used to re-derive both through
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
*/
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
const scoreA = a;
const scoreB = b;
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
@@ -309,35 +325,65 @@ function moreSpecific(a: string, b: string): number {
return 0; return 0;
} }
/** Finds the most specific route matching both method and path; ties keep registration order. */ /** One route with its pattern already compiled. Built once per table, ordered within its method. */
interface IndexedRoute {
def: RouteDef;
compiled: CompiledPattern;
}
/**
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
* they were built from.
*
* A server hands the same array to every request, so this is built once and collected with the
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
* different array and gets its own index, so nothing has to remember to invalidate anything.
*/
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
const cached = routeIndexCache.get(routes);
if (cached) return cached;
const byMethod = new Map<string, IndexedRoute[]>();
for (const def of routes) {
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
const bucket = byMethod.get(def.method);
if (bucket) bucket.push(entry);
else byMethod.set(def.method, [entry]);
}
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
// keep registration order — which is exactly what the old scan did by refusing to replace its
// best on a tie.
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
routeIndexCache.set(routes, byMethod);
return byMethod;
}
/**
* Finds the most specific route matching both method and path; ties keep registration order.
*
* The ranking is settled when the table is built, not per request: the answer cannot change between
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
* table. What is left here is a walk that stops at the first match.
*/
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
const candidates = routeIndex(routes).get(method);
if (!candidates) return undefined;
const pathSegs = splitPath(path); const pathSegs = splitPath(path);
let best: MatchedRoute | undefined; const decoded: Array<string | undefined> = new Array(pathSegs.length);
let bestPattern = '';
for (const route of routes) { for (const { def, compiled } of candidates) {
if (route.method !== method) continue; const params = matchCompiled(compiled, pathSegs, decoded);
const compiled = compilePattern(route.pattern); if (params) return { params, def };
const params = matchCompiled(compiled, pathSegs);
if (!params) continue;
// An all-static match ends the scan. Specificity ranks a literal segment above every other
// kind, so no pattern that also matches this path can outrank one made only of literals — and
// an equal rank keeps registration order, which is this route. Finishing the scan would
// re-derive the answer already in hand.
//
// The scan used to run to the end regardless: `/hello` cost the same whether it was declared
// first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per
// registered route on every request, and it grows with the route table.
if (compiled.allStatic) return { params, def: route };
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
best = { params, def: route };
bestPattern = route.pattern;
}
} }
return best; return undefined;
} }
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */ /** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
+43
View File
@@ -76,3 +76,46 @@ describe('renderMarkdown', () => {
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k) 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');
});
});
+17
View File
@@ -119,6 +119,23 @@ describe('matchRoute precedence', () => {
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value'); expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
}); });
it('keeps registration order between patterns of equal specificity', () => {
// The tie-break the ordering rests on. Ranking is settled once when the table is built, and the
// sort that settles it is stable — which is what preserves the behaviour the scan used to get
// by refusing to replace its best on an equal rank. A sort that reordered equals would change
// which of two same-shape routes answers, silently and only for the ones that collide.
const routes = [route('GET', '/a/:first'), route('GET', '/a/:second')];
expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:first');
expect(matchRoute([...routes].reverse(), 'GET', '/a/x')?.def.pattern).toBe('/a/:second');
});
it('decodes a parameter once per position, however many candidates the scan walks', () => {
// Not an optimisation detail: the decoded value each candidate sees must be the same one, so
// memoising per request cannot change which route matches or what it receives.
const routes = [route('GET', '/a/:x/zzz'), route('GET', '/a/:y/b')];
expect(matchRoute(routes, 'GET', '/a/a%20b/b')?.params).toEqual({ y: 'a b' });
});
it('returns undefined when no pattern matches the path', () => { it('returns undefined when no pattern matches the path', () => {
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
}); });