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>
The same bytes on the wire reached different routes depending on where
the app ran. `GET /public/../admin` hit a `/admin` route under Deno, Bun
and workerd, and 404'd under Node — 200 vs 404 for one request.
The fetch-based runtimes resolve dot segments inside the `Request`
constructor, before green-tea is handed anything: `new Request(
'http://x/public/../admin').url` is already `http://x/admin`. Node's raw
target has no such step. Rejecting outright — the stricter policy, and
what this module already does for `//` — is not implementable on three of
the four runtimes, because the raw target is unrecoverable there. So Node
converges on the rule the other three cannot opt out of.
`%2e` is a dot to the URL parser, so the encoded spelling resolves too;
leaving it out would keep it as a way to reach a route the plain spelling
resolves away from.
Cost is gated: paths with no `.` and no `%` pay two indexOf scans
(20.0 -> 21.7 ns for `/hello`), a literal dot pays the regex (35.5 ns),
and only real dot segments pay the split (103.6 ns).
The existing parity suite could not have caught this — its `both()`
helper goes through `fetch()`, which normalizes the URL before it reaches
the wire. The new cases write the request line to a socket by hand.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
matchRoute evaluated every registered route before answering, so `/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, growing with the route table, and the benchmark app has
the smallest table any real service would have.
Specificity ranks a literal segment above every other kind, so a pattern
made only of literals cannot be outranked by anything else matching the
same path, and an equal rank keeps registration order — which is the
route already in hand. Finishing the scan only re-derives it.
The path split moves out of matchCompiled for the same reason: `split` +
`filter` ran once per candidate route on every request, always producing
the same array. Doing it once per request is 63.7% off a 32-route scan
that early exit cannot help at all (a :param match, which must be
compared against the rest of the table).
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.
92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.
Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.
Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
normalizeRequestPath ran on every request and validated percent-encoding by
splitting the path and calling decodeURIComponent on each segment, discarding
every result — matching is done on the raw path. Two array allocations and one
decodeURIComponent per segment, per request, to prove that a string nobody
decodes could be decoded.
Measured in isolation: 95.8ns for /hello, 342.7ns for a six-segment route. The
guard costs 15.7ns and 6.7ns for the same two paths.
Same validation. decodeURIComponent throws on the first malformed % sequence
wherever it appears, so one call on the whole string catches what per-segment
calls caught, and %2F inside a segment decodes fine either way. Only the throw
was ever used. The existing tests for malformed encoding and repeated slashes
pass unchanged.
Found by sweeping all 178 commits between fe1831a and the observability work
after the regenerated benchmark showed green-tea down ~20% since July while
raw-http, fastify and nestjs-fastify reproduced their July numbers within 1.4%
on the same run. The sweep put a +11.8% step at 9a61ba8 "complete HEAD and
OPTIONS semantics", which is where this function entered the request path.
Effect: -6.2% in-process request latency, from twelve interleaved measurements
whose ranges do not overlap (OLD 4.253-4.425us, FIX 4.035-4.151us). A first
attempt measured with-then-without and produced the opposite sign, so the
interleaving is load-bearing, not ceremony. Expect roughly 2% over a real
socket, which is below that harness's own noise floor.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).
On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:
- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
catch-all, not registration order), and 405 + Allow when a path exists
under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
`mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>