63 Commits
Author SHA1 Message Date
chrnx 1c9f387b91 fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 30s
The outbound pump pulled a @Ws handler's iterator as fast as it yielded,
whatever the peer read. With a slow client, 10,000 frames of 64 KiB were
all pulled at once and sat in the send buffer: 640 MiB.

WsSocket gains one optional member, drained(): it resolves once the
socket's send buffer is at or below the adapter's high-water mark
(WS_HIGH_WATER_MARK, 1 MiB, internal), or the socket has closed. The
pump awaits it before each pull, so the buffer peaks at the mark plus
one frame. A close ends the wait and the abort path runs the iterator's
return(), as before. A socket without drained() is never waited on.

Per runtime:
- Node: ws.bufferedAmount, released by each send's write callback;
- Bun: getBufferedAmount(), released by the server's drain callback;
- Deno: polls bufferedAmount every 10 ms, only while over the mark;
- workerd reports no buffered amount, so the edge never waits.

The Deno poll also waits while the socket is CONNECTING. Deno hands the
socket over before it opens, and a handler that yielded at once had its
first value pulled into a socket that was not open yet. The pump then
gave up, so the client saw no frame and a 1005 close.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:52:32 -05:00
chrnx bd85bf67bc fix(mesh): hold the control channel to hello size until the peer authenticates
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
boundInbound(socket, meshBounds) runs before ensureBooted() and before
the hello is checked, and meshBounds allowed 4,096 queued frames of up
to 7 MB each. During a slow boot nothing reads that queue, so an
unauthenticated peer could make the process buffer tens of GB.

The control channel's bounds are now phased (controlBounds() replaces
controlLimits()):
- until the hello is accepted: frames of at most HELLO_FRAME_BYTES
  (64 KiB) and the default 16-frame queue, so about 1 MiB per
  connection;
- after: the frame bound from #120 and the queue bound from #148.

boundInbound takes the second set as an optional `widened` argument and
keeps the switch on the bounded socket under a Symbol.for key. The
teapot calls widenInbound() when the handshake succeeds. The teapot's
own parse check follows the same phases, so a standalone
createMeshControl also refuses a pre-auth frame over hello size.

This is an auth-phased bound rather than a total-bytes cap: the only
unauthenticated frame with a purpose is the hello, and phasing keeps
the trusted path free of a second accounting rule. No new option.

On Node the control path's native maxPayload stays at the authed bound,
because ws cannot change it per phase. A pre-auth peer can still make
ws assemble one frame of up to that size before boundInbound closes
the connection with 1009. That frame is transient and never queued.

Tests: during a delayed boot, a 1 MB pre-auth frame closes 1009 at once
and a flood closes 1013 within 17 frames; after the hello, large frames
and a 64-ping burst are accepted. On Node, Deno and Bun, an
unauthenticated 1 MB frame over a real socket closes 1009. The #148
64-RPC test stays green.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:52:20 -05:00
chrnx de798771e4 fix(mesh): size control frames for the worst escaping a body can get (#120)
A 999,000-byte text/plain body of U+0001, within maxBodyBytes, still
failed 503: the envelope carries a text body as a JSON string, each
control character escapes to six characters, and the ~6 MB frame was
over the 4,000,000 the channel was sized to.

controlFrameLimit() is now 6 x maxBodyBytes plus 1 MiB for headers,
params, query and the envelope: 7,048,576 at the 1 MB default. Six is
the worst growth of any body byte; quotes and backslashes double, JSON
numbers like 1e20 grow about fivefold, multipart Buffers at most
fourfold, and non-ASCII text is not escaped. The fixed MAX_FRAME_CHARS
goes away with it.

Test (T1c) on Node, Deno and Bun: the control-character body now
answers 200 and the channel stays open.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:49:34 -05:00
chrnx 3455b421a4 fix(mesh): give the control channel its own inbound queue bound (#148)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 21s
The control channel also inherited limits.maxWsQueue (16 undelivered
frames, close 1013) from #107. On Node, ws emits every frame of one
socket read synchronously, so a teacup with more than 16 RPCs in flight
sent a burst the teapot's queue refused: the link dropped and every
pending request failed 503. Deno and Bun deliver one frame per task and
did not trip.

controlLimits() now also raises maxWsQueue for the control channel, to
an internal 4,096 frames or maxWsQueue if larger, alongside the size
bound from #120. The teapot's frame loop never awaits between frames, so
the queue only holds one delivery burst, and one read (at most 64 KiB)
holds fewer than 4,096 of the smallest control frame. The bound stays
finite, so a peer flooding a channel nobody is reading is still cut off.
No new option. User @Ws routes keep closing 1013 at maxWsQueue.

Tests: 64 RPCs in one tick through app.fetch on one link all answer 200
(red on Node before), and a user route on the same teapot still closes
1013, on Node, Deno and Bun.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:29:31 -05:00
chrnx 99ad996c2e fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
The 1 MiB inbound cap from #107 applied to every WebSocket, the mesh
control channel included. An RPC carries a whole request body, so a body
inside maxBodyBytes could still overflow the cap once wrapped in an
rpc-req frame, and the teapot then closed the whole channel with 1009:
every request through that link failed 503 until it reconnected.

The test asked for by the card (T1, a 1 MB JSON body at defaults) passes
on Node, Deno and Bun, because a JSON body re-encodes to about its own
size. Two other cases fail on all three before this change:
- T1b: a 999 KB text body of quotes doubles under JSON escaping;
- T4: maxBodyBytes raised to 4 MB, a 3.9 MB JSON body.

The control channel's bound is now derived from the teapot's
limits.maxBodyBytes via controlFrameLimit(): MAX_FRAME_CHARS (4,000,000)
at the 1 MB default, scaled by the same ratio above it, never below
maxWsMessageBytes. No new option. User @Ws routes keep
maxWsMessageBytes: Node gets a second WebSocketServer for the control
path, app.upgrade picks the bound from the path before subscribing, and
Bun's single native maxPayloadLength is raised on a teapot only, leaving
app.upgrade to close user routes 1009 itself.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:03:11 -05:00
chrnx e565b1d4c9 Merge pull request 'chore(deps): patch vite, vitest and fastify dev-dependency advisories' (#134) from chore/audit-fix-2026-10-22 into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 27s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 04:55:05 +00:00
chrnxandClaude Opus 5.5 e112819f64 chore(deps): patch vite, vitest and fastify dev-dependency advisories
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
`npm audit --audit-level=moderate` failed on develop: vite <=6.4.3 (high:
cross-origin script execution in custom middleware, fs.allow bypass,
launch-editor), vitest/@vitest/mocker <=4.1.11 (moderate: code injection via
manual mock registration) and fastify 5.12.2-5.12.5 (low, benchmark only).

All are devDependencies; the published package is unaffected. Lockfile-only:
vite 6.4.5, vitest 4.1.12, fastify 5.12.7, all inside the existing ranges.
Generated with npm 11 because npm 10.9.7's arborist crashes on this tree
(`Cannot read properties of null (reading 'edgesOut')`).

Verified: npm ci, audit (0), lint, format, typecheck, test (915),
build, complexity, test:deno, test:bun, test:edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-22 23:53:16 -05:00
chrnx f4d29d8ee8 Merge pull request 'test(bun): expect 1009 for oversized WebSocket frames on Bun 1.4+' (#135) from fix/bun-ws-oversize-close into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-10-23 04:53:08 +00:00
chrnxandClaude Opus 5.5 69bdc8adec test(bun): expect 1009 for oversized WebSocket frames on Bun 1.4+
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 27s
CI picked up Bun 1.4.4 (`oven-sh/setup-bun@v2`, latest), which now sends a
real `1009` close frame when `maxPayloadLength` refuses a frame. Bun 1.3
dropped the connection instead, so the peer saw `1006` — the difference D1
documented and these two assertions pinned on purpose so a Bun upgrade would
be noticed. It was: `runtimes (bun)` fails on develop.

The assertion now follows `Bun.version` (1006 before 1.4, 1009 from 1.4), so a
further change in either direction still fails. JSDoc, README and the #107
CHANGELOG entry say which Bun versions do what.

Verified with Bun 1.3.14 and 1.4.4 (26/26 each); lint, format, typecheck,
npm test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-22 23:50:30 -05:00
chrnx 169ffe6b88 Merge pull request 'ci: move workflow actions off the deprecated Node 20 runtime' (#133) from chore/ci-node24-actions into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 5s
2026-10-18 04:42:07 +00:00
chrnx 7bc402a1fb ci: move workflow actions off the deprecated Node 20 runtime
CI / dco (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 37s
CI / build (pull_request) Successful in 53s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
actions/checkout and actions/setup-node v4 -> v5, softprops/action-gh-release
v2 -> v3; all three run on Node 24. setup-deno@v2, setup-bun@v2 and
crates-io-auth-action@v1 already resolve to Node 24 releases. Jobs keep
node-version 22.

Refs #103

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-17 22:55:41 -05:00
chrnx 539f287a67 Merge pull request 'feat(router)!: fail boot on unreachable or ambiguous constrained params (CARD-13, #127)' (#132) from feature/fprd-001b-constraint-ambiguity into develop
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 26s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 20s
2026-10-14 02:22:28 +00:00
chrnx 84e6f0752e docs(readme): describe radix route lookup
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 15s
The README still said matching was a linear scan with a radix tree as
post-beta work; CARD-07 (#128) shipped the radix index.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-13 21:21:25 -05:00
chrnx 63f60134ea feat(router)!: fail boot on unreachable or ambiguous constrained params
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
Before, when two sibling routes could match the same request, the router
picked one by registration order or precedence, and nothing reported it.
Boot now refuses two cases between routes of the same method that branch at
the same segment under the same prefix:

- ambiguous: both params are constrained, the constraints accept a common
  segment, and the rest of both patterns can match one request. The error
  names both declarations and a witness segment with an example path.
- unreachable: a plain param sits next to a constraint that accepts every
  segment, and the constraint wins every request the plain param could take.

A plain param next to a constraint that leaves some segments over is the
documented fallback pattern and still boots.

The check is exact. assertSafeConstraint admits only a linear, group-free
subset, so every constraint reads back as a sequence of (character set, min,
max) blocks. Atom sets follow u-flag semantics. \p{...} is the one construct
that is not modelled, and for it the engine is asked once per code point. A
product walk over two block sequences finds a common segment, or proves none
exists, in O(|A|*|B|*(|A|+|B|)*K) with K <= 2048. "Accepts every segment" is
a closed-form test on the blocks. Both are measured against what the router
hands a param: a decoded, non-empty segment that is never "." or "..".

The check runs per table under that table's own precedence. HTTP ranks by
specificity. WebSocket takes the first declared match. @Stream routes sit in
both tables. Routes exported by different teapots are checked against each
other. Local against remote keeps the local override and its warning.

The lookup path is unchanged. router.ts only exports the two token regexes,
so the boot check and assertSafeConstraint read atoms the same way.

BREAKING CHANGE: an app that declares two overlapping constrained siblings
  (e.g. /u/:id(\d+) and /u/:n(\d{1,3})), or a plain param beside a constraint
  that accepts every segment, now fails createApp. So do a plain WebSocket param
  declared before a constrained sibling, and such pairs across mesh teapots.
Refs: #127
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 16:07:58 -05:00
chrnx e41d9560ba test(router-parity): make the app fixture's hex route disjoint for CARD-13 (owner approval required)
The frozen app fixture declares GET /n/:num(\d+) and GET /n/:code([0-9a-f]+).
Both constraints accept digits, so CARD-13 (#127) makes this pair a boot error,
and the fixture app could no longer start. That would fail app-fetch.json and
app-node.json, and the Deno, Bun and workerd parity runs that boot the same app.

Narrow nCode to [a-f]+. The two frozen requests on this pair still get the
captured answers: /n/42 goes to nNum and /n/ff goes to nCode, with the same
params. No frozen JSON file changes.

What is lost at app level is the equal-rank registration tie between two
overlapping constraints. CARD-13 now forbids that tie at boot. The tie stays
covered by matcher-hand.json, which calls the matcher without booting an app.

Owner approval required (CARD-08 rule): this edits a file under
test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 16:07:15 -05:00
chrnx c2db4f69c6 Merge pull request 'test(router): record D4 lookup evidence and no miss-time recompilation (CARD-10, #109)' (#130) from feature/fprd-001b-lookup-evidence into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 5s
2026-10-12 20:43:32 +00:00
chrnx 2e2c68de07 test(bench): record D4 lookup evidence at ed19f16 (CARD-10, #109)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 19s
Formal D4 run after the walk-stack fix (#131) and the router-order fix in
the harness, 16 x 21 rounds on jarvis. Every cell passes; the 10-route
late param hit passes with its CI lower bound at +4.9%. Marks the
b128139 evidence as superseded.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 15:27:20 -05:00
chrnx ed19f16c70 test(bench): alternate the whole router order per lookup run
Only the import order alternated between processes; warm-up order and
the shared lookup call site always saw the first-listed router first.
CARD-10's A/A run (oracle vs a byte-identical copy) showed a steady bias
of up to +8.3% against the second-listed router at 10 routes. Reversing
the whole order per process brings the same A/A to -0.1% (8 x 21
rounds on jarvis). Owner-approved D4 method change (2026-10-12).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 15:16:13 -05:00
chrnx a64f514db2 test(bench): record D4 lookup evidence for the radix router (CARD-10, #109)
Formal D4 run on jarvis with the baseline's harness, image, and cpuset:
oracle (pre-radix linear matcher) against the radix router at b128139,
16 processes x 21 rounds = 336 paired rounds per cell, plus an A/A
run (oracle against a byte-identical copy) at the same settings.

D4 fails at 10 routes: late param hit +52.5%, method miss +31.8% and path
miss +101.9%, with every CI lower bound far above +5%. 100 routes improve
in every cell, and all 500-route targets are met (-82.5% to -92.1%). A
diagnostic run with three router revisions traces the 10-route regression
to a2b71e2 (try/finally stack reset in the walk). The seam counters
added for the no-recompilation test change nothing.

No threshold was relaxed and no src/ change was made. The raw samples
are committed for an owner decision.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 15:12:40 -05:00
chrnx 7a9932f095 test(router): prove misses after index build recompile nothing (CARD-10, #109)
The linear matcher answered every 404, 405 and automatic OPTIONS by compiling
the whole route table. The radix index compiles each pattern once, when the
index for an array is built. Nothing asserted that, so a regression to
per-request compilation or per-request index builds would only show up as a
slower benchmark.

compilePattern is called inside router.ts, where a spy on the module export
cannot see it, so the router gains two internal counters (compilePattern calls,
index builds), exposed as @internal routerSeamCounts() next to walkStackSize.
router.ts is not a package entry. The new test warms the index, then repeats
404, 405 and OPTIONS misses through resolveRoute/allowedMethods, buildFetch and
app.fetch, and asserts both counts stay constant while status and Allow stay
correct.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 15:12:40 -05:00
chrnx 72f591dd21 Merge pull request 'test(router): prove introspection parity after the radix index (CARD-09, #109)' (#129) from feature/fprd-001b-introspection-parity into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-12 20:12:25 +00:00
chrnx d07d6add04 Merge pull request 'perf(router): reset the walk stack only when a lookup throws (#109)' (#131) from fix/router-walk-stack-reset into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 7s
2026-10-12 20:10:44 +00:00
chrnx 1b30f15c02 perf(router): reset the walk stack only when a lookup throws
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 19s
The finally block added in a2b71e2 wrote both stacks' length on every
lookup, which drops their backing storage and made every walked lookup
pay for reallocation: +50% late param hit, +33% method miss and +104%
path miss at 10 routes on jarvis (CARD-10). A normal walk already ends
at base, so reset only in a catch and rethrow.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 14:27:24 -05:00
chrnx fcee6892bf test(router): prove introspection parity after the radix index (CARD-09, #109)
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
The frozen CARD-08 goldens already hold graph(), explain(), openapi() and
the mesh teacup. This adds what they do not cover, with expectations
captured from the pre-radix code at ed47836 in a detached checkout:

- explain()/inspect() on a pattern shared by several methods with a
  non-GET declared first, and a concrete path that is not a declaration;
- /__graph__ and /__openapi__ on app.fetch, a Node listener and a mesh
  teacup, and their agreement with the direct API;
- a structural check that graph/explain/inspect/openapi never call the
  router lookup, return the same output before and after the index is
  built, and keep declaration order where the index ranks differently.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 13:59:56 -05:00
chrnx cb123e3774 Merge pull request 'perf(router): radix index for HTTP route lookup (CARD-07, #109)' (#128) from feature/fprd-001b-radix-index into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 7s
2026-10-12 18:54:45 +00:00
chrnx a2b71e2472 fix(router): drop pending walk frames when a segment fails to decode
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
The walk stack is shared across lookups. A malformed % escape threw out
of decodeSegment with frames still pushed, so repeated direct matcher
calls on such paths retained them. Truncate both arrays back to the
entry length in a finally block, and check it with a test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 13:47:53 -05:00
chrnx 4de9f32e31 test(router-parity): retarget walk mutants to the iterative walk
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / runtimes (bun) (pull_request) Successful in 15s
Same four mutants (no-backtrack, catch-all-needs-segment,
prune-bound-off-by-one, zero-catch-all-after-static-dead-end), patched
at their new sites in the stack-based walk. 21/21 still killed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 22:07:17 -05:00
chrnx 5e0ae94ba2 fix(router): walk the radix index without recursion
The lookup walk recursed once per path segment, so a valid deep route
such as 4,999 static segments followed by /:x threw RangeError where the
linear matcher matched. Walk on an explicit stack instead, visiting
frames in the same order, and cover the case through buildFetch.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 22:06:49 -05:00
chrnx 996fb3f7a5 test(router-parity): retarget mutants to the radix index (owner-approved)
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 25s
The owner approved editing this one file under test/router-parity/ so
the PR ends with a single mutant check. The original search texts
targeted lines of the linear scan that CARD-07 removed, so the script
refused to run against the new router. The parity tests, oracle,
frozen JSON and manifest are untouched.

The twelve original mutants keep their names and the bug each models;
six apply their original edit, six are rewritten against the index.
Nine new mutants cover risks the index introduced: the static-route
map ignoring the method or shadowing an earlier route, an off-by-one
pruning bound, the empty-collection skip pruning a real match, a
local/remote tie going remote, Allow and implicit HEAD from the local
tree only, the stale-index guard removed, and a zero-segment
catch-all skipped where the path ends on a static continuation.

The suite now also runs test/router-index.test.ts, which covers the
local/remote split and index lifetime the corpus cannot reach. Each
edit must match exactly once and must change the file; a failed edit
restores the copy before the run aborts. The script still ends with
git diff --exit-code src.

Removes test/router-index-mutants.ts and parity:mutants:index, which
this replaces.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 21:00:35 -05:00
chrnx 55a4e282ad test(router): cover pruning across a static branch and a param sibling
The walk takes the static branch first, so for `GET /a/:rest*` and
`GET /:x/b` it reaches the catch-all on `/a/b` before the exact param
route that outranks it. The corpus has no such pair, and a pruning
bound off by one went unnoticed there. Checked against the oracle in
both declaration orders.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 21:00:27 -05:00
chrnx d76afd7f25 docs(changelog): note the radix route index
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 25s
An internal change with no behaviour difference, recorded under
Changed with the lookup numbers from the jarvis run.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 12:58:26 -05:00
chrnx 815f76116f perf(router): index HTTP routes in a radix tree
Replace the linear, specificity-sorted scan behind matchRoute,
resolveRoute and allowedMethods with a segment trie per HTTP method,
built once per route array from the compiled segments compilePattern
already produces.

Ranking stays global: every terminal carries its position in the old
sorted bucket (moreSpecific, declaration order on ties), and the walk
keeps the lowest rank it can reach, pruning subtrees that cannot beat
it. The tree decides which routes can match; the rank alone decides
which one does. A static branch that dead-ends deeper backtracks into
its param, constrained and catch-all siblings.

All-static routes are also kept by exact path per method. A hit there
is provably the tree's best match, so a static request is answered
without splitting the path; a miss falls through to the walk.

Mesh-spliced remote routes go in a second tree, per the owner's
design decision. Both trees answer, the more specific match wins and
an equal one goes to the earlier declaration, so local still beats
remote on a tie. Allow, 405 and implicit HEAD run over the union. An
app without remote routes does one lookup.

allowedMethods walks the index instead of recompiling every route on
a miss, and an implicit HEAD no longer builds a fresh index from a
filtered array on every request.

The frozen parity corpus passes unchanged. The frozen mutant script
cannot run against the new layout by design, so
test/router-index-mutants.ts re-targets its twelve bug classes at
the new code and runs the same untouched suite.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 12:56:37 -05:00
chrnx 7ee7ab7ec5 Merge pull request 'test(router): freeze radix-router parity corpus and baseline (CARD-08, #109)' (#123) from feature/fprd-001b-router-corpus into develop
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
2026-10-11 17:23:53 +00:00
chrnx fdd762b081 test(router): freeze local/remote Allow and remote implicit HEAD for mesh
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CARD-07 will index local and remote mesh routes as two radix trees and keep
today's unified precedence: the most specific route wins across both trees, a
tie goes to the local route, and Allow is the union. This freezes that behaviour
from ed47836, through app.fetch and a Node socket, in a new file
(owner-mesh-allow.json); existing captures are untouched.

- Local GET and remote POST on one path: PUT is 405 and OPTIONS is 204, both
  with Allow GET, HEAD, POST, OPTIONS. HEAD uses the local GET.
- Local static GET /api/v/b with remote POST /api/v/🆔 the same union on
  /api/v/b, and only POST, OPTIONS on /api/v/c.
- A remote GET with no local route: OPTIONS advertises GET, HEAD, OPTIONS, but
  HEAD answers 404. The teacup resolves HEAD to the remote GET implicitly,
  forwards it as HEAD, and the teapot finds no plan for (pattern, HEAD). That
  is the mesh proxy, not the matcher, and is captured as observed.

The mutation check still kills 12 of 12.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 18:16:09 -05:00
chrnx 71fc027134 perf(bench): re-baseline lookup on jarvis with the interleaved harness
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 35s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
The first baseline came from a laptop on battery, with one router per process,
run one after the other. It moves to battery-run/ for reference. The new
baseline is the interleaved A/A run (live matcher as A, byte-identical oracle
as B) on jarvis.

Setup: Ryzen 7 3700X, cpuset 6,7,14,15 (two idle physical cores and their SMT
siblings), node:22 container, Node 22.23.1, load average 0.27-0.79, no CI job
running. 4 processes x 21 rounds give 84 paired rounds per cell.

Live medians in ns per lookup (static hit, late param, method miss, path miss):
  10 routes:   185, 328, 800, 626
  100 routes:  201, 878, 2525, 3054
  500 routes:  202, 2931, 11904, 15514

A/A noise floor (oracle/live median ratio, 95% CI): at 10 routes, static hit
-13.7..+11.9% and late param -1.6..+9.8%; misses within +-4.4%. At 100 and 500
routes, offsets are systematic but within about 3%.

In-process, the module imported first runs about 20% faster on the 10-route
static hit. Alternating import order per process removes the bias from the
median but not from that cell's CI. A 5% limit there cannot be resolved with
this method and sample size, so this is recorded for the D4 decision. The 20%
improvement target at 500 routes is far outside the noise.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:44:53 -05:00
chrnx ee7fdec541 perf(bench): interleave lookup comparisons and report B/A with a bootstrap CI
The first baseline ran each router in its own process, one after another, so
drift and background load landed on whichever side ran later. Comparing two
medians taken minutes apart cannot resolve a 5% threshold.

bench:lookup now loads every router into one process. In each cell it warms
every router, then takes one sample from each per round, alternating the
order: AB, BA, AB. There are at least 15 rounds per cell per run (default 21)
over 4 fresh processes, and module import order also alternates per run.
Every router after the first is reported against the first as the median of
the per-round paired B/A ratios, with a percentile-bootstrap 95% CI (4000
resamples, fixed seed, so the same samples always give the same interval).
With a single router it reports absolute medians as before.

The record now includes hostname, the effective cpuset when run in a Linux
container, and any LOOKUP_* note variables. The harness still runs on any
machine with Node 22.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:41:15 -05:00
chrnx 32caa21308 test(router): add a mutation check for the parity corpus
A frozen corpus is only worth what it catches. npm run parity:mutants applies 12
targeted mutants to a temporary copy of src/, one at a time, and runs the parity
suite against each. Every mutant models a bug a radix rewrite could plausibly
introduce:

  no backtracking to a param branch     static/param precedence swapped
  equal-rank tie to last-registered     constraint ignored
  decode before splitting (%2F)         catch-all needs a segment
  implicit HEAD from a streaming GET    Allow from one pattern only
  Allow in discovery order              trailing slash not normalized
  WS ranked like HTTP                   case-insensitive static match

All 12 are killed (4 to 74 failing tests each), so no corpus case had to be
added. A mutant whose search text is not found exactly once fails the run rather
than silently testing an unmutated copy. The real src/ is never written, and
the run ends with git diff --exit-code src. It is not part of npm test because
it runs the suite once per mutant.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:39:38 -05:00
chrnx 684795a2de test(router): run the parity differential on Deno, Bun and workerd
The matcher comparison does not depend on the runtime, so it should run on every
runtime core supports. Only the Node suite ran it before.

The comparison and the app.fetch fixtures move into differential.ts and
app-fixture.ts, which use neither vitest nor a file API. Each runtime passes in
a loader for the frozen JSON. The vitest files use the same modules, plus a
Node check that the neutral runners report no mismatch, so the two paths cannot
drift.

- Deno and Bun: test/{deno,bun}/router-parity.test.ts run all 1158 frozen
  matcher cases (hand-picked, owner, generated v1 and v2, WS) through the oracle
  and the live router, plus the 55 app.fetch cases.
- workerd: test/edge/parity-worker.ts bundles the frozen JSON and runs the
  same checks; test/edge/run.ts adds the phase after its existing assertions.

The Node-socket, WS-upgrade, boot and mesh captures stay Node-only: they need
http.request, the ws client, or a mesh peer on a port.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:38:36 -05:00
chrnx a4562b2b23 perf(bench): record the pre-radix lookup baseline at ed47836
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
The baseline CARD-10 compares the radix index against, captured before any
router change. Kept with its environment record and every raw sample.

bench:lookup on the linear matcher, five runs of 105 samples per cell. Median
ns per lookup:

  routes  static hit  late param  method miss  path miss
  10            61.3       123.3        313.1      247.1
  100           67.6       343.4       1263.7     1463.3
  500           67.8      1326.8       6732.2     8973.4

Run-to-run spread of the per-run medians is 2.0-17.5%. An A/A run (live
router against the byte-identical oracle, same protocol) differs by +5.2% on
the 10-route static hit and by at most 2.7% elsewhere, so D4's 5% limit at 10
routes sits at the noise floor for that cell. That is recorded for the D4
decision, not resolved here.

bench:compare, run once A/A, is stored separately as end-to-end req/s only:
every case within 1.9%.

Measured on an Apple M4 Max on battery power, load average 2.4-3.4 on 16
cores; the comparison run should use the same power source.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:27:26 -05:00
chrnx a47c6564ab test(router): add owner-requested parity cases and a shared-prefix generator
Additions requested in CARD-08 review, captured from ed47836 like the rest of
the corpus and frozen in their own files, so the first capture is untouched.

- Backtracking: a static branch failing one level down, at depth 5 (and a
  param branch at depth 3), and with a constrained param on the fallback.
- Cross-pattern Allow: GET :id plus POST b, with and without DELETE :rest*,
  at matcher level and through app.fetch and Node.
- Encoded slashes in plain and constrained params. A constraint cannot itself
  contain a slash: the pattern splits there and is rejected as malformed.
- Zero-segment catch-alls without an exact sibling, and a root catch-all.
- The mesh HTTP table across a peer's lifetime. It is built once at boot and
  never changes: a peer that leaves keeps its routes (503 on hit, 405 Allow
  unchanged) and a peer that arrives after boot is never spliced in (404).
  CARD-10 can reuse this for its no-rebuild-per-request check.
- router-parity-gen-v2, same seed 10908, forces static, param, constrained
  and catch-all siblings under shared prefixes at depths 1-4. branches.ts
  measures the effect and the result is frozen with the fixture: 71.9% of v2
  requests reach sibling branches and 67.3% backtrack, against 36.5% and
  26.7% for v1. v1 and its fixture are unchanged.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:27:11 -05:00
chrnx 98ea948ffa perf(bench): add a focused route-lookup benchmark for D4
bench:compare reports end-to-end req/s with 50 and 200 filler routes. Lookup
is a few percent of a request there, so it cannot judge D4's thresholds
(at most 5% median regression at 10 routes, at least 20% improvement at 500),
which are stated in median lookup time.

bench:lookup measures exactly what dispatch does with a normalized path:
resolveRoute, and on a miss allowedMethods. It covers 10, 100 and 500 total
HTTP routes from a recorded generator, with static hit, late parameter hit,
method miss and path miss workloads. Each answer is checked before timing, so
an implementation that answers wrongly cannot post a number. Warm-up is
time-boxed and calibrates the iterations per sample; every sample is kept.

The router under test is a module path. LOOKUP_ROUTERS takes several, and each
run measures them in separate child processes, alternating which goes first,
so CARD-07/10 can run this same harness on base and head.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:01:25 -05:00
chrnx 5d0e544878 test(router): capture graph, explain and OpenAPI goldens before indexing
graph(), explain() and openapi() read routePlans in declaration order. A
radix index must stay a lookup structure and never become their source, so
their output is frozen from ed47836 for CARD-09 to compare against.

One app fixture covers multiple methods and transports, constraints, explicit
HEAD and OPTIONS, providers and steps, and WS, declared out of specificity
order. The goldens hold graph(), explain() for declared patterns and the
`no route: <pattern>` error (including a concrete request path, which is not a
declaration), and openapi({ title: 'Parity', version: '1' }). A separate mesh
teacup records the pre-ready errors, then post-ready introspection in which
the remote HTTP route is reachable but absent from routePlans.

The comparison holds array order and object key order, and `vitest -u` is
refused rather than allowed to rewrite a golden.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:46 -05:00
chrnx c30cf7e457 test(router): freeze the differential, application, WS and boot-error corpus
The parity corpus from ROUTER-CORPUS §2, with every expected output captured
from ed47836 rather than written by hand.

Matcher: 24 hand-picked scenarios (precedence, constraint ties, exact versus
catch-all, equal-rank and same-pattern ties with reversed twins, implicit and
explicit HEAD, streaming GETs, canonical Allow, encoding, case, Unicode and
normalization) plus 40 scenarios from a fixed-seed generator
(router-parity-gen-v1, seed 10908). The generated file stores the seed, the
rules and every generated input; the test regenerates and requires a match,
so changing the generator cannot move the baseline. Each scenario runs through
the oracle and the live router and both must equal the capture, compared by
declaration ID, decoded params, implicitHead, ordered Allow, or the
normalization error.

Application level: status, Allow, headers and body through app.fetch and a
Node socket, including HEAD body suppression, 400/404/405 and OPTIONS.

WebSocket, separate from HTTP: first-registered selection, an HTTP route at the
same path not taking the upgrade, and the reserved mesh control path, through
app.upgrade and the Node listener. This freezes one adapter disagreement as
observed: a user @Ws('/__mesh__/control') on an app without mesh is refused by
app.upgrade (1008) and served by the Node listener.

Boot-time rejections: pattern compilation, local ambiguity and mesh splicing
(duplicate exports, same-shape exports, local-over-remote precedence with its
warning, and a remote static outranking a local parameter route).

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:45 -05:00
chrnx adce82beaa test(router): pin the retained-test manifest and a frozen pre-radix oracle
CARD-07 replaces the linear HTTP matcher with a radix index. Before any of
that code changes, the behaviour it must preserve has to exist somewhere the
new code cannot quietly move it.

manifest.json names the existing tests retained unchanged (ROUTER-CORPUS §1),
pinned to ed47836 instead of 42376c6: #117 and #122 landed after the corpus
was written. Every named file and test was verified to exist and pass there;
none was renamed. Three upgrade-path tests from #117 are listed separately as
proposed additions, pending D5. manifest.test.ts fails if a named test
disappears.

oracle.ts is a verbatim copy of the matcher at ed47836 (matchRoute,
resolveRoute, allowedMethods, normalizeRequestPath, compilePattern,
matchWsRoute), with local route types and its own caches. Its header says it
must not be edited to fit a new implementation, and the manifest test fails if
anything under src/ imports it.

frozen.ts reads the captured baseline. It refuses `vitest -u`, and the capture
switch only fills a missing file, never overwrites one.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:31 -05:00
chrnx ed47836c98 Merge pull request 'chore!: require Node 22 and clear dev audit advisories' (#122) from chore/audit-dev-deps into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 30s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (edge) (push) Successful in 13s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-10 21:41:42 +00:00
chrnx 77a99e83ce chore(deps): vitest 4
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 13s
vitest 3.2.7 carried the last three dev audit advisories: tinypool
(critical, prototype pollution to RCE in worker options), vitest itself
(critical, through tinypool and @vitest/mocker) and @vitest/mocker
(moderate, path traversal through a redirected mock). 4.1.11 is the
first stable release outside every affected range; vitest 4 no longer
depends on tinypool at all. It needs Node 20 or newer, which the Node 22
floor now guarantees. vitest 5 would need Node 22.12, and 4.1.11 is
enough to clear the advisories.

vite stays on ^6.4.3, which vitest 4 accepts.

The one change the bump requires: vitest 4 types `vi.fn()` with no
arguments as a mock of a function *or* a constructor, so
`ReturnType<typeof vi.fn>` is no longer callable as a plain function.
listener-boundary.test.ts now types its spies as
`Mock<(...args: unknown[]) => void>`.

npm 10.9 crashes in arborist's #loadPeerSet resolving this tree, so the
lockfile was produced with npm 11.6.2; `npm ci` on Node 22's bundled
npm 10 installs it cleanly.

npm audit: 3 -> 0. npm audit --omit=dev stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 15:03:19 -05:00
chrnx bd478ce09c build!: require Node 22
Node 18 and Node 20 are end-of-life and receive no security patches, so
supporting them before RC.1 would mean promising a runtime nobody can
patch. Node 22 is the oldest line still maintained.

engines.node moves to >=22, @types/node to ^22, the tsup target to
node22, and CI's build job from Node 18 to 22, so every workflow now
runs Node 22 only. The docs, the bug report example and the comments
that stated 18 as the floor follow.

The node:crypto fallback in the HTTP core existed only for Node 18,
which lacked the global crypto; it goes with its regression test, which
said as much. The ws fallback for the WebSocket client stays: Node 22
has the global, but it can still be switched off with a flag.

Moving off Node 18 and 20 also unblocks vitest 4, which the remaining
dev audit advisories need.

BREAKING CHANGE: Node 18 and Node 20 are no longer supported. The
minimum is Node 22.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 12:10:52 -05:00
chrnx 4c3b4d29c4 chore(deps): move the benchmark's fastify to 5.12.5
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 13s
fastify <= 5.12.4 carries seven advisories (high), and it reaches us
twice, both benchmark-only: as a direct devDependency and through
@nestjs/platform-fastify 11.2.7, which pins fastify 5.11.3 exactly.
`npm audit fix --force` would move to @nestjs/platform-fastify 12,
which is ESM-only and needs @nestjs/core and @nestjs/common 12 as
well: a migration of the Nest benchmark servers, not a dependency fix.

Raise the direct range to ^5.12.5, a patch inside the major we already
use, and point nest's copy at it with `"fastify": "$fastify"` so the
tree holds a single, patched fastify.

Checked with `BENCH_SMOKE=1 npm run bench`: fastify, nestjs-fastify
and nestjs-express all boot and serve every scenario with 0% errors.

npm audit: 5 (2 critical, 1 high, 2 moderate) -> 3 (2 critical,
1 moderate), all of them vitest. `npm audit --omit=dev` stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 12:00:06 -05:00
chrnx 445738e830 chore(deps): override miniflare's undici and sharp to patched releases
miniflare 4.20260730.0 is still the newest stable release, and it pins
undici 7.28.0 and sharp 0.35.2. The existing undici 7.29.0 override is
now inside a new advisory range (7.0.0 - 7.29.0, high), and sharp is
under two libheif/librsvg advisories (<= 0.35.5-rc.1, high).
`npm audit fix --force` would install miniflare 5.20261006.1-alpha:
a major and a prerelease, for a test-only dependency.

Move the undici override to 7.29.1 and add sharp 0.35.5, both patch
releases and the exact versions the next miniflare ships with. Same
approach already used for find-my-way, hyperid's uuid and undici.

`test:edge` is the suite that drives workerd through miniflare and it
passes unchanged.

npm audit: 8 (2 critical, 4 high, 2 moderate) -> 5 (2 critical,
1 high, 2 moderate). `npm audit --omit=dev` stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:59:59 -05:00
chrnx 352ba477b4 chore(deps): apply non-breaking dev-dependency audit fixes
`npm audit fix` without --force: every bump stays inside the ranges
package.json already declares, so only the lockfile changes.

Clears proxy-addr (critical), multer and @nestjs/platform-express,
qs, brace-expansion, fast-uri, js-yaml and source-map-js. All of them
are dev or benchmark dependencies; `npm audit --omit=dev` was and
stays at 0.

npm audit: 16 (3 critical, 11 high, 2 moderate) -> 8 (2 critical,
4 high, 2 moderate).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:57:23 -05:00
chrnx 4d1639f7c5 Merge pull request 'FPRD-001a: core safety and adapter correctness (#104 #105 #106 #107 #108 #116)' (#117) from feature/fprd-001a into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 21s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-10-10 16:49:33 +00:00
chrnx 26bacdb304 fix(ws): bound inbound frames synchronously and all-or-nothing
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
Two gaps in boundInbound, both from review of #117.

The bound ran in an async pump reading the adapter's channel. `ws` emits a
whole TCP read's worth of frames synchronously, so the unbounded channel
took the burst before the pump saw the first frame: with maxWsQueue 2, a
2,000-frame burst reached the channel in full before close(1013). boundInbound now taps
the channel through an internal, non-exported hook that runs inside push(),
so each frame is bounded before it is queued. Measured on the Node
listen() path, the same burst now closes on the 3rd frame.

accept() also offered a frame to consumers in order and closed 1013 when a
later queue was full, so the rejected frame had already reached earlier
consumers. Capacity is now checked for every consumer before any delivery.

Refs #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:42:38 -05:00
chrnx 7fa02d16be fix(ws): give every inbound consumer its own bounded queue
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
boundInbound returned one shared FIFO to every `inbound` iterator, with a
single waiter slot. Two consumers waiting at once left one hanging forever,
sequential consumers split frames, and one consumer's return() ended the
stream for all. Node used to fan out through `channel`; Deno, Bun and edge
already shared one iterator before #107, so the bug was older there.

Each iterator now gets its own queue, and maxWsQueue bounds each one. Frames
that arrive before anyone reads still go to the first consumer, which keeps
the mesh `hello`.

Refs #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:23:38 -05:00
chrnx f78c9dc6fd fix(runtime): give ctx.ip the socket peer on Deno and Bun
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.

The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.

The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.

A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.

Closes #116

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:59 -05:00
chrnx ae60cd68a2 fix(http): enforce maxBodyBytes while reading fetch request bodies
The fetch adapter read every body through request.arrayBuffer() and
compared the length afterwards, so Deno, Bun and the edge buffered an
oversized upload in full before refusing it. readFetchBytes now reads
request.body chunk by chunk, stops at the chunk that crosses the limit
and cancels the reader, so no further chunk is pulled.

A content-length that already declares more than the limit is refused
before anything is read, on both adapters. On Node the request used to
wait for its first chunk, which a client that sends only headers never
delivers. A malformed or absent header is ignored and the running count
enforces the limit. The response is the same 413 through onError, and
the route-over-server precedence for maxBodyBytes and maxParts is
untouched; the new tests pin it.

The over-read is proven with a counting stream rather than a status
code, which is the same 413 either way. The stream uses a high-water
mark of 0: the default of 1 pulls a chunk at construction, before any
reader exists, which would make "nothing was read" unprovable.

Socket-level tests on Deno, Bun and workerd use a 1000-byte route limit
so every refused body fits in the socket buffer. With a multi-megabyte
body the client is still writing when the 413 lands and sometimes sees
ECONNRESET instead, which is the transport racing the answer. The Bun
socket test also disables keep-alive: Bun's own fetch client reuses a
socket after a response that arrived before the body was read, and its
next request on it comes back 400 or 431. Node's fetch against the same
Bun server does not.

Closes #105

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:47 -05:00
chrnx 0540bef07b feat(ws)!: bound inbound WebSocket message size and queue
Inbound WebSocket traffic was unbounded per connection: Node used ws's
100 MiB default payload, the other runtimes had no cap of their own, and
the queue behind `inbound` was an unbounded channel on every runtime, so
one client could exhaust memory with large messages or a slow consumer.

Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and
`limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded
in D1. Both are server-wide and validated by createApp, which throws a
TypeError for anything but a positive integer. Enforcement is shared in
`boundInbound`, which subscribes immediately and replaces the
subscribe-before-boot trick in app.upgrade. Node and Bun also get the
native pre-buffer cap; Bun drops the connection without a close frame,
so its peer sees 1006, which is documented and tested. Deno and workerd
expose no such option and check the size after receipt.

BREAKING CHANGE: messages over 1 MiB now close the connection with 1009,
and a connection with 16 unread inbound messages is closed with 1013 on
the next one, including a handler that never reads `inbound`.

Closes #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 59763c9af5 fix(ws): reject malformed upgrades instead of crashing the server
The Node 'upgrade' listener matched the raw request path without the
normalization HTTP runs. A bad percent escape in a param segment threw
URIError synchronously inside the listener, an uncaught exception that
ends the process, and '//' silently matched a route HTTP refuses.

Upgrades now normalize the path first: malformed escapes and repeated
slashes get a 400, an unknown route a written 404 instead of a bare
destroy, and any other throw in the listener a 500. app.upgrade
(Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011.

On Deno the adapter's socket is still CONNECTING when an early 1008 is
sent, and that close was a no-op that left the peer hanging; eventSocket
now defers such a close to 'open'.

Closes #104

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 1069c727c8 fix(http): catch failures at the Node request-listener boundary
The Node request listener was an async function, and http.createServer
ignores the promise a listener returns. Anything that rejected outside
the region where errors convert to a response - a custom static resolver,
a handler header value Node refuses to write (ERR_INVALID_CHAR), a stream
that fails between flushing its headers and its first frame - became an
unhandled rejection, which Node's default mode turns into a process exit.

The listener now hands the request to serve() and catches its rejection
in failSafe(), per refinement decision D2:

- writable: a fixed 500 with connection: close, written through the
  patched writeHead so the security headers still land, without calling
  onError again;
- headers or body already sent, or the client gone: destroy the socket;
- the failure is logged through logger.error first, guarded, with
  String(err) for non-Error values.

No request:end is emitted for these requests: observers do not alter the
response, and the core never completed it. The request gate slot is
already released by the existing finally, which the tests prove.

Deno, Bun and the edge are unaffected: they receive app.fetch's promise
and the runtime answers a rejection itself.

Closes #108

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:32 -05:00
chrnx 53660adcce fix(views): confine static serving to the root's real path
The static resolver's traversal guard compared paths lexically, and the
read that followed it resolved symlinks, so a link inside the root such
as `public/leak -> /etc/hosts` served a file outside it.

Containment now compares real paths. The root's real path is resolved
on the first request and cached (a failed lookup is not, so a root
created after boot still starts serving); the requested file and a
directory's `index.html` are each realpath'd and must lie at or beneath
it, with the `root + sep` rule keeping a sibling such as `root-evil`
out. The lexical guard stays in front, since it rejects `..` without a
syscall.

An escape or a dangling link is a plain miss: 404 through `onError`, or
405/204 where the path has routes. Not 403, so a probe cannot tell a
file outside the root from one that does not exist. Re-pointing a root
symlink at runtime needs a restart. The realpath-to-read race is left
open and marked; closing it needs per-component O_NOFOLLOW, which is
not portable across Node, Deno and Bun.

Closes #106

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:03 -05:00
chrnx 42376c6693 Merge pull request 'docs(agents): stop publishing the address of the private forge' (#102) from docs/scrub-forge-host into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-09-23 17:04:26 +00:00
chrnx 9761b40eb5 docs(agents): stop publishing the address of the private forge
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
The promotion example I added in #101 carried the development forge's full
hostname, and this file is mirrored to GitHub — `develop` reaches the public
`contrib` branch on every merge, so it has been readable by anyone since it
landed.

That host resolves from the public internet, unlike the internal registry named
elsewhere in this repository, so it is a reachable endpoint rather than an
internal naming detail. Replaced with `$GITEA_URL` and `$REPO`, which costs a
reader nothing: `fast-forward-only` was always the part worth documenting, and
it is the part the CLI does not offer.

Not a rewrite of history — the commit stays where it is. Anyone who wanted the
address can still read it there, so this is tidiness going forward rather than a
recall.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:51:53 -05:00
chrnx 7255b8ec30 Merge pull request 'docs(agents): say how the promotion is actually merged' (#101) from docs/promotion-via-api into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 8s
2026-09-23 14:36:12 +00:00
chrnx ca78f0a8e5 docs(agents): say how the promotion is actually merged
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 18s
CI / runtimes (edge) (pull_request) Successful in 14s
The section tells you promotions are fast-forward-only and never says which
tool does that. `tea pr merge` does not: it offers merge, rebase, squash and
rebase-merge, and each one births a commit on main — the exact drift the rule
exists to prevent. Reaching for the obvious command therefore produces the
thing the paragraph above it forbids.

Gitea's API takes the style the CLI omits, so the promotion for 26.9.0-beta.2
went through curl. Recording the call, and the 405 that precedes it: main is
protected and a promotion PR runs its own checks rather than inheriting the
ones develop already passed, so the first attempt is refused for checks that
simply have not finished yet.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 09:34:57 -05:00
147 changed files with 191113 additions and 773 deletions

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
## Environment
- green-tea version:
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- Runtime and version: <!-- Node 22.12 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- OS:
<!--
+6 -6
View File
@@ -13,7 +13,7 @@ jobs:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Every commit needs a Signed-off-by
@@ -38,10 +38,10 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: '18'
node-version: '22'
- run: npm ci
- run: npm run lint
- run: npm run format:check
@@ -73,8 +73,8 @@ jobs:
matrix:
runtime: [deno, bun, edge]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: '22'
# All three need the dependency tree: the edge suite drives workerd from a Node process, and
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0 # full history for a clean push
- name: Push to GitHub
+2 -2
View File
@@ -18,8 +18,8 @@ jobs:
id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: write # create the GitHub release for this tag
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
+2 -2
View File
@@ -19,8 +19,8 @@ jobs:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: '22'
- run: npm ci
+1
View File
@@ -21,6 +21,7 @@ coverage/
# Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs
test/edge/_parity-worker.mjs
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
+14
View File
@@ -55,6 +55,20 @@ feature/* → develop → main → [promote.yml] → GitHub main
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
**`tea pr merge` cannot do the promotion.** The CLI offers `merge`, `rebase`, `squash` and `rebase-merge`, and every one of them births a commit on `main` — the drift this section exists to prevent. Gitea's API has the style the CLI lacks, so promote through it:
```bash
curl -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
-d '{"Do":"fast-forward-only"}' \
"$GITEA_URL/api/v1/repos/$REPO/pulls/<n>/merge"
```
`$GITEA_URL` and `$REPO` are yours to fill in — this file is mirrored to a public repository, and
the address of a private forge is not something to publish. `fast-forward-only` is the part that
matters and is the part the CLI does not offer.
A `405 Not all required status checks successful` means the pull request's own CI has not finished — `main` is protected, and a promotion runs its own checks rather than inheriting `develop`'s. Wait for them; the call is the same afterwards.
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
```bash
+193
View File
@@ -6,6 +6,199 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
### Breaking
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
for Node 18's missing global `crypto` is removed with it.
- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own
default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could
make the server hold a message of any size the runtime would accept. A larger message now closes
the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`.
- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013`
(`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler
that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws`
handler that never reads `inbound` at all: on Node those frames used to be discarded, and they
now count. Raise the bound with `limits.maxWsQueue`.
- **A constrained route param that ties with a sibling, or makes one unreachable, now fails boot**
(#127). Before, the router picked by registration order, and nothing reported it.
Two routes of the same method that branch at the same segment under the same prefix fail
`createApp` when:
- both are constrained, their constraints accept a common segment, and the rest of both patterns
can match one request. The error names both declarations and a witness:
`/u/:id(\d+)` + `/u/:n(\d{1,3})` → `both match '0' (GET /u/0)`. Different spellings of one
language (`\d+` and `[0-9]+`) count. `/u/:id(\d+)/a` + `/u/:n(\d{1,3})/b` share digits but
no request, so they still boot.
- a plain param is next to a constraint that accepts every segment (`[^]*`, `[\s\S]+`) and
outranks it. The error names the dead route and the one that wins.
A plain param next to a constraint that leaves some segments over is the fallback pattern and
still boots: `/u/:id(\d+)` + `/u/:slug` routes digits to `:id` and everything else to `:slug`. An
unescaped `.` does not match line terminators, so `/algo/:a(.*)` leaves `/algo/%0A` to a plain
sibling, and that pair boots too.
WebSocket routes are checked under their own precedence, which is declaration order. So a plain
WS param declared before a constrained one now fails as unreachable. A `@Stream` route sits in
both tables and is checked under both. Mesh routes exported by different teapots are checked
against each other. A local route against a remote one keeps the deliberate local override and
its warning.
The check is exact. The safe subset makes every constraint a sequence of (character set, min,
max) blocks, and the check walks the product of two such sequences. It costs
O(|A|·|B|·(|A|+|B|)·K) per pair, with K ≤ 2048. Measured at under 0.1 ms for `\d{0,2048}`
against `[0-9]{0,2048}`, and about 90 ms for the largest product the 128-character limit allows.
It runs once at boot, and lookup is unchanged. One case is not compared yet: two *different*
constraints at a later segment of an otherwise unreachable route. The route then boots, as
before.
### Added
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
before buffering it; Bun before 1.4 does so by dropping the connection, so its peer sees `1006`
rather than `1009` (Bun 1.4 and later send `1009`). Deno and workerd expose no such option, so there the message is received in full and then
refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
Bun have no connection cap, so set one at the platform or proxy there.
- **`WsSocket.drained()`** (#41): an optional method an adapter's socket provides so the outbound
pump can wait for its send buffer. It resolves once the buffer is at or below the adapter's
high-water mark, or the socket has closed, and at once when it already is. The built-in adapters
all provide it. A socket built without it is never waited on, as before.
### Changed
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`.
It now walks a tree per method, built once from the route table, with mesh routes from teapots
in a tree of their own. This is internal and changes no behaviour: the same route wins, with the
same params, `Allow`, implicit `HEAD` and 404/405, checked against the frozen parity corpus.
`graph()`, `explain()` and `openapi()` still read the declared routes, not the tree. Median lookup
time against the old matcher (jarvis, `bench:lookup`): at 500 routes, static hit −54%, late
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
### Fixed
- **WebSocket outbound respects backpressure** (#41). A `@Ws` handler's async iterator was pulled
as fast as it could yield, whatever the peer read, so a fast producer and a slow client grew the
send buffer without limit: 10,000 frames of 64 KiB put 640 MiB in memory at once. The pump now
waits before each pull while the socket's buffer is over 1 MiB, an internal mark rather than an
option, so a slow peer holds at most about that plus one frame. A peer that keeps up never makes
it wait. If the peer goes away while the pump waits, the wait ends and the iterator's `return()`
runs, as on any other close. Each runtime signals in its own way: Node uses `ws`'s
`bufferedAmount` and send callback, Bun uses `getBufferedAmount()` and its `drain` callback, and
Deno polls `bufferedAmount`, since its `WebSocket` has no drain event. **workerd reports no
buffered amount**, so on the edge the pump never waits and buffering is left to the platform.
- **On Deno, a `@Ws` handler that yields at once no longer loses the connection.** Deno hands the
socket over before it is open. A value yielded in that window was pulled, the pump found the
socket not open, and it gave up: the client got no frame and a close without a code (`1005`).
The pump now waits for the socket to open, as part of the same backpressure wait.
- **A mesh RPC whose body is within `maxBodyBytes` reaches the teapot again** (#120). The 1 MiB
WebSocket cap from #107 also bounded the mesh control channel, so a request body that fit the
HTTP limit could still exceed it once the teacup wrapped it in an RPC frame. A text body near
1 MB was enough, because JSON escaping doubles every `"` and backslash, and any body limit raised
above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel
with `1009`, and every request through that link failed with `503` until it reconnected.
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body
limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB
for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from
the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user
`@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot
raises that limit to the control channel's bound, so an oversized frame on a user route is
refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4
refused natively by dropping the connection (`1006`).
- **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The
16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On
Node, `ws` delivers every frame of one socket read at once, so a teacup sending a burst of RPCs
got the channel closed with `1013`, and every pending request failed with `503`. The control
channel now has its own queue bound of 4,096 frames, or `maxWsQueue` if that is larger, which is
more than one socket read can carry. User `@Ws` routes keep closing `1013` at `maxWsQueue`. Deno
and Bun deliver frames one at a time and did not hit this, but they now share the same bound.
Both larger bounds, this one and the frame size from #120, **apply only once the peer's `hello`
is accepted**. Until then the control channel takes frames of at most 64 KiB and queues at most
16, and closes with `1009` or `1013` past that. An unauthenticated peer can therefore make a
teapot hold about 1 MiB per connection, including while `app.upgrade` waits for a slow boot,
instead of thousands of multi-megabyte frames.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
root that is itself a symlink, keep working.
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
"does not exist". The content-type still follows the requested name, not the link target.
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
while the app runs needs a restart** to take effect. A link swapped inside the root between the
check and the read can still escape; exploiting that needs write access to the served directory.
- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node
request listener was an `async` function, and `http.createServer` ignores the promise it returns,
so anything that rejected outside the region where errors convert to a response — a custom static
resolver, a handler header value Node refuses to write, a stream that fails before its first frame
— became an unhandled rejection, which Node's default mode turns into an exit. The listener now
catches it. While the response is still writable the client gets a fixed 500 with
`connection: close`, written without calling `onError` again; once output has started the socket
is destroyed instead. Either way the failure is logged through `logger.error`. No `request:end` is
emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s
promise, and the runtime answers a rejection with a 500 itself.
- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never
ran the request-path normalization HTTP runs, so a bad percent escape in a param segment
(`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request
was enough to end the process. Upgrades now go through the same normalization: a malformed escape
or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect,
and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on
upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
the socket finished opening now reaches the client instead of leaving it hanging.
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
is refused before any of the body is read, on Node too, where the request used to wait for its
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
the count rather than up front. The status is the same; only how early it comes differs.
- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch
path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as
`''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one
client could exhaust the limit for everyone, above all. Both adapters now hand the peer to
`app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first
`x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer
otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on
the fetch path and now falls back to the peer, as Node always has.
Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all
three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from
your own code has no socket to report and still answers `''` (or the forwarded hop), and so does
a `Request` copied from the one the adapter received. No signature changed. The edge adapter is
unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own
decision.
## [26.9.0-beta.2] - 2026-09-22
### Breaking
+1 -1
View File
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
## Local setup
Node 18 or newer, which is what `engines` requires and what CI runs.
Node 22 or newer, which is what `engines` requires and what CI runs. Node 18 and 20 are end-of-life and no longer supported.
```bash
npm install
+10 -3
View File
@@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
@@ -259,7 +259,14 @@ Patterns match by segment: static, constrained params such as `:id(\d+)`, plain
`@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
Because that subset is linear, constraints are also compared at boot. Two routes that branch at the same segment, under the same prefix and method, fail `createApp`:
- **ambiguous**: two constrained params accept a common segment and the rest of both patterns can match one request. The error names both routes and a segment both accept, such as `/u/:id(\d+)` + `/u/:n(\d{1,3})`, which both match `'0'`. Different spellings of one language (`\d+`, `[0-9]+`) count.
- **unreachable**: a plain `:param` whose constrained sibling accepts every segment, such as `[^]*`, and wins every request the plain one could take.
A constraint next to a plain param is still the fallback pattern: with `/u/:id(\d+)` + `/u/:slug`, digits go to `:id` and everything else goes to `:slug`. An unescaped `.` does not match a line terminator, so `(.*)` does not cover every segment. WebSocket routes follow the same rules, except that they match in declaration order, so a plain WS param declared before a constrained one makes the constrained one unreachable. Mesh routes exported by different teapots are checked against each other; a local route still overrides a remote one, with a warning.
Lookup uses a radix tree per method, built once from the final route table, so a request only walks the branches its path can follow. Precedence is the same as above, and so are `Allow`, 405 and OPTIONS.
## Two layers
@@ -284,7 +291,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
+82
View File
@@ -0,0 +1,82 @@
# Pre-radix router baseline — `ed47836`
The performance half of the CARD-08 parity corpus (FPRD-001, #109), captured before any CARD-07
router change and immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures
the radix index with the **same harness and defaults, on the same host, cpuset and image**, running
`LOOKUP_ROUTERS="base=<ed47836 router>,head=src/http/router.ts"`. Do not re-run into this directory:
a new capture goes in a new directory.
## Files
| File | What it is |
|---|---|
| `lookup-raw.json` | **The D4 baseline.** Interleaved `bench:lookup` with the live linear matcher as A and the byte-identical frozen oracle as B: environment, method, every sample of every round, and the summary. The live column gives the absolute baseline; the B/A ratios give the A/A noise floor. |
| `lookup-summary.txt` | The tables that run printed. |
| `load.txt` | `uptime` and running CI job containers, before and after. |
| `battery-run/` | The superseded first capture (laptop on battery, sequential harness), kept for reference, including its `bench:compare` end-to-end req/s run. |
## Environment
| | |
|---|---|
| Host | jarvis (homelab), Ubuntu 24.04.3 LTS, kernel 6.8.0-138-generic, x86_64 |
| CPU | AMD Ryzen 7 3700X, 8 cores / 16 threads, 2 × 16 MiB L3, governor `schedutil` (host default; not changed) |
| Memory | 62.7 GiB |
| Isolation | `docker run --rm --cpuset-cpus 6,7,14,15`: physical cores 6 and 7 plus their SMT siblings, both on the second CCX. All 16 CPUs were 0.0–0.8% busy in a 5 s sample beforehand. |
| Container | `node:22` (`sha256:5647be70…`), Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
| Power | Not applicable (mains-powered server) |
| Load | 1-minute load 0.27 before, 0.79 after; no CI job containers running (see `load.txt`). jarvis also runs long-lived services (payments-automation, open-webui, windmill, the Gitea act_runner, alloy, beszel), none of them pinned off these cores. |
| Revision | Router at `ed47836c9820c47bf4ed5e902d91e019abdb110a`; harness `ee7fdec`, whose `src/` is byte-identical to `ed47836`. Copied with `git archive`, `npm ci --ignore-scripts` in the container. |
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS`. |
## Method (`bench/lookup.ts` at `ee7fdec`, defaults)
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`.
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**, from the recorded generator (`meta.method.routeGenerator`).
- **Workloads:** static hit, late parameter hit, method miss, path miss; each answer is asserted before timing.
- **Interleaving:** for each cell, every router is warmed for 250 ms (also calibrating ≈25 ms samples), then 21 rounds of one sample per router with the order alternating AB / BA.
- **Repetitions:** 4 fresh processes, with module import order alternating per process → 84 paired rounds per cell. Every sample is kept.
- **Statistics:** absolute = median ns per lookup over all 84 samples; ratio = median of the 84 per-round B/A ratios, with a percentile-bootstrap 95% CI (4000 resamples, seed 10908).
## Baseline: live linear matcher (median ns per lookup)
| Routes | Workload | live median ns | run medians (ns) | run spread |
|---:|---|---:|---|---:|
| 10 | static hit | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
| 10 | late param hit | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
| 10 | method miss | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
| 10 | path miss | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
| 100 | static hit | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
| 100 | late param hit | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
| 100 | method miss | 2,525 | 2,424 / 2,514 / 2,580 / 2,531 | 6.2% |
| 100 | path miss | 3,054 | 2,965 / 3,024 / 3,114 / 3,071 | 4.9% |
| 500 | static hit | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
| 500 | late param hit | 2,931 | 2,830 / 2,804 / 2,980 / 3,016 | 7.2% |
| 500 | method miss | 11,904 | 11,635 / 11,518 / 11,946 / 12,031 | 4.3% |
| 500 | path miss | 15,514 | 15,103 / 14,972 / 15,665 / 16,034 | 6.8% |
## A/A noise floor: identical code, oracle / live
| Routes | Workload | oracle / live median | 95% CI |
|---:|---|---:|---|
| 10 | static hit | 0.9507 (-4.9%) | -13.7% … +11.9% |
| 10 | late param hit | 1.0415 (+4.1%) | -1.6% … +9.8% |
| 10 | method miss | 0.9809 (-1.9%) | -4.4% … +0.8% |
| 10 | path miss | 0.9919 (-0.8%) | -3.2% … +1.4% |
| 100 | static hit | 1.0082 (+0.8%) | -1.9% … +4.5% |
| 100 | late param hit | 1.0247 (+2.5%) | +1.9% … +2.9% |
| 100 | method miss | 1.0055 (+0.6%) | +0.3% … +0.7% |
| 100 | path miss | 1.0165 (+1.7%) | +1.2% … +1.9% |
| 500 | static hit | 1.0107 (+1.1%) | -2.2% … +4.5% |
| 500 | late param hit | 0.9838 (-1.6%) | -2.2% … +0.8% |
| 500 | method miss | 1.0197 (+2.0%) | +1.6% … +2.3% |
| 500 | path miss | 1.0161 (+1.6%) | +0.5% … +2.6% |
**For D4:**
- **Import order.** In-process, the module imported first is faster on the cheapest cell. At 10-route static hit (≈180 ns) the per-run medians swap by about 20% when the import order swaps (run 1: live 156, oracle 200 ns; run 2: live 188, oracle 162 ns). Alternating the import order removes that bias from the median, but it leaves that cell's 95% CI at −13.7 … +11.9%. A ≤5% regression limit cannot be resolved there with this method and sample size.
- **Other 10-route cells.** The CIs are within about ±10% (late parameter hit −1.6 … +9.8%), and the misses are within ±4.4%.
- **100 and 500 routes.** Identical code shows small but systematic offsets of up to +2.9%, with CIs that exclude 1. Treat anything inside ±3% as indistinguishable from no change.
- **500 routes.** The ≥20% improvement target is far outside the noise in every cell.
The options for D4 are to apply the 10-route limit to the miss and late-parameter cells only, to require more rounds for the static cell, or to restate the limit relative to this measured floor. That decision belongs to the owner.
@@ -0,0 +1,94 @@
# Superseded: first baseline, laptop on battery — `ed47836`
> Kept for reference only. **The baseline is `../README.md`**, captured on jarvis with the
> interleaved harness. This run used the earlier sequential harness (`98ea948`), one router per
> process, on a laptop running on battery.
The performance half of the CARD-08 parity corpus (FPRD-001, #109). Captured before any CARD-07
router change; immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures the
radix index with the **same harness, same defaults, same machine class**, and compares against
these files. Do not re-run into this directory: a new capture goes in a new directory.
## Files
| File | What it is |
|---|---|
| `lookup-raw.json` | **The D4 baseline.** `bench:lookup` on the live linear matcher: environment, method, every sample of every run, and the summary. |
| `lookup-summary.txt` | The table `bench:lookup` printed for that run. |
| `lookup-aa-raw.json`, `lookup-aa-summary.txt` | A/A noise check: the live router against the byte-identical frozen oracle (`test/router-parity/oracle.ts`), same alternating protocol. Any difference here is noise. |
| `compare-e2e-raw.json`, `compare-e2e-summary.txt`, `compare-e2e-stderr.txt` | `npm run bench:compare`, run once with this tree as both base and head. **End-to-end req/s signal only**: 50/200 *filler* routes plus base routes, not 10/100/500 total, and not lookup time. It cannot decide D4. |
| `load.txt` | `uptime` before and after each run. |
## Environment
| | |
|---|---|
| Hardware | Apple M4 Max (`Mac16,5`), 16 cores (12 performance + 4 efficiency), 64 GiB |
| Power | **On battery** (84%, discharging) for every run. macOS may manage clocks differently on AC; run the CARD-10 comparison on the same power source, or re-capture both on AC. |
| OS | macOS 27.0.1 (build 26A434), Darwin 27.0.0 arm64 |
| Node | v22.22.2 (V8 12.4.254.21-node.39) |
| Packages | `@green-tea/core@26.9.0-beta.2`; tsx 4.23.5, typescript 5.9.3, vitest 4.1.11, autocannon 8.0.0 (from `package-lock.json`) |
| Core revision | Router source at `ed47836c9820c47bf4ed5e902d91e019abdb110a`. The harness ran from `98ea948` (this branch), whose `src/` is byte-identical to `ed47836` — the branch adds only tests and bench files. |
| Env vars | `LOOKUP_OUT` only (and `LOOKUP_ROUTERS` for the A/A run); no `NODE_OPTIONS`. Recorded in each raw file under `meta.env`. |
| Load | 1-minute load average 2.4–3.4 on 16 cores throughout (see `load.txt` and `meta.loadavgAtStart/End`). Foreground apps were a browser and the window server; nothing else CPU-bound. |
## Method (`bench/lookup.ts`, defaults)
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`. Normalization is excluded.
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**.
- **Generator:** N−2 fillers cycling `GET /res{k}/items`, `POST /res{k}/items`, `GET /res{k}/items/:id`, `PUT /res{k}/items/:id(\d+)`, `GET /res{k}/files/:path*` (k = ⌊i/5⌋), then `GET /static/target/leaf`, then `GET /late/:group/:id` declared last.
- **Workloads:** static hit `GET /static/target/leaf`; late parameter hit `GET /late/g1/42`; method miss `DELETE /static/target/leaf` (Allow `GET, HEAD, OPTIONS`); path miss `GET /nowhere/at/all`. Each answer is asserted before timing.
- **Order:** for each run, for each router (order alternates per run), for count 10 → 100 → 500, for the four workloads in the order above.
- **Warm-up:** 250 ms per cell, time-boxed; it also calibrates iterations so one sample lasts ≈25 ms (iteration counts are stored per cell).
- **Repetitions:** 5 runs, each a fresh child process; 21 samples per cell per run → 105 samples per cell. Every sample is kept.
- **Statistic:** median ns per lookup over all 105 samples. Run spread = (max − min of the five per-run medians) / median.
## Baseline (median ns per lookup, `lookup-raw.json`)
| Routes | Static hit | Late param hit | Method miss | Path miss |
|---:|---:|---:|---:|---:|
| 10 | 61.3 (spread 17.5%) | 123.3 (6.2%) | 313.1 (4.6%) | 247.1 (6.8%) |
| 100 | 67.6 (8.0%) | 343.4 (2.1%) | 1 263.7 (3.5%) | 1 463.3 (3.2%) |
| 500 | 67.8 (7.5%) | 1 326.8 (16.5%) | 6 732.2 (6.5%) | 8 973.4 (2.0%) |
## Noise floor (A/A, `lookup-aa-raw.json`)
Identical matcher code under two labels, alternating order per run. Median difference
(oracle − live) / live:
| Routes | Static hit | Late param hit | Method miss | Path miss |
|---:|---:|---:|---:|---:|
| 10 | +5.2% | 0.0% | +1.2% | +0.2% |
| 100 | −0.1% | −0.8% | −0.1% | +0.1% |
| 500 | −2.7% | +0.3% | −0.4% | +0.1% |
**For D4:** with no code difference at all, the 10-route static hit already moves 5.2% — the
size of the proposed ≤5% regression limit — and per-run medians at 10 routes spread 4.5–17.5%.
That cell is ~60 ns, where a few nanoseconds of timer and scheduling noise are a large fraction.
The ≥20% improvement at 500 routes is well clear of the noise (≤2.7% A/A, ≤16.5% spread on a
1.3–9 µs operation). Whether D4's 10-route limit applies per workload, to a mean across workloads,
or needs more runs is an owner decision; this baseline does not make it.
## End-to-end signal (`bench:compare`, req/s — not lookup time)
Run once, A/A: `AB_BASE` pointed at this same tree, so base and head are identical code. Defaults:
3 rounds × 10 s per case after a 10 s warm-up, 100 connections, alternating side order. Load
average 2.8–3.3 throughout. A few short parity-test runs (seconds each) happened during this
~22-minute run; the lookup runs above had nothing else running.
| Scenario | base req/s | head req/s | Δ |
|---|---:|---:|---:|
| hello | 88,212 | 88,236 | +0.0% |
| param | 86,508 | 85,885 | −0.7% |
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% |
| steps5 | 74,359 | 73,975 | −0.5% |
| validate (POST) | 70,607 | 69,903 | −1.0% |
| hello + security | 83,913 | 83,802 | −0.1% |
| hello + cors predicate | 82,028 | 80,445 | −1.9% |
| preflight + cors predicate | 114,377 | 114,010 | −0.3% |
| param, 50 routes | 82,476 | 82,045 | −0.5% |
| param, 200 routes | 72,957 | 73,306 | +0.5% |
Every row's sample ranges overlap. So with no code change, end-to-end throughput moves up to
±1.9%; the route-width rows show that 200 filler routes already cost ~12% req/s against
`param` with none.
@@ -0,0 +1,207 @@
{
"rounds": 3,
"duration": 10,
"conns": 100,
"rows": [
{
"name": "hello",
"base": 88212.37,
"head": 88235.64,
"delta": 0.0263795202418936,
"separated": false,
"samples": {
"base": [
82493.1,
88503.28,
88212.37
],
"head": [
88177.46,
88235.64,
92826.19
]
}
},
{
"name": "param",
"base": 86507.64,
"head": 85885.1,
"delta": -0.7196358610638246,
"separated": false,
"samples": {
"base": [
81230.55,
86757.82,
86507.64
],
"head": [
83412.37,
86705.46,
85885.1
]
}
},
{
"name": "pipeline (3 steps)",
"base": 80189.1,
"head": 80933.82,
"delta": 0.9287047740902455,
"separated": false,
"samples": {
"base": [
76116.37,
80189.1,
80276.37
],
"head": [
77035.64,
80992,
80933.82
]
}
},
{
"name": "steps5",
"base": 74359.28,
"head": 73975.28,
"delta": -0.5164116704734096,
"separated": false,
"samples": {
"base": [
75272.73,
74359.28,
73928.73
],
"head": [
72235.64,
74813.1,
73975.28
]
}
},
{
"name": "validate (POST)",
"base": 70606.55,
"head": 69902.55,
"delta": -0.997074634010584,
"separated": false,
"samples": {
"base": [
70775.28,
70606.55,
69762.91
],
"head": [
67138.91,
74353.46,
69902.55
]
}
},
{
"name": "hello + security",
"base": 83912.73,
"head": 83802.19,
"delta": -0.13173209833596597,
"separated": false,
"samples": {
"base": [
81928.73,
84709.82,
83912.73
],
"head": [
81742.55,
83802.19,
84512
]
}
},
{
"name": "hello + cors predicate",
"base": 82027.64,
"head": 80445.1,
"delta": -1.9292765219138253,
"separated": false,
"samples": {
"base": [
82481.46,
82027.64,
81381.82
],
"head": [
79368.73,
82213.82,
80445.1
]
}
},
{
"name": "preflight + cors predicate",
"base": 114376.73,
"head": 114010.19,
"delta": -0.3204672838609686,
"separated": false,
"samples": {
"base": [
114580.37,
114376.73,
112322.91
],
"head": [
109669.82,
114813.1,
114010.19
]
}
},
{
"name": "param, 50 routes",
"base": 82475.64,
"head": 82045.1,
"delta": -0.5220208051734956,
"separated": false,
"samples": {
"base": [
82562.91,
82475.64,
82178.91
],
"head": [
78891.64,
82045.1,
82388.37
]
}
},
{
"name": "param, 200 routes",
"base": 72957.1,
"head": 73306.19,
"delta": 0.47848667230467834,
"separated": false,
"samples": {
"base": [
72986.19,
72957.1,
72194.91
],
"head": [
72055.28,
73306.19,
73381.82
]
}
}
],
"cors": {
"base": {
"get": 1,
"preflight": 1
},
"head": {
"get": 1,
"preflight": 1
}
}
}
@@ -0,0 +1,60 @@
[compare] round 1 base hello 82,493 req/s
[compare] round 1 base param 81,231 req/s
[compare] round 1 base pipeline (3 steps) 76,116 req/s
[compare] round 1 base steps5 75,273 req/s
[compare] round 1 base validate (POST) 70,775 req/s
[compare] round 1 base hello + security 81,929 req/s
[compare] round 1 base hello + cors predicate 82,481 req/s
[compare] round 1 base preflight + cors predicate 114,580 req/s
[compare] round 1 base param, 50 routes 82,563 req/s
[compare] round 1 base param, 200 routes 72,986 req/s
[compare] round 1 head hello 88,177 req/s
[compare] round 1 head param 83,412 req/s
[compare] round 1 head pipeline (3 steps) 77,036 req/s
[compare] round 1 head steps5 72,236 req/s
[compare] round 1 head validate (POST) 67,139 req/s
[compare] round 1 head hello + security 81,743 req/s
[compare] round 1 head hello + cors predicate 79,369 req/s
[compare] round 1 head preflight + cors predicate 109,670 req/s
[compare] round 1 head param, 50 routes 78,892 req/s
[compare] round 1 head param, 200 routes 72,055 req/s
[compare] round 2 head hello 88,236 req/s
[compare] round 2 head param 86,705 req/s
[compare] round 2 head pipeline (3 steps) 80,992 req/s
[compare] round 2 head steps5 74,813 req/s
[compare] round 2 head validate (POST) 74,353 req/s
[compare] round 2 head hello + security 83,802 req/s
[compare] round 2 head hello + cors predicate 82,214 req/s
[compare] round 2 head preflight + cors predicate 114,813 req/s
[compare] round 2 head param, 50 routes 82,045 req/s
[compare] round 2 head param, 200 routes 73,306 req/s
[compare] round 2 base hello 88,503 req/s
[compare] round 2 base param 86,758 req/s
[compare] round 2 base pipeline (3 steps) 80,189 req/s
[compare] round 2 base steps5 74,359 req/s
[compare] round 2 base validate (POST) 70,607 req/s
[compare] round 2 base hello + security 84,710 req/s
[compare] round 2 base hello + cors predicate 82,028 req/s
[compare] round 2 base preflight + cors predicate 114,377 req/s
[compare] round 2 base param, 50 routes 82,476 req/s
[compare] round 2 base param, 200 routes 72,957 req/s
[compare] round 3 base hello 88,212 req/s
[compare] round 3 base param 86,508 req/s
[compare] round 3 base pipeline (3 steps) 80,276 req/s
[compare] round 3 base steps5 73,929 req/s
[compare] round 3 base validate (POST) 69,763 req/s
[compare] round 3 base hello + security 83,913 req/s
[compare] round 3 base hello + cors predicate 81,382 req/s
[compare] round 3 base preflight + cors predicate 112,323 req/s
[compare] round 3 base param, 50 routes 82,179 req/s
[compare] round 3 base param, 200 routes 72,195 req/s
[compare] round 3 head hello 92,826 req/s
[compare] round 3 head param 85,885 req/s
[compare] round 3 head pipeline (3 steps) 80,934 req/s
[compare] round 3 head steps5 73,975 req/s
[compare] round 3 head validate (POST) 69,903 req/s
[compare] round 3 head hello + security 84,512 req/s
[compare] round 3 head hello + cors predicate 80,445 req/s
[compare] round 3 head preflight + cors predicate 114,010 req/s
[compare] round 3 head param, 50 routes 82,388 req/s
[compare] round 3 head param, 200 routes 73,382 req/s
@@ -0,0 +1,21 @@
> @green-tea/core@26.9.0-beta.2 bench:compare
> tsx bench/compare.ts
| Scenario | base | head | Δ | |
| --- | --- | --- | --- | --- |
| hello | 88,212 | 88,236 | +0.0% | overlaps |
| param | 86,508 | 85,885 | -0.7% | overlaps |
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% | overlaps |
| steps5 | 74,359 | 73,975 | -0.5% | overlaps |
| validate (POST) | 70,607 | 69,903 | -1.0% | overlaps |
| hello + security | 83,913 | 83,802 | -0.1% | overlaps |
| hello + cors predicate | 82,028 | 80,445 | -1.9% | overlaps |
| preflight + cors predicate | 114,377 | 114,010 | -0.3% | overlaps |
| param, 50 routes | 82,476 | 82,045 | -0.5% | overlaps |
| param, 200 routes | 72,957 | 73,306 | +0.5% | overlaps |
cors.origins calls — base: 1 per GET, 1 per preflight
cors.origins calls — head: 1 per GET, 1 per preflight
exit 0
@@ -0,0 +1,6 @@
uptime before: 17:01 up 9 days, 7:50, 1 user, load averages: 2.47 2.14 6.86
uptime after: 17:02 up 9 days, 7:51, 1 user, load averages: 2.58 2.21 6.64
A/A uptime before: 17:02 up 9 days, 7:51, 1 user, load averages: 3.42 2.40 6.66
A/A uptime after: 17:03 up 9 days, 7:53, 1 user, load averages: 2.89 2.48 6.26
bench:compare uptime before: 17:04 up 9 days, 7:53, 1 user, load averages: 2.98 2.51 6.25
bench:compare uptime after: 17:26 up 9 days, 8:15, 1 user, load averages: 2.82 3.32 4.29
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,33 @@
> @green-tea/core@26.9.0-beta.2 bench:lookup
> tsx bench/lookup.ts
| router | routes | workload | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| live | 10 | static hit | 62.0 | 57.9 / 65.8 / 60.3 / 62.7 / 61.8 | 12.7% |
| live | 10 | late param hit | 123.8 | 124.0 / 120.4 / 122.1 / 124.3 / 128.4 | 6.4% |
| live | 10 | method miss | 309.0 | 305.7 / 305.6 / 320.1 / 310.8 / 311.6 | 4.7% |
| live | 10 | path miss | 248.4 | 242.7 / 242.5 / 253.7 / 251.0 / 248.7 | 4.5% |
| live | 100 | static hit | 69.5 | 66.7 / 68.7 / 69.2 / 71.6 / 71.5 | 7.1% |
| live | 100 | late param hit | 352.2 | 345.1 / 348.3 / 349.9 / 355.2 / 365.1 | 5.7% |
| live | 100 | method miss | 1265.3 | 1273.8 / 1256.0 / 1254.2 / 1279.7 / 1267.1 | 2.0% |
| live | 100 | path miss | 1464.9 | 1462.8 / 1451.3 / 1462.3 / 1485.2 / 1470.6 | 2.3% |
| live | 500 | static hit | 67.8 | 67.2 / 66.9 / 68.1 / 69.3 / 67.7 | 3.4% |
| live | 500 | late param hit | 1313.7 | 1362.0 / 1293.9 / 1309.7 / 1313.7 / 1316.9 | 5.2% |
| live | 500 | method miss | 6778.2 | 7068.9 / 6783.2 / 6634.3 / 6816.4 / 6689.2 | 6.4% |
| live | 500 | path miss | 9005.3 | 9445.9 / 9015.5 / 8965.0 / 9032.4 / 8834.1 | 6.8% |
| oracle | 10 | static hit | 65.2 | 62.2 / 66.6 / 66.6 / 65.2 / 58.0 | 13.1% |
| oracle | 10 | late param hit | 123.9 | 130.7 / 123.5 / 125.2 / 122.9 / 120.1 | 8.5% |
| oracle | 10 | method miss | 312.7 | 311.4 / 314.2 / 312.2 / 316.8 / 309.1 | 2.4% |
| oracle | 10 | path miss | 249.0 | 248.6 / 253.1 / 247.3 / 249.0 / 248.9 | 2.3% |
| oracle | 100 | static hit | 69.4 | 69.5 / 71.1 / 69.8 / 67.5 / 66.7 | 6.4% |
| oracle | 100 | late param hit | 349.3 | 347.5 / 352.5 / 349.6 / 347.2 / 354.0 | 1.9% |
| oracle | 100 | method miss | 1263.6 | 1294.1 / 1243.1 / 1251.2 / 1286.5 / 1258.0 | 4.0% |
| oracle | 100 | path miss | 1466.2 | 1511.6 / 1464.0 / 1459.5 / 1480.7 / 1449.1 | 4.3% |
| oracle | 500 | static hit | 66.0 | 67.0 / 67.3 / 65.8 / 64.9 / 65.1 | 3.6% |
| oracle | 500 | late param hit | 1317.6 | 1313.2 / 1310.2 / 1323.5 / 1294.5 / 1363.2 | 5.2% |
| oracle | 500 | method miss | 6753.3 | 6717.3 / 6758.7 / 6666.4 / 6876.3 / 6750.7 | 3.1% |
| oracle | 500 | path miss | 9015.3 | 8998.0 / 9021.6 / 8980.8 / 9100.7 / 8884.0 | 2.4% |
load average: start 3.42 2.40 6.66, end 2.89 2.48 6.26
raw samples: bench/baseline/router-ed47836/lookup-aa-raw.json
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,21 @@
> @green-tea/core@26.9.0-beta.2 bench:lookup
> tsx bench/lookup.ts
| router | routes | workload | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| live | 10 | static hit | 61.3 | 64.4 / 61.0 / 68.4 / 58.0 / 57.6 | 17.5% |
| live | 10 | late param hit | 123.3 | 122.4 / 128.1 / 123.3 / 123.7 / 120.4 | 6.2% |
| live | 10 | method miss | 313.1 | 303.2 / 314.0 / 317.6 / 317.2 / 304.7 | 4.6% |
| live | 10 | path miss | 247.1 | 243.8 / 246.0 / 256.5 / 251.7 / 239.7 | 6.8% |
| live | 100 | static hit | 67.6 | 67.6 / 70.3 / 71.7 / 66.9 / 66.3 | 8.0% |
| live | 100 | late param hit | 343.4 | 339.7 / 345.5 / 346.8 / 343.0 / 341.0 | 2.1% |
| live | 100 | method miss | 1263.7 | 1253.2 / 1236.5 / 1280.9 / 1261.0 / 1264.6 | 3.5% |
| live | 100 | path miss | 1463.3 | 1444.6 / 1442.4 / 1489.2 / 1467.6 / 1467.1 | 3.2% |
| live | 500 | static hit | 67.8 | 69.7 / 68.1 / 68.2 / 64.6 / 65.1 | 7.5% |
| live | 500 | late param hit | 1326.8 | 1480.6 / 1262.0 / 1309.9 / 1328.9 / 1331.8 | 16.5% |
| live | 500 | method miss | 6732.2 | 7072.0 / 6659.6 / 6796.0 / 6631.5 / 6699.6 | 6.5% |
| live | 500 | path miss | 8973.4 | 8915.3 / 8994.7 / 9052.0 / 8876.0 / 8981.4 | 2.0% |
load average: start 2.47 2.14 6.86, end 2.58 2.21 6.64
raw samples: bench/baseline/router-ed47836/lookup-raw.json
+3
View File
@@ -0,0 +1,3 @@
before: 2026-10-10T22:42:38Z 17:42:38 up 44 days, 17:31, 2 users, load average: 0.27, 0.11, 0.04
ci job containers: 0
after: 2026-10-10T22:43:54Z 17:43:54 up 44 days, 17:32, 2 users, load average: 0.79, 0.31, 0.12
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | live | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
| 10 | static hit | oracle | 176.8 | 199.9 / 161.9 / 195.0 / 162.5 | 21.5% |
| 10 | late param hit | live | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
| 10 | late param hit | oracle | 337.6 | 343.0 / 329.2 / 356.3 / 324.3 | 9.5% |
| 10 | method miss | live | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
| 10 | method miss | oracle | 768.8 | 770.0 / 764.6 / 833.1 / 762.5 | 9.2% |
| 10 | path miss | live | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
| 10 | path miss | oracle | 606.6 | 603.8 / 610.1 / 657.9 / 591.5 | 10.9% |
| 100 | static hit | live | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
| 100 | static hit | oracle | 206.9 | 211.7 / 196.6 / 213.9 / 201.7 | 8.4% |
| 100 | late param hit | live | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
| 100 | late param hit | oracle | 893.0 | 888.7 / 869.0 / 942.1 / 895.2 | 8.2% |
| 100 | method miss | live | 2524.8 | 2424.2 / 2513.7 / 2579.6 / 2531.5 | 6.2% |
| 100 | method miss | oracle | 2515.2 | 2473.4 / 2527.3 / 2595.9 / 2509.5 | 4.9% |
| 100 | path miss | live | 3054.2 | 2965.2 / 3023.7 / 3113.5 / 3070.6 | 4.9% |
| 100 | path miss | oracle | 3075.6 | 3002.5 / 3087.9 / 3179.5 / 3064.3 | 5.8% |
| 500 | static hit | live | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
| 500 | static hit | oracle | 206.3 | 212.1 / 197.8 / 213.2 / 201.1 | 7.5% |
| 500 | late param hit | live | 2930.6 | 2829.6 / 2804.3 / 2980.0 / 3016.2 | 7.2% |
| 500 | late param hit | oracle | 2878.8 | 2865.8 / 2832.6 / 2916.8 / 2881.2 | 2.9% |
| 500 | method miss | live | 11903.6 | 11635.5 / 11518.4 / 11946.5 / 12031.2 | 4.3% |
| 500 | method miss | oracle | 12101.5 | 11822.5 / 11856.4 / 12275.6 / 12190.0 | 3.7% |
| 500 | path miss | live | 15513.7 | 15103.4 / 14971.6 / 15664.8 / 16034.1 | 6.8% |
| 500 | path miss | oracle | 15719.6 | 15158.8 / 15479.0 / 16084.0 / 15885.7 | 5.9% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle / live | 0.9507 (-4.9%) | 0.8629 – 1.1186 (-13.7% … +11.9%) | 84 |
| 10 | late param hit | oracle / live | 1.0415 (+4.1%) | 0.9840 – 1.0982 (-1.6% … +9.8%) | 84 |
| 10 | method miss | oracle / live | 0.9809 (-1.9%) | 0.9563 – 1.0076 (-4.4% … +0.8%) | 84 |
| 10 | path miss | oracle / live | 0.9919 (-0.8%) | 0.9676 – 1.0141 (-3.2% … +1.4%) | 84 |
| 100 | static hit | oracle / live | 1.0082 (+0.8%) | 0.9808 – 1.0453 (-1.9% … +4.5%) | 84 |
| 100 | late param hit | oracle / live | 1.0247 (+2.5%) | 1.0192 – 1.0292 (+1.9% … +2.9%) | 84 |
| 100 | method miss | oracle / live | 1.0055 (+0.6%) | 1.0033 – 1.0072 (+0.3% … +0.7%) | 84 |
| 100 | path miss | oracle / live | 1.0165 (+1.7%) | 1.0119 – 1.0185 (+1.2% … +1.9%) | 84 |
| 500 | static hit | oracle / live | 1.0107 (+1.1%) | 0.9782 – 1.0453 (-2.2% … +4.5%) | 84 |
| 500 | late param hit | oracle / live | 0.9838 (-1.6%) | 0.9784 – 1.0076 (-2.2% … +0.8%) | 84 |
| 500 | method miss | oracle / live | 1.0197 (+2.0%) | 1.0161 – 1.0235 (+1.6% … +2.3%) | 84 |
| 500 | path miss | oracle / live | 1.0161 (+1.6%) | 1.0047 – 1.0257 (+0.5% … +2.6%) | 84 |
load average: start 0.27 0.11 0.04, end 0.79 0.31 0.12; cpuset 6-7,14-15
raw samples: out/lookup-raw.json
+358
View File
@@ -0,0 +1,358 @@
/**
* Focused route-lookup benchmark — the D4 instrument for the radix router (FPRD-001 CARD-08/10, #109).
*
* `bench:compare` measures req/s end to end, where lookup is a few percent of a request and drowns
* in socket and pipeline noise. This measures the lookup alone: exactly what `dispatch` in
* `src/http/core.ts` does with an already-normalized path — `resolveRoute`, and on a miss
* `allowedMethods` for the 404/405 decision. Normalization is excluded: CARD-07 does not touch it.
*
* Usage:
*
* npm run bench:lookup
* LOOKUP_ROUTERS="base=/tmp/base/src/http/router.ts,head=src/http/router.ts" npm run bench:lookup
* LOOKUP_ROUTERS="live=src/http/router.ts,oracle=test/router-parity/oracle.ts" npm run bench:lookup # A/A
*
* Each router is a module exporting `resolveRoute` and `allowedMethods` with the `src/http/router.ts`
* signatures. All routers are loaded into the same process and **interleaved**: per cell, every
* router is warmed, then each round takes one sample from each router, alternating which goes first
* (AB, BA, AB, ...). Fresh processes alternate the whole router order, warm-up included. Every router after the first is reported against the first as the median of the
* per-round B/A ratios, with a bootstrap 95% CI. Interleaving puts drift and background load on both
* sides of each ratio instead of on whichever ran later. With one router it reports absolute numbers
* only. Do not edit the generator, the workloads or the defaults between a baseline and its
* comparison: they are the method.
*
* Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (4 fresh
* processes, router order alternating), `LOOKUP_ROUNDS` (21 per cell per run, minimum 15), `LOOKUP_SAMPLE_MS` (25),
* `LOOKUP_WARMUP_MS` (250 per router per cell), `LOOKUP_OUT` (bench/lookup-results.json). Any other
* `LOOKUP_*` variable (e.g. `LOOKUP_HOST`, `LOOKUP_CPUSET`) is copied into the record as a note.
*/
import { spawn, execFileSync } from 'child_process';
import { writeFileSync, readFileSync } from 'fs';
import os from 'os';
import { dirname, resolve } from 'path';
import { pathToFileURL } from 'url';
const ROUTE_COUNTS = [10, 100, 500];
const RUNS = Number(process.env.LOOKUP_RUNS ?? 4);
const ROUNDS = Math.max(15, Number(process.env.LOOKUP_ROUNDS ?? 21));
const BOOTSTRAP = 4000;
const SAMPLE_MS = Number(process.env.LOOKUP_SAMPLE_MS ?? 25);
const WARMUP_MS = Number(process.env.LOOKUP_WARMUP_MS ?? 250);
const OUT = process.env.LOOKUP_OUT ?? 'bench/lookup-results.json';
interface Route {
method: string;
pattern: string;
transport: 'buffer';
handler: () => Promise<{ status: number; headers: Record<string, string>; body: string }>;
}
interface RouterModule {
resolveRoute(routes: Route[], method: string, path: string): { def: Route } | undefined;
allowedMethods(routes: Route[], path: string): string[];
}
/** Five REST-shaped filler routes per resource, cycled, so every count has statics, params, constraints and catch-alls. */
const FILLER: Array<(k: number) => [string, string]> = [
(k) => ['GET', `/res${k}/items`],
(k) => ['POST', `/res${k}/items`],
(k) => ['GET', `/res${k}/items/:id`],
(k) => ['PUT', `/res${k}/items/:id(\\d+)`],
(k) => ['GET', `/res${k}/files/:path*`],
];
export const ROUTE_GENERATOR =
'N total HTTP routes: N-2 fillers (i = 0..N-3, shape FILLER[i % 5] with k = floor(i / 5): GET /res{k}/items, ' +
'POST /res{k}/items, GET /res{k}/items/:id, PUT /res{k}/items/:id(\\d+), GET /res{k}/files/:path*), then ' +
'GET /static/target/leaf, then GET /late/:group/:id declared last. All buffer transport.';
const handler = async () => ({ status: 200, headers: {}, body: '' });
export function buildRoutes(total: number): Route[] {
const fillers = Array.from({ length: total - 2 }, (_, i): Route => {
const [method, pattern] = FILLER[i % FILLER.length](Math.floor(i / FILLER.length));
return { method, pattern, transport: 'buffer', handler };
});
return [
...fillers,
{ method: 'GET', pattern: '/static/target/leaf', transport: 'buffer', handler },
{ method: 'GET', pattern: '/late/:group/:id', transport: 'buffer', handler },
];
}
interface Workload {
name: string;
method: string;
path: string;
/** What the lookup must answer; checked before timing, so a broken implementation cannot post a number. */
expect: string;
}
export const WORKLOADS: Workload[] = [
{ name: 'static hit', method: 'GET', path: '/static/target/leaf', expect: 'hit /static/target/leaf' },
{ name: 'late param hit', method: 'GET', path: '/late/g1/42', expect: 'hit /late/:group/:id' },
{ name: 'method miss', method: 'DELETE', path: '/static/target/leaf', expect: 'allow GET,HEAD,OPTIONS' },
{ name: 'path miss', method: 'GET', path: '/nowhere/at/all', expect: 'allow ' },
];
/** One lookup, as `dispatch` performs it. Returns a value so the work cannot be optimised away. */
function lookup(router: RouterModule, routes: Route[], w: Workload): string {
const matched = router.resolveRoute(routes, w.method, w.path);
if (matched) return `hit ${matched.def.pattern}`;
return `allow ${router.allowedMethods(routes, w.path).join(',')}`;
}
interface Cell {
routes: number;
workload: string;
/** Calibrated per router; a sample is `iterations` lookups. */
iterations: Record<string, number>;
/** Round order, e.g. ['live', 'oracle'] then ['oracle', 'live']. */
orders: string[][];
/** One entry per router, one sample (ns per lookup) per round, in round order. */
samplesNs: Record<string, number[]>;
}
type Loaded = Array<{ label: string; router: RouterModule }>;
let sink = 0;
function warm(router: RouterModule, routes: Route[], w: Workload): number {
const answer = lookup(router, routes, w);
if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`);
// Time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS.
let ops = 0;
const warmStart = process.hrtime.bigint();
const warmBudget = BigInt(WARMUP_MS * 1_000_000);
while (process.hrtime.bigint() - warmStart < warmBudget) {
for (let i = 0; i < 100; i++) sink += lookup(router, routes, w).length;
ops += 100;
}
const nsPerOp = Number(process.hrtime.bigint() - warmStart) / ops;
return Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp));
}
function sample(router: RouterModule, routes: Route[], w: Workload, iterations: number): number {
const start = process.hrtime.bigint();
for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length;
return Number(process.hrtime.bigint() - start) / iterations;
}
function measureCell(loaded: Loaded, routes: Route[], w: Workload): Cell {
const iterations: Record<string, number> = {};
const samplesNs: Record<string, number[]> = {};
const orders: string[][] = [];
for (const { label, router } of loaded) {
iterations[label] = warm(router, routes, w);
samplesNs[label] = [];
}
for (let round = 0; round < ROUNDS; round++) {
const order = round % 2 === 0 ? loaded : [...loaded].reverse();
orders.push(order.map(({ label }) => label));
for (const { label, router } of order) samplesNs[label].push(sample(router, routes, w, iterations[label]));
}
return { routes: routes.length, workload: w.name, iterations, orders, samplesNs };
}
async function child(routers: Array<[string, string]>): Promise<void> {
// Router order alternates per run (LOOKUP_IMPORT_REVERSED): import order, warm-up order and which
// router opens each cell's first round. Whichever router V8 sees first, in import or in the shared
// `lookup` call site, can bias an in-process comparison of otherwise identical code; alternating
// all of it spreads that over both sides. Reversing only the import order left an A/A bias of up
// to +8% on the second-listed router (CARD-10).
const ordered = process.env.LOOKUP_IMPORT_REVERSED === '1' ? [...routers].reverse() : routers;
const loaded: Loaded = [];
for (const [label, path] of ordered)
loaded.push({ label, router: (await import(pathToFileURL(resolve(path)).href)) as RouterModule });
const cells: Cell[] = [];
for (const count of ROUTE_COUNTS) {
const routes = buildRoutes(count);
for (const w of WORKLOADS) cells.push(measureCell(loaded, routes, w));
}
if (sink === 42) process.stderr.write(''); // keeps `sink` observable
process.stdout.write(`${JSON.stringify({ cells })}\n`);
}
function runChild(spec: string, importReversed: boolean): Promise<{ cells: Cell[] }> {
return new Promise((resolvePromise, reject) => {
const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], {
env: { ...process.env, LOOKUP_CHILD: spec, LOOKUP_IMPORT_REVERSED: importReversed ? '1' : '0' },
stdio: ['ignore', 'pipe', 'inherit'],
});
let out = '';
proc.stdout.on('data', (d) => (out += d));
proc.on('exit', (code) =>
code === 0 ? resolvePromise(JSON.parse(out)) : reject(new Error(`child exited ${code}`)),
);
});
}
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;
};
/** Deterministic PRNG for the bootstrap, so the same raw samples always give the same interval. */
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** Percentile bootstrap 95% CI of the median of `xs`. */
function bootstrapMedianCi(xs: number[]): [number, number] {
const rng = mulberry32(10908);
const medians: number[] = [];
for (let b = 0; b < BOOTSTRAP; b++) medians.push(median(xs.map(() => xs[Math.floor(rng() * xs.length)])));
medians.sort((a, b) => a - b);
return [medians[Math.floor(BOOTSTRAP * 0.025)], medians[Math.ceil(BOOTSTRAP * 0.975) - 1]];
}
function git(cwd: string, ...args: string[]): string {
try {
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch {
return 'unavailable';
}
}
function cpuset(): string {
for (const file of ['/sys/fs/cgroup/cpuset.cpus.effective', '/sys/fs/cgroup/cpuset/cpuset.effective_cpus']) {
try {
return readFileSync(file, 'utf8').trim();
} catch {
/* not Linux, or not this cgroup layout */
}
}
return 'n/a';
}
function environment(routers: Array<[string, string]>) {
const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string };
return {
startedAt: new Date().toISOString(),
hostname: os.hostname(),
node: process.version,
v8: process.versions.v8,
platform: `${os.platform()} ${os.release()} ${os.arch()}`,
cpu: os.cpus()[0]?.model,
cpus: os.cpus().length,
cpuset: cpuset(),
memoryBytes: os.totalmem(),
loadavgAtStart: os.loadavg(),
package: `${pkg.name}@${pkg.version}`,
harnessCommit: process.env.LOOKUP_COMMIT ?? git('.', 'rev-parse', 'HEAD'),
routers: routers.map(([label, path]) => ({ label, path })),
env: Object.fromEntries(
Object.entries(process.env).filter(([k]) => k.startsWith('LOOKUP_') || k === 'NODE_OPTIONS'),
),
method: {
routeCounts: ROUTE_COUNTS,
routeCountMeaning: 'total registered HTTP routes',
routeGenerator: ROUTE_GENERATOR,
workloads: WORKLOADS,
workloadOrder:
'for each run (fresh process; module import order reversed on even-numbered runs): for count in routeCounts: ' +
'for workload in workloads: warm every router, ' +
'then ROUNDS rounds of one sample per router, order alternating AB/BA per round',
operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)',
runs: RUNS,
roundsPerCellPerRun: ROUNDS,
sampleMs: SAMPLE_MS,
warmupMsPerRouterPerCell: WARMUP_MS,
ratio: 'per round, sample(B) / sample(A) with A the first router; median over all rounds of all runs',
ci: `percentile bootstrap of the median ratio, ${BOOTSTRAP} resamples, seed 10908`,
unit: 'ns per lookup (sample time / iterations)',
},
};
}
function summarize(labels: string[], runs: Array<{ run: number; cells: Cell[] }>) {
return ROUTE_COUNTS.flatMap((count) =>
WORKLOADS.map((w) => {
const cells = runs.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!);
const routers = labels.map((label) => {
const runMedians = cells.map((c) => median(c.samplesNs[label]));
const med = median(cells.flatMap((c) => c.samplesNs[label]));
return {
router: label,
medianNs: med,
runMediansNs: runMedians,
runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100,
};
});
const ratios = labels.slice(1).map((label) => {
const paired = cells.flatMap((c) => c.samplesNs[label].map((b, i) => b / c.samplesNs[labels[0]][i]));
const [low, high] = bootstrapMedianCi(paired);
return { b: label, a: labels[0], medianRatio: median(paired), ci95: [low, high], rounds: paired.length };
});
return { routes: count, workload: w.name, routers, ratios };
}),
);
}
const pct = (ratio: number): string => `${ratio >= 1 ? '+' : ''}${((ratio - 1) * 100).toFixed(1)}%`;
async function main(): Promise<void> {
const spec = process.env.LOOKUP_CHILD
? process.env.LOOKUP_CHILD
: (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts');
const routers = spec.split(',').map((entry) => entry.split('=') as [string, string]);
if (process.env.LOOKUP_CHILD) return child(routers);
const labels = routers.map(([label]) => label);
const meta = environment(routers);
const runs: Array<{ run: number; importReversed: boolean; cells: Cell[] }> = [];
for (let run = 0; run < RUNS; run++) {
runs.push({ run: run + 1, importReversed: run % 2 === 1, ...(await runChild(spec, run % 2 === 1)) });
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} done\n`);
}
const summary = summarize(labels, runs);
const loadavgAtEnd = os.loadavg();
writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`);
console.log('| routes | workload | router | median ns/op | run medians (ns) | run spread |');
console.log('| --- | --- | --- | --- | --- | --- |');
for (const cell of summary)
for (const r of cell.routers)
console.log(
`| ${cell.routes} | ${cell.workload} | ${r.router} | ${r.medianNs.toFixed(1)} | ` +
`${r.runMediansNs.map((n) => n.toFixed(1)).join(' / ')} | ${r.runSpreadPct.toFixed(1)}% |`,
);
if (labels.length > 1) {
console.log('\n| routes | workload | B / A | median ratio | 95% CI | rounds |');
console.log('| --- | --- | --- | --- | --- | --- |');
for (const cell of summary)
for (const r of cell.ratios)
console.log(
`| ${cell.routes} | ${cell.workload} | ${r.b} / ${r.a} | ${r.medianRatio.toFixed(4)} (${pct(r.medianRatio)}) | ` +
`${r.ci95.map((x) => x.toFixed(4)).join(' – ')} (${pct(r.ci95[0])} … ${pct(r.ci95[1])}) | ${r.rounds} |`,
);
}
console.log(
`\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, ` +
`end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}; cpuset ${meta.cpuset}`,
);
console.log(`raw samples: ${OUT}`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+131
View File
@@ -0,0 +1,131 @@
# Radix router lookup evidence — `b128139` (CARD-10, D4)
> **Superseded by `../router-ed19f16/`.** This run found the 10-route regression from `a2b71e2`, which #131 fixed, and the A/A order bias, which `ed19f16` fixed in `bench/lookup.ts`. It is kept as the record of both.
The formal D4 comparison for the radix index (FPRD-001 CARD-10, #109): the radix router at
`b128139` against the frozen pre-radix linear matcher, with the harness, host, cpuset and image of
the baseline in `bench/baseline/router-ed47836/`. `b128139` is `develop` at `cb123e3` (CARD-07,
PR #128) plus the internal seam counters added for the no-recompilation test; the attribution run
below shows those counters do not move the numbers.
**Verdict: D4 fails at 10 routes** (late param hit, method miss, path miss). 100 and 500 routes pass.
The cause is localized below to one CARD-07 commit. Per the card, no threshold was relaxed and no
`src/` change was made to recover it; this is evidence for an owner decision.
## Files
| File | What it is |
|---|---|
| `lookup-raw.json` | **The D4 run.** A = `oracle` (`test/router-parity/oracle.ts`, the pre-radix linear matcher), B = `radix` (`src/http/router.ts` at `b128139`). Environment, method, every sample of every round, and the summary. |
| `lookup-summary.txt` | The tables that run printed. |
| `aa-raw.json`, `aa-summary.txt` | A/A noise band, same settings: `oracle` against `oracle-copy`, a byte-identical copy of the oracle at another path (sha256 `8875ec12…`, same as the original), so V8 sees two separate modules. |
| `attrib-raw.json`, `attrib-summary.txt` | Diagnostic only, not part of the D4 verdict: oracle against the radix router at `5e0ae94`, `cb123e3` and `b128139` in the same process. |
| `load.txt` | `uptime` and running CI job containers before and after each run. |
## Environment
| | |
|---|---|
| Host | jarvis (homelab), Ubuntu 24.04, kernel 6.8.0-138-generic, x86_64, AMD Ryzen 7 3700X, 62.7 GiB — same host as the baseline |
| Isolation | `docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000` (cpuset reported inside the container: `6-7,14-15`) |
| Container | `node:22`, image id `sha256:5647be709086c696ff32edaaf1c70cd26d1da6ab2b39c32f3c7b4c4a31957e37` — the baseline's image; Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
| Revision | `b128139e2f4447af52b6b6d1a0d60d92664e40f8`, copied with `git archive`; `npm ci --ignore-scripts` inside the container |
| Load (1/5/15 min) | D4 run: 0.24 0.25 0.11 before, 1.92 1.40 0.66 after. A/A: 1.92 1.40 0.66 before, 1.62 1.50 0.92 after. No CI job containers at any point. The rise is the benchmark itself (16 consecutive processes) plus jarvis's long-lived services; see `load.txt`. |
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS` |
## Method
`bench/lookup.ts` unchanged from the baseline (defaults: 250 ms warm-up per router per cell, ≈25 ms
samples, rounds alternating AB/BA, import order alternating per process, bootstrap 95% CI of the
median paired ratio, 4000 resamples, seed 10908). The one difference is more repetitions, as the
owner asked, to narrow the CIs: **16 fresh processes × 21 rounds = 336 paired rounds per cell**
(baseline: 4 × 21 = 84).
```sh
docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 -e HOME=/tmp -v "$PWD":/w -w /w \
-e LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,radix=src/http/router.ts" \
-e LOOKUP_RUNS=16 -e LOOKUP_ROUNDS=21 -e LOOKUP_OUT=out/lookup-raw.json \
-e LOOKUP_COMMIT=b128139e2f4447af52b6b6d1a0d60d92664e40f8 -e LOOKUP_HOST=jarvis -e LOOKUP_CPUSET=6,7,14,15 \
-e LOOKUP_DOCKER="$(docker --version)" -e LOOKUP_KERNEL="$(uname -r)" \
-e LOOKUP_IMAGE="$(docker image inspect node:22 --format '{{.Id}}')" \
node:22 node --import tsx bench/lookup.ts
```
The A/A run is the same command with `LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,oracle-copy=aa/oracle-copy.ts"`
and `LOOKUP_OUT=out/aa-raw.json`, started immediately after.
## D4 rule (accepted by the owner, 2026-10-10)
Per cell, B/A = median lookup time ratio radix / oracle with its bootstrap 95% CI.
- No regression anywhere: a cell **fails** only if its CI **lower** bound is above +5%.
- At 500 routes, late param hit, method miss and path miss must also have a CI **upper** bound ≤ −20%. Static hit at 500: no regression only.
## D4 verdict — radix / oracle, 336 paired rounds per cell
| Routes | Workload | oracle ns | radix ns | radix / oracle | 95% CI | Rule | Verdict |
|---:|---|---:|---:|---:|---|---|---|
| 10 | static hit | 189.3 | 79.9 | 0.4198 (−58.0%) | −59.5% … −56.5% | lower ≤ +5% | PASS |
| 10 | late param hit | 335.8 | 495.8 | 1.5253 (+52.5%) | +51.6% … +53.0% | lower ≤ +5% | **FAIL** |
| 10 | method miss | 774.2 | 1,032.5 | 1.3181 (+31.8%) | +31.3% … +32.3% | lower ≤ +5% | **FAIL** |
| 10 | path miss | 605.2 | 1,216.1 | 2.0192 (+101.9%) | +100.6% … +102.9% | lower ≤ +5% | **FAIL** |
| 100 | static hit | 203.1 | 94.4 | 0.4632 (−53.7%) | −53.9% … −53.4% | lower ≤ +5% | PASS |
| 100 | late param hit | 880.6 | 499.1 | 0.5726 (−42.7%) | −42.9% … −42.6% | lower ≤ +5% | PASS |
| 100 | method miss | 2,515.1 | 1,048.2 | 0.4193 (−58.1%) | −58.3% … −57.8% | lower ≤ +5% | PASS |
| 100 | path miss | 3,042.8 | 1,218.2 | 0.4042 (−59.6%) | −59.9% … −59.4% | lower ≤ +5% | PASS |
| 500 | static hit | 203.9 | 96.3 | 0.4673 (−53.3%) | −53.5% … −53.2% | lower ≤ +5% | PASS |
| 500 | late param hit | 2,825.2 | 498.6 | 0.1751 (−82.5%) | −82.6% … −82.4% | upper ≤ −20% | PASS |
| 500 | method miss | 11,838.0 | 1,052.0 | 0.0887 (−91.1%) | −91.2% … −91.1% | upper ≤ −20% | PASS |
| 500 | path miss | 15,335.4 | 1,218.9 | 0.0786 (−92.1%) | −92.2% … −92.1% | upper ≤ −20% | PASS |
The oracle's absolute medians match the baseline's live linear matcher within a few percent in every
cell (e.g. 10-route late param 335.8 vs 328.4 ns, 500-route path miss 15,335 vs 15,514 ns), so the
host and setup are comparable with the baseline capture.
## A/A noise band — oracle-copy / oracle, same settings
| Routes | Workload | ratio | 95% CI |
|---:|---|---:|---|
| 10 | static hit | 1.0421 (+4.2%) | +2.1% … +5.7% |
| 10 | late param hit | 1.0829 (+8.3%) | +7.1% … +9.1% |
| 10 | method miss | 0.9862 (−1.4%) | −2.0% … +0.2% |
| 10 | path miss | 0.9988 (−0.1%) | −0.7% … +0.1% |
| 100 | static hit | 1.0384 (+3.8%) | +2.4% … +5.4% |
| 100 | late param hit | 1.0285 (+2.9%) | +2.6% … +3.0% |
| 100 | method miss | 0.9971 (−0.3%) | −0.5% … −0.0% |
| 100 | path miss | 1.0100 (+1.0%) | +0.7% … +1.2% |
| 500 | static hit | 1.0374 (+3.7%) | +2.7% … +4.9% |
| 500 | late param hit | 1.0113 (+1.1%) | +0.9% … +1.4% |
| 500 | method miss | 1.0107 (+1.1%) | +0.8% … +1.3% |
| 500 | path miss | 1.0155 (+1.5%) | +1.3% … +1.9% |
With 336 rounds the CIs are narrow, so identical code now shows **systematic** offsets that exclude
1: up to +8.3% (CI +7.1 … +9.1%) at 10-route late param hit, and +3.7 … +4.2% on the static hits.
The baseline's A/A had the same sign at that cell (+4.1%, CI −1.6 … +9.8%). The harness therefore
carries an in-process bias of up to ≈9% against the second-listed router on the cheapest cells,
which the 5% rule does not account for. It does not change this verdict: the three failing cells
are 30–100% slower, far outside the band.
## Attribution (diagnostic, not part of the verdict)
Same image, cpuset and harness, 8 processes × 21 rounds, four routers in one process. The two
older revisions are `git show <sha>:src/http/router.ts` (sha256 checked against git).
| 10 routes | `5e0ae94` (before the last CARD-07 fix) | `cb123e3` (merged CARD-07) | `b128139` (this commit) |
|---|---|---|---|
| late param hit | +5.3% (+4.1 … +9.4%) | +44.9% (+42.9 … +52.6%) | +45.5% (+44.1 … +51.2%) |
| method miss | −2.6% (−2.8 … −2.1%) | +34.4% (+33.9 … +35.2%) | +34.4% (+33.3 … +35.1%) |
| path miss | +1.2% (+1.0 … +1.4%) | +105.9% (+104.7 … +106.3%) | +103.4% (+102.5 … +103.9%) |
- The regression arrived with `a2b71e2` (*fix(router): drop pending walk frames when a segment
fails to decode*), the only router change between `5e0ae94` and `cb123e3`. It wraps the walk
loop in `try … finally` and resets `stackNodes.length` / `stackDepths.length` on every walk.
It costs a roughly constant 130–650 ns per lookup, depending on how many walks a lookup makes,
at every route count. Static hits, which take the `exactPaths` shortcut and never walk, are unaffected.
- `b128139` matches `cb123e3` within noise in every cell, so the seam counters added by this change
do not affect lookup time.
- At `5e0ae94`, the 10-route cells were within D4 (late param lower bound +4.1%) and the 100- and
500-route improvements were larger (e.g. 500-route path miss −95.9% vs −91.8% now).
No optimization was attempted here; restoring the walk's cost without losing the `a2b71e2` fix is a
`src/` change for the owner to decide on.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle | 185.3 | 171.6 / 186.8 / 175.1 / 192.6 / 170.0 / 205.3 / 171.4 / 199.3 / 171.1 / 193.4 / 177.1 / 189.5 / 169.8 / 184.8 / 185.4 / 195.5 | 19.2% |
| 10 | static hit | oracle-copy | 192.0 | 196.0 / 153.5 / 200.2 / 172.0 / 197.0 / 177.6 / 197.1 / 176.1 / 203.6 / 174.9 / 200.2 / 178.6 / 198.1 / 191.5 / 194.9 / 165.3 | 26.1% |
| 10 | late param hit | oracle | 331.9 | 320.2 / 341.3 / 317.8 / 338.3 / 324.5 / 340.3 / 317.4 / 351.5 / 317.5 / 347.3 / 329.1 / 340.9 / 315.2 / 336.1 / 322.1 / 350.8 | 11.0% |
| 10 | late param hit | oracle-copy | 351.3 | 355.6 / 320.9 / 352.7 / 326.7 / 353.3 / 337.1 / 349.3 / 326.9 / 359.6 / 330.6 / 361.0 / 339.1 / 353.3 / 362.1 / 353.6 / 342.2 | 11.7% |
| 10 | method miss | oracle | 779.3 | 777.8 / 784.3 / 763.9 / 777.0 / 755.4 / 772.9 / 763.4 / 886.9 / 765.3 / 786.1 / 785.6 / 802.9 / 747.7 / 777.0 / 799.4 / 799.2 | 17.9% |
| 10 | method miss | oracle-copy | 777.0 | 798.4 / 753.2 / 777.7 / 765.1 / 780.7 / 737.3 / 793.9 / 766.2 / 796.8 / 754.9 / 803.9 / 783.0 / 764.9 / 745.1 / 797.6 / 780.6 | 8.6% |
| 10 | path miss | oracle | 609.3 | 584.8 / 616.8 / 592.5 / 609.0 / 597.2 / 611.6 / 595.4 / 644.2 / 596.9 / 602.2 / 629.0 / 624.6 / 602.9 / 611.7 / 613.7 / 617.7 | 9.8% |
| 10 | path miss | oracle-copy | 608.0 | 614.9 / 582.4 / 611.4 / 601.2 / 615.8 / 588.2 / 624.8 / 595.1 / 625.1 / 590.1 / 626.7 / 590.9 / 604.0 / 581.9 / 620.0 / 617.8 | 7.4% |
| 100 | static hit | oracle | 205.5 | 194.9 / 206.9 / 189.7 / 214.3 / 188.1 / 217.3 / 186.0 / 229.0 / 190.8 / 213.4 / 202.8 / 209.4 / 201.7 / 209.7 / 194.9 / 215.3 | 20.9% |
| 100 | static hit | oracle-copy | 210.5 | 207.8 / 193.9 / 218.3 / 194.5 / 213.6 / 205.8 / 213.3 / 206.2 / 211.8 / 197.6 / 217.5 / 216.4 / 211.0 / 195.7 / 211.3 / 210.2 | 11.6% |
| 100 | late param hit | oracle | 875.3 | 902.1 / 855.1 / 852.7 / 852.9 / 906.6 / 882.9 / 873.6 / 905.3 / 877.5 / 866.5 / 896.0 / 875.3 / 860.6 / 866.4 / 874.7 / 886.1 | 6.2% |
| 100 | late param hit | oracle-copy | 895.3 | 913.2 / 889.1 / 889.9 / 876.3 / 890.4 / 887.5 / 896.3 / 910.0 / 907.8 / 897.7 / 916.0 / 892.1 / 889.4 / 888.0 / 897.7 / 951.7 | 8.4% |
| 100 | method miss | oracle | 2509.1 | 2589.9 / 2498.9 / 2487.7 / 2509.2 / 2487.4 / 2496.7 / 2473.1 / 2589.6 / 2516.7 / 2519.8 / 2455.1 / 2588.2 / 2405.1 / 2509.1 / 2499.6 / 2547.7 | 7.4% |
| 100 | method miss | oracle-copy | 2502.4 | 2620.9 / 2470.5 / 2491.5 / 2484.1 / 2487.6 / 2436.2 / 2562.5 / 2523.3 / 2559.0 / 2508.5 / 2491.9 / 2572.8 / 2473.1 / 2460.1 / 2480.1 / 2540.1 | 7.4% |
| 100 | path miss | oracle | 3032.2 | 3123.1 / 3002.5 / 3029.2 / 3027.7 / 3035.2 / 3023.8 / 2984.2 / 3115.4 / 3057.8 / 3042.8 / 2996.6 / 3089.9 / 2916.3 / 3028.2 / 2983.7 / 3066.3 | 6.8% |
| 100 | path miss | oracle-copy | 3069.0 | 3164.6 / 3009.8 / 3072.4 / 3041.6 / 3033.8 / 3027.1 / 3080.2 / 3077.8 / 3115.3 / 3083.6 / 3050.5 / 3099.1 / 2989.7 / 3019.5 / 3018.2 / 3075.3 | 5.7% |
| 500 | static hit | oracle | 206.7 | 197.8 / 209.1 / 193.0 / 215.8 / 193.8 / 219.8 / 186.2 / 230.4 / 196.6 / 216.2 / 202.7 / 208.8 / 195.3 / 208.2 / 197.6 / 216.7 | 21.4% |
| 500 | static hit | oracle-copy | 209.7 | 207.7 / 195.5 / 218.7 / 196.3 / 217.5 / 207.7 / 211.3 / 205.7 / 214.9 / 198.0 / 217.5 / 215.3 / 208.1 / 194.0 / 212.9 / 210.4 | 11.8% |
| 500 | late param hit | oracle | 2851.6 | 3013.2 / 2800.0 / 2822.0 / 2822.6 / 2985.7 / 2976.5 / 2853.5 / 2841.9 / 2938.3 / 2842.8 / 2903.9 / 2847.2 / 2789.9 / 2833.2 / 2813.1 / 2967.4 | 7.8% |
| 500 | late param hit | oracle-copy | 2904.5 | 2898.8 / 2832.6 / 2904.8 / 2849.5 / 2917.2 / 2922.2 / 2839.8 / 2955.2 / 2986.3 / 2964.2 / 2966.0 / 2863.6 / 2850.6 / 2874.6 / 2853.0 / 2965.1 | 5.3% |
| 500 | method miss | oracle | 11893.2 | 11982.2 / 11618.7 / 11522.3 / 11528.5 / 12093.8 / 12866.2 / 11749.3 / 11991.5 / 11895.6 / 11915.7 / 11763.2 / 11896.4 / 11793.6 / 12613.8 / 11668.1 / 12156.8 | 11.3% |
| 500 | method miss | oracle-copy | 12004.6 | 12046.9 / 11880.8 / 11572.6 / 11957.2 / 12294.5 / 12289.2 / 11975.8 / 12018.3 / 11969.8 / 11802.4 / 12070.3 / 12118.1 / 11893.5 / 12437.1 / 11771.9 / 12685.4 | 9.3% |
| 500 | path miss | oracle | 15411.0 | 15690.0 / 15020.4 / 14830.8 / 14986.3 / 15701.3 / 16217.0 / 15500.7 / 15373.9 / 15740.1 / 15391.9 / 15109.0 / 15411.0 / 15122.5 / 16445.6 / 15265.1 / 15824.8 | 10.5% |
| 500 | path miss | oracle-copy | 15727.3 | 15736.8 / 15428.6 / 15278.9 / 15690.0 / 15853.1 / 16234.6 / 15623.0 / 15809.2 / 15772.1 / 15577.8 / 15765.7 / 15756.7 / 15389.3 / 16351.2 / 15500.3 / 16250.8 | 6.8% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle-copy / oracle | 1.0421 (+4.2%) | 1.0207 – 1.0565 (+2.1% … +5.7%) | 336 |
| 10 | late param hit | oracle-copy / oracle | 1.0829 (+8.3%) | 1.0707 – 1.0909 (+7.1% … +9.1%) | 336 |
| 10 | method miss | oracle-copy / oracle | 0.9862 (-1.4%) | 0.9797 – 1.0016 (-2.0% … +0.2%) | 336 |
| 10 | path miss | oracle-copy / oracle | 0.9988 (-0.1%) | 0.9927 – 1.0010 (-0.7% … +0.1%) | 336 |
| 100 | static hit | oracle-copy / oracle | 1.0384 (+3.8%) | 1.0244 – 1.0536 (+2.4% … +5.4%) | 336 |
| 100 | late param hit | oracle-copy / oracle | 1.0285 (+2.9%) | 1.0259 – 1.0301 (+2.6% … +3.0%) | 336 |
| 100 | method miss | oracle-copy / oracle | 0.9971 (-0.3%) | 0.9952 – 0.9997 (-0.5% … -0.0%) | 336 |
| 100 | path miss | oracle-copy / oracle | 1.0100 (+1.0%) | 1.0071 – 1.0122 (+0.7% … +1.2%) | 336 |
| 500 | static hit | oracle-copy / oracle | 1.0374 (+3.7%) | 1.0272 – 1.0495 (+2.7% … +4.9%) | 336 |
| 500 | late param hit | oracle-copy / oracle | 1.0113 (+1.1%) | 1.0091 – 1.0135 (+0.9% … +1.4%) | 336 |
| 500 | method miss | oracle-copy / oracle | 1.0107 (+1.1%) | 1.0082 – 1.0128 (+0.8% … +1.3%) | 336 |
| 500 | path miss | oracle-copy / oracle | 1.0155 (+1.5%) | 1.0125 – 1.0186 (+1.3% … +1.9%) | 336 |
load average: start 1.92 1.40 0.66, end 1.62 1.50 0.92; cpuset 6-7,14-15
raw samples: out/aa-raw.json
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle | 187.8 | 168.5 / 200.6 / 175.3 / 190.2 / 170.3 / 190.5 / 168.8 / 192.4 | 17.1% |
| 10 | static hit | radix-5e0ae94 | 84.9 | 85.7 / 86.0 / 79.7 / 83.5 / 88.2 / 78.5 / 89.3 / 77.6 | 13.8% |
| 10 | static hit | radix-cb123e3 | 84.5 | 81.1 / 83.5 / 76.5 / 89.7 / 87.8 / 85.3 / 92.9 / 81.1 | 19.4% |
| 10 | static hit | radix-b128139 | 80.1 | 80.8 / 78.3 / 80.9 / 79.2 / 81.0 / 73.2 / 88.3 / 72.2 | 20.2% |
| 10 | late param hit | oracle | 336.6 | 324.5 / 385.9 / 322.3 / 352.3 / 326.7 / 343.0 / 322.4 / 357.0 | 18.9% |
| 10 | late param hit | radix-5e0ae94 | 365.3 | 368.2 / 370.1 / 360.7 / 366.8 / 356.6 / 350.2 / 369.3 / 363.5 | 5.5% |
| 10 | late param hit | radix-cb123e3 | 500.4 | 503.7 / 495.1 / 514.9 / 502.3 / 498.4 / 481.8 / 538.7 / 498.7 | 11.4% |
| 10 | late param hit | radix-b128139 | 496.0 | 507.8 / 488.5 / 489.6 / 508.8 / 494.4 / 480.8 / 507.1 / 496.2 | 5.6% |
| 10 | method miss | oracle | 772.3 | 764.9 / 783.0 / 768.7 / 775.2 / 773.0 / 761.1 / 757.6 / 777.4 | 3.3% |
| 10 | method miss | radix-5e0ae94 | 755.9 | 770.1 / 759.0 / 745.2 / 760.1 / 771.6 / 727.2 / 750.8 / 747.0 | 5.9% |
| 10 | method miss | radix-cb123e3 | 1043.5 | 1060.9 / 1043.9 / 1063.5 / 1040.5 / 1029.8 / 1007.2 / 1032.6 / 1050.8 | 5.4% |
| 10 | method miss | radix-b128139 | 1038.4 | 1056.8 / 1027.2 / 1043.0 / 1050.4 / 1010.3 / 1010.0 / 1034.4 / 1042.8 | 4.5% |
| 10 | path miss | oracle | 600.9 | 578.0 / 631.4 / 604.8 / 603.2 / 599.0 / 589.4 / 594.2 / 612.4 | 8.9% |
| 10 | path miss | radix-5e0ae94 | 611.0 | 622.1 / 628.3 / 601.6 / 610.3 / 608.1 / 596.6 / 611.3 / 617.3 | 5.2% |
| 10 | path miss | radix-cb123e3 | 1246.5 | 1304.5 / 1261.4 / 1252.0 / 1262.0 / 1199.2 / 1218.0 / 1216.0 / 1235.3 | 8.5% |
| 10 | path miss | radix-b128139 | 1225.0 | 1250.3 / 1211.7 / 1240.8 / 1253.4 / 1215.2 / 1198.9 / 1197.2 / 1227.9 | 4.6% |
| 100 | static hit | oracle | 206.6 | 204.8 / 211.1 / 197.2 / 210.7 / 203.8 / 211.6 / 200.2 / 207.8 | 7.0% |
| 100 | static hit | radix-5e0ae94 | 99.0 | 99.4 / 97.9 / 95.0 / 106.8 / 101.9 / 92.1 / 105.6 / 98.7 | 14.8% |
| 100 | static hit | radix-cb123e3 | 99.5 | 104.8 / 91.4 / 94.3 / 103.2 / 95.7 / 101.8 / 104.3 / 96.0 | 13.4% |
| 100 | static hit | radix-b128139 | 95.4 | 92.5 / 96.5 / 92.0 / 105.7 / 102.1 / 84.9 / 102.2 / 88.7 | 21.8% |
| 100 | late param hit | oracle | 868.9 | 885.4 / 862.0 / 869.3 / 871.4 / 864.4 / 855.0 / 868.9 / 879.3 | 3.5% |
| 100 | late param hit | radix-5e0ae94 | 369.7 | 386.9 / 362.5 / 360.3 / 373.0 / 367.5 / 353.6 / 375.6 / 372.1 | 9.0% |
| 100 | late param hit | radix-cb123e3 | 501.6 | 508.1 / 496.2 / 502.9 / 500.3 / 503.1 / 508.5 / 497.4 / 500.1 | 2.5% |
| 100 | late param hit | radix-b128139 | 493.5 | 518.8 / 482.0 / 496.6 / 483.9 / 499.6 / 489.7 / 504.7 / 488.8 | 7.5% |
| 100 | method miss | oracle | 2502.9 | 2533.9 / 2508.3 / 2493.5 / 2481.1 / 2577.2 / 2450.9 / 2466.6 / 2510.1 | 5.0% |
| 100 | method miss | radix-5e0ae94 | 774.7 | 792.1 / 772.2 / 775.9 / 784.0 / 761.3 / 757.2 / 754.8 / 779.7 | 4.8% |
| 100 | method miss | radix-cb123e3 | 1051.3 | 1105.3 / 1040.9 / 1083.8 / 1052.1 / 1050.8 / 1033.5 / 1027.5 / 1067.1 | 7.4% |
| 100 | method miss | radix-b128139 | 1060.1 | 1088.1 / 1031.5 / 1068.2 / 1060.7 / 1093.0 / 1033.6 / 1040.2 / 1059.6 | 5.8% |
| 100 | path miss | oracle | 3026.9 | 3035.0 / 3106.5 / 3057.6 / 2989.9 / 3054.9 / 2927.9 / 2987.3 / 3023.6 | 5.9% |
| 100 | path miss | radix-5e0ae94 | 615.7 | 639.5 / 619.8 / 612.0 / 592.7 / 622.4 / 588.0 / 600.1 / 619.4 | 8.4% |
| 100 | path miss | radix-cb123e3 | 1231.5 | 1266.1 / 1255.0 / 1264.9 / 1215.8 / 1209.3 / 1186.0 / 1212.1 / 1240.5 | 6.5% |
| 100 | path miss | radix-b128139 | 1230.0 | 1261.6 / 1233.2 / 1246.0 / 1213.0 / 1222.2 / 1169.2 / 1216.9 / 1237.5 | 7.5% |
| 500 | static hit | oracle | 208.6 | 204.7 / 216.8 / 201.3 / 208.9 / 205.4 / 223.7 / 203.9 / 217.7 | 10.7% |
| 500 | static hit | radix-5e0ae94 | 107.7 | 104.2 / 112.1 / 104.8 / 105.5 / 109.4 / 109.4 / 108.3 / 114.2 | 9.3% |
| 500 | static hit | radix-cb123e3 | 104.5 | 106.1 / 110.9 / 103.8 / 100.2 / 106.0 / 112.5 / 104.6 / 100.3 | 11.8% |
| 500 | static hit | radix-b128139 | 103.1 | 98.2 / 102.2 / 102.9 / 104.6 / 104.0 / 102.4 / 104.6 / 104.0 | 6.2% |
| 500 | late param hit | oracle | 2845.6 | 2835.8 / 2802.4 / 2823.4 / 2840.5 / 2866.8 / 2913.6 / 2810.5 / 2883.0 | 3.9% |
| 500 | late param hit | radix-5e0ae94 | 378.2 | 383.9 / 373.7 / 367.4 / 380.3 / 389.5 / 374.5 / 375.7 / 379.7 | 5.8% |
| 500 | late param hit | radix-cb123e3 | 508.5 | 511.6 / 503.5 / 496.2 / 504.9 / 522.1 / 527.9 / 504.4 / 513.9 | 6.2% |
| 500 | late param hit | radix-b128139 | 502.5 | 515.2 / 494.4 / 487.7 / 492.1 / 516.9 / 503.8 / 505.7 / 500.6 | 5.8% |
| 500 | method miss | oracle | 11778.4 | 11628.2 / 11388.0 / 11702.2 / 11567.8 / 11866.3 / 12532.8 / 11933.9 / 11949.8 | 9.7% |
| 500 | method miss | radix-5e0ae94 | 794.6 | 804.2 / 786.3 / 768.6 / 801.9 / 797.1 / 791.5 / 785.1 / 796.6 | 4.5% |
| 500 | method miss | radix-cb123e3 | 1082.2 | 1110.1 / 1063.7 / 1078.1 / 1062.3 / 1089.6 / 1075.3 / 1127.6 / 1080.6 | 6.0% |
| 500 | method miss | radix-b128139 | 1079.5 | 1083.6 / 1050.3 / 1079.0 / 1065.1 / 1124.2 / 1092.1 / 1098.9 / 1067.3 | 6.8% |
| 500 | path miss | oracle | 15341.3 | 15106.1 / 14850.3 / 15080.7 / 15327.4 / 15495.3 / 16139.2 / 15346.2 / 15630.0 | 8.4% |
| 500 | path miss | radix-5e0ae94 | 629.5 | 658.3 / 646.1 / 620.1 / 626.6 / 666.2 / 631.3 / 610.1 / 615.6 | 8.9% |
| 500 | path miss | radix-cb123e3 | 1249.6 | 1285.0 / 1252.6 / 1250.4 / 1243.2 / 1280.2 / 1250.4 / 1214.4 / 1235.9 | 5.6% |
| 500 | path miss | radix-b128139 | 1235.2 | 1272.1 / 1228.4 / 1243.8 / 1236.2 / 1278.3 / 1226.9 / 1216.5 / 1226.1 | 5.0% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | radix-5e0ae94 / oracle | 0.4484 (-55.2%) | 0.4386 – 0.4553 (-56.1% … -54.5%) | 168 |
| 10 | static hit | radix-cb123e3 / oracle | 0.4496 (-55.0%) | 0.4462 – 0.4731 (-55.4% … -52.7%) | 168 |
| 10 | static hit | radix-b128139 / oracle | 0.4312 (-56.9%) | 0.4158 – 0.4608 (-58.4% … -53.9%) | 168 |
| 10 | late param hit | radix-5e0ae94 / oracle | 1.0535 (+5.3%) | 1.0415 – 1.0937 (+4.1% … +9.4%) | 168 |
| 10 | late param hit | radix-cb123e3 / oracle | 1.4493 (+44.9%) | 1.4291 – 1.5261 (+42.9% … +52.6%) | 168 |
| 10 | late param hit | radix-b128139 / oracle | 1.4549 (+45.5%) | 1.4414 – 1.5117 (+44.1% … +51.2%) | 168 |
| 10 | method miss | radix-5e0ae94 / oracle | 0.9744 (-2.6%) | 0.9724 – 0.9790 (-2.8% … -2.1%) | 168 |
| 10 | method miss | radix-cb123e3 / oracle | 1.3441 (+34.4%) | 1.3387 – 1.3520 (+33.9% … +35.2%) | 168 |
| 10 | method miss | radix-b128139 / oracle | 1.3437 (+34.4%) | 1.3329 – 1.3510 (+33.3% … +35.1%) | 168 |
| 10 | path miss | radix-5e0ae94 / oracle | 1.0124 (+1.2%) | 1.0105 – 1.0143 (+1.0% … +1.4%) | 168 |
| 10 | path miss | radix-cb123e3 / oracle | 2.0590 (+105.9%) | 2.0473 – 2.0628 (+104.7% … +106.3%) | 168 |
| 10 | path miss | radix-b128139 / oracle | 2.0340 (+103.4%) | 2.0254 – 2.0387 (+102.5% … +103.9%) | 168 |
| 100 | static hit | radix-5e0ae94 / oracle | 0.4836 (-51.6%) | 0.4813 – 0.4878 (-51.9% … -51.2%) | 168 |
| 100 | static hit | radix-cb123e3 / oracle | 0.4800 (-52.0%) | 0.4746 – 0.4834 (-52.5% … -51.7%) | 168 |
| 100 | static hit | radix-b128139 / oracle | 0.4597 (-54.0%) | 0.4569 – 0.4677 (-54.3% … -53.2%) | 168 |
| 100 | late param hit | radix-5e0ae94 / oracle | 0.4236 (-57.6%) | 0.4226 – 0.4252 (-57.7% … -57.5%) | 168 |
| 100 | late param hit | radix-cb123e3 / oracle | 0.5754 (-42.5%) | 0.5744 – 0.5768 (-42.6% … -42.3%) | 168 |
| 100 | late param hit | radix-b128139 / oracle | 0.5709 (-42.9%) | 0.5680 – 0.5726 (-43.2% … -42.7%) | 168 |
| 100 | method miss | radix-5e0ae94 / oracle | 0.3095 (-69.0%) | 0.3088 – 0.3107 (-69.1% … -68.9%) | 168 |
| 100 | method miss | radix-cb123e3 / oracle | 0.4225 (-57.8%) | 0.4213 – 0.4241 (-57.9% … -57.6%) | 168 |
| 100 | method miss | radix-b128139 / oracle | 0.4235 (-57.6%) | 0.4228 – 0.4249 (-57.7% … -57.5%) | 168 |
| 100 | path miss | radix-5e0ae94 / oracle | 0.2012 (-79.9%) | 0.2006 – 0.2020 (-79.9% … -79.8%) | 168 |
| 100 | path miss | radix-cb123e3 / oracle | 0.4068 (-59.3%) | 0.4058 – 0.4075 (-59.4% … -59.2%) | 168 |
| 100 | path miss | radix-b128139 / oracle | 0.4055 (-59.4%) | 0.4035 – 0.4065 (-59.6% … -59.3%) | 168 |
| 500 | static hit | radix-5e0ae94 / oracle | 0.5144 (-48.6%) | 0.5106 – 0.5169 (-48.9% … -48.3%) | 168 |
| 500 | static hit | radix-cb123e3 / oracle | 0.5066 (-49.3%) | 0.5014 – 0.5089 (-49.9% … -49.1%) | 168 |
| 500 | static hit | radix-b128139 / oracle | 0.4860 (-51.4%) | 0.4820 – 0.4998 (-51.8% … -50.0%) | 168 |
| 500 | late param hit | radix-5e0ae94 / oracle | 0.1332 (-86.7%) | 0.1328 – 0.1336 (-86.7% … -86.6%) | 168 |
| 500 | late param hit | radix-cb123e3 / oracle | 0.1793 (-82.1%) | 0.1788 – 0.1797 (-82.1% … -82.0%) | 168 |
| 500 | late param hit | radix-b128139 / oracle | 0.1754 (-82.5%) | 0.1739 – 0.1763 (-82.6% … -82.4%) | 168 |
| 500 | method miss | radix-5e0ae94 / oracle | 0.0670 (-93.3%) | 0.0667 – 0.0675 (-93.3% … -93.2%) | 168 |
| 500 | method miss | radix-cb123e3 / oracle | 0.0922 (-90.8%) | 0.0918 – 0.0925 (-90.8% … -90.7%) | 168 |
| 500 | method miss | radix-b128139 / oracle | 0.0922 (-90.8%) | 0.0917 – 0.0924 (-90.8% … -90.8%) | 168 |
| 500 | path miss | radix-5e0ae94 / oracle | 0.0409 (-95.9%) | 0.0406 – 0.0412 (-95.9% … -95.9%) | 168 |
| 500 | path miss | radix-cb123e3 / oracle | 0.0818 (-91.8%) | 0.0808 – 0.0824 (-91.9% … -91.8%) | 168 |
| 500 | path miss | radix-b128139 / oracle | 0.0815 (-91.8%) | 0.0806 – 0.0821 (-91.9% … -91.8%) | 168 |
load average: start 0.74 1.27 0.87, end 1.09 1.16 0.95; cpuset 6-7,14-15
raw samples: out/attrib-raw.json
+8
View File
@@ -0,0 +1,8 @@
d4 before: 2026-10-12T18:58:39Z 13:58:39 up 46 days, 13:47, 2 users, load average: 0.24, 0.25, 0.11
ci job containers: 0
d4 after / aa before: 2026-10-12T19:03:38Z 14:03:38 up 46 days, 13:52, 3 users, load average: 1.92, 1.40, 0.66
ci job containers: 0
aa after: 2026-10-12T19:08:38Z 14:08:38 up 46 days, 13:57, 3 users, load average: 1.62, 1.50, 0.92
ci job containers: 0
attrib before: 2026-10-12T19:09:34Z 14:09:34 up 46 days, 13:58, 2 users, load average: 0.74, 1.27, 0.87
attrib after: 2026-10-12T19:14:33Z 14:14:33 up 46 days, 14:03, 3 users, load average: 1.09, 1.16, 0.95
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle | 189.3 | 181.1 / 193.3 / 189.0 / 189.8 / 173.8 / 193.6 / 179.5 / 290.1 / 170.8 / 196.3 / 164.7 / 202.2 / 172.3 / 207.0 / 186.1 / 198.5 | 66.2% |
| 10 | static hit | radix | 79.9 | 80.5 / 76.3 / 80.4 / 76.0 / 81.0 / 78.8 / 78.8 / 95.0 / 89.6 / 71.2 / 80.6 / 71.0 / 87.4 / 70.2 / 85.5 / 76.3 | 31.2% |
| 10 | late param hit | oracle | 335.8 | 318.2 / 339.1 / 315.3 / 342.1 / 324.1 / 366.1 / 324.7 / 527.3 / 323.3 / 341.9 / 324.4 / 338.6 / 317.1 / 341.9 / 327.3 / 344.9 | 63.1% |
| 10 | late param hit | radix | 495.8 | 492.0 / 487.5 / 495.8 / 494.7 / 496.8 / 489.9 / 497.5 / 801.9 / 495.5 / 485.1 / 504.0 / 504.2 / 497.0 / 581.5 / 497.9 / 487.1 | 63.9% |
| 10 | method miss | oracle | 774.2 | 759.1 / 774.4 / 745.0 / 773.2 / 771.5 / 797.9 / 774.8 / 797.8 / 764.1 / 768.2 / 767.2 / 795.5 / 761.3 / 777.9 / 784.2 / 789.1 | 6.8% |
| 10 | method miss | radix | 1032.5 | 1009.5 / 1003.8 / 1039.7 / 1015.7 / 1056.1 / 1033.4 / 1069.7 / 1028.3 / 1059.3 / 1002.3 / 1047.3 / 1017.9 / 1048.7 / 1022.2 / 1033.2 / 1028.6 | 6.5% |
| 10 | path miss | oracle | 605.2 | 594.3 / 607.6 / 583.3 / 609.8 / 600.0 / 626.6 / 607.2 / 629.6 / 605.1 / 591.5 / 595.6 / 713.2 / 583.0 / 600.3 / 607.1 / 614.0 | 21.5% |
| 10 | path miss | radix | 1216.1 | 1183.5 / 1193.5 / 1238.1 / 1205.4 / 1282.2 / 1214.5 / 1272.6 / 1211.0 / 1271.8 / 1193.4 / 1218.9 / 1215.2 / 1224.3 / 1209.3 / 1242.6 / 1174.7 | 8.8% |
| 100 | static hit | oracle | 203.1 | 182.3 / 210.0 / 203.7 / 212.3 / 203.4 / 201.1 / 209.6 / 212.6 / 209.2 / 208.9 / 199.2 / 195.9 / 195.4 / 202.1 / 186.2 / 201.9 | 14.9% |
| 100 | static hit | radix | 94.4 | 90.2 / 96.5 / 102.2 / 92.3 / 98.8 / 95.2 / 96.5 / 83.3 / 96.8 / 80.8 / 97.0 / 90.3 / 91.6 / 91.0 / 100.8 / 88.5 | 22.7% |
| 100 | late param hit | oracle | 880.6 | 853.2 / 862.3 / 885.2 / 870.7 / 861.9 / 891.0 / 885.0 / 896.1 / 886.1 / 865.7 / 876.4 / 892.3 / 851.3 / 880.6 / 889.4 / 883.5 | 5.1% |
| 100 | late param hit | radix | 499.1 | 491.3 / 494.4 / 519.6 / 493.9 / 504.8 / 509.3 / 518.2 / 516.4 / 496.7 / 496.9 / 521.4 / 490.0 / 494.4 / 495.6 / 505.0 / 480.1 | 8.3% |
| 100 | method miss | oracle | 2515.1 | 2509.2 / 2535.9 / 2510.3 / 2525.3 / 2490.2 / 2561.8 / 2525.3 / 2494.8 / 2439.7 / 2423.0 / 2499.4 / 2511.6 / 2385.6 / 2579.1 / 2519.5 / 2545.4 | 7.7% |
| 100 | method miss | radix | 1048.2 | 1018.7 / 1035.6 / 1075.5 / 1016.9 / 1066.9 / 1042.7 / 1079.9 / 1052.9 / 1073.1 / 1026.8 / 1059.7 / 1042.4 / 1039.5 / 1060.1 / 1054.8 / 1033.0 | 6.0% |
| 100 | path miss | oracle | 3042.8 | 3018.3 / 3084.7 / 3030.3 / 3092.0 / 2983.1 / 3092.1 / 3035.8 / 3017.4 / 2997.3 / 2928.0 / 3051.5 / 3049.1 / 2878.8 / 3112.3 / 3047.9 / 3086.6 | 7.7% |
| 100 | path miss | radix | 1218.2 | 1195.4 / 1204.1 / 1240.3 / 1211.8 / 1227.2 / 1218.4 / 1243.9 / 1242.6 / 1220.0 / 1198.2 / 1228.8 / 1218.2 / 1185.0 / 1203.0 / 1273.6 / 1212.9 | 7.3% |
| 500 | static hit | oracle | 203.9 | 185.0 / 212.4 / 203.2 / 213.1 / 203.7 / 203.9 / 208.0 / 209.0 / 209.4 / 209.9 / 202.5 / 193.9 / 196.4 / 200.1 / 186.2 / 203.9 | 13.8% |
| 500 | static hit | radix | 96.3 | 91.7 / 95.8 / 94.2 / 99.5 / 100.5 / 98.6 / 97.1 / 82.1 / 97.7 / 85.0 / 97.7 / 90.3 / 105.0 / 89.6 / 103.2 / 85.4 | 23.9% |
| 500 | late param hit | oracle | 2825.2 | 2782.7 / 2787.9 / 2800.5 / 2832.6 / 2832.2 / 3098.7 / 2786.3 / 2839.1 / 2896.6 / 2805.7 / 2793.9 / 2896.0 / 2838.7 / 2754.0 / 2917.6 / 2790.8 | 12.2% |
| 500 | late param hit | radix | 498.6 | 490.6 / 498.8 / 513.9 / 488.6 / 513.6 / 502.6 / 504.4 / 495.1 / 499.6 / 498.7 / 513.2 / 488.8 / 501.8 / 480.6 / 496.4 / 480.6 | 6.7% |
| 500 | method miss | oracle | 11838.0 | 11627.9 / 11728.6 / 11904.6 / 11696.5 / 11752.0 / 12264.6 / 13500.6 / 12268.7 / 11613.4 / 11893.1 / 11864.7 / 11897.3 / 12343.2 / 11508.1 / 11541.6 / 11492.7 | 17.0% |
| 500 | method miss | radix | 1052.0 | 1039.0 / 1017.2 / 1056.4 / 1027.9 / 1068.6 / 1077.4 / 1239.0 / 1052.4 / 1048.1 / 1032.9 / 1055.6 / 1056.9 / 1056.9 / 1020.8 / 1056.6 / 1034.0 | 21.1% |
| 500 | path miss | oracle | 15335.4 | 15129.6 / 15295.6 / 15401.4 / 15353.4 / 15333.0 / 16553.2 / 16364.6 / 16945.0 / 15275.6 / 15335.0 / 15342.4 / 15630.5 / 15379.6 / 15051.5 / 15119.7 / 15143.7 | 12.3% |
| 500 | path miss | radix | 1218.9 | 1222.0 / 1211.4 / 1216.4 / 1226.8 / 1232.7 / 1260.1 / 1269.4 / 1221.6 / 1195.9 / 1181.8 / 1210.2 / 1211.3 / 1229.7 / 1167.4 / 1240.5 / 1210.2 | 8.4% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | radix / oracle | 0.4198 (-58.0%) | 0.4051 – 0.4352 (-59.5% … -56.5%) | 336 |
| 10 | late param hit | radix / oracle | 1.5253 (+52.5%) | 1.5161 – 1.5300 (+51.6% … +53.0%) | 336 |
| 10 | method miss | radix / oracle | 1.3181 (+31.8%) | 1.3130 – 1.3228 (+31.3% … +32.3%) | 336 |
| 10 | path miss | radix / oracle | 2.0192 (+101.9%) | 2.0063 – 2.0291 (+100.6% … +102.9%) | 336 |
| 100 | static hit | radix / oracle | 0.4632 (-53.7%) | 0.4610 – 0.4662 (-53.9% … -53.4%) | 336 |
| 100 | late param hit | radix / oracle | 0.5726 (-42.7%) | 0.5711 – 0.5741 (-42.9% … -42.6%) | 336 |
| 100 | method miss | radix / oracle | 0.4193 (-58.1%) | 0.4173 – 0.4215 (-58.3% … -57.8%) | 336 |
| 100 | path miss | radix / oracle | 0.4042 (-59.6%) | 0.4013 – 0.4064 (-59.9% … -59.4%) | 336 |
| 500 | static hit | radix / oracle | 0.4673 (-53.3%) | 0.4653 – 0.4683 (-53.5% … -53.2%) | 336 |
| 500 | late param hit | radix / oracle | 0.1751 (-82.5%) | 0.1744 – 0.1763 (-82.6% … -82.4%) | 336 |
| 500 | method miss | radix / oracle | 0.0887 (-91.1%) | 0.0885 – 0.0889 (-91.2% … -91.1%) | 336 |
| 500 | path miss | radix / oracle | 0.0786 (-92.1%) | 0.0784 – 0.0790 (-92.2% … -92.1%) | 336 |
load average: start 0.24 0.25 0.11, end 1.92 1.40 0.66; cpuset 6-7,14-15
raw samples: out/lookup-raw.json
+67
View File
@@ -0,0 +1,67 @@
# Radix router lookup evidence: `ed19f16` (CARD-10, D4)
This is the formal D4 comparison for the radix index (FPRD-001 CARD-10, #109). It supersedes `../router-b128139/`.
The radix router (`src/http/router.ts`) runs against the frozen pre-radix linear matcher (`test/router-parity/oracle.ts`). `ed19f16` contains:
- `develop` at `72f591d`, which includes:
- CARD-07 (#128);
- the walk-stack fix (#131);
- CARD-09 (#129);
- the no-recompilation seam counters;
- the harness order fix described below.
**Verdict: D4 passes.** Every cell passes. The 10-route late param hit passes by 0.1 point: its CI lower bound is +4.9% and the limit is +5%.
## Method
The harness, host, cpuset and image are the same as in `bench/baseline/router-ed47836/`, with two differences:
- 16 processes × 21 rounds give 336 paired rounds per cell. The owner asked for more rounds to narrow the CI on the borderline cell.
- In `bench/lookup.ts` (`ed19f16`), each process now reverses the **whole** router order: import, warm-up, and which router opens each cell's first round. Before, only the import order alternated. The A/A in `../router-b128139/` showed a steady bias of up to +8.3% against the second-listed router at 10 routes, and with this change the same A/A centres on 0. The owner approved this method change on 2026-10-12.
Run details:
- **Host and container:** jarvis, `docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 node:22`.
- **Image:** `sha256:5647be70…`, the same as the baseline.
- **Command:** in `run.sh`. It ran on a `git archive` of `ed19f16`, installed with `npm ci --ignore-scripts`.
- **Load:** see `load.txt`. The 1-minute load was about 1 throughout.
## D4 verdict (radix / oracle, median of per-round ratios, bootstrap 95% CI)
| routes | workload | ratio | 95% CI | D4 rule | verdict |
| -----: | -------------- | -----: | --------------- | ------------------ | -------------------- |
| 10 | static hit | −57.7% | −58.8% … −55.9% | lower bound ≤ +5% | pass |
| 10 | late param hit | +5.6% | +4.9% … +6.6% | lower bound ≤ +5% | pass (margin 0.1 pt) |
| 10 | method miss | −6.1% | −6.9% … −5.2% | lower bound ≤ +5% | pass |
| 10 | path miss | −2.5% | −3.2% … −2.0% | lower bound ≤ +5% | pass |
| 100 | static hit | −55.4% | −55.8% … −55.2% | lower bound ≤ +5% | pass |
| 100 | late param hit | −57.9% | −58.1% … −57.7% | lower bound ≤ +5% | pass |
| 100 | method miss | −70.6% | −70.7% … −70.6% | lower bound ≤ +5% | pass |
| 100 | path miss | −80.1% | −80.2% … −80.1% | lower bound ≤ +5% | pass |
| 500 | static hit | −54.2% | −54.7% … −53.8% | lower bound ≤ +5% | pass |
| 500 | late param hit | −87.3% | −87.4% … −87.3% | upper bound ≤ −20% | pass |
| 500 | method miss | −93.8% | −93.8% … −93.8% | upper bound ≤ −20% | pass |
| 500 | path miss | −96.1% | −96.1% … −96.1% | upper bound ≤ −20% | pass |
## A/A noise band (oracle vs `oracle-copy`, same settings)
`oracle-copy` is a byte-identical copy of the oracle at another path (sha256 `8875ec12…`), so V8 sees two separate modules. It is not committed.
| routes | static hit | late param hit | method miss | path miss |
| -----: | -------------------- | ------------------- | ------------------- | ------------------- |
| 10 | +7.9% (+5.2 … +14.1) | −0.6% (−6.4 … +5.4) | −0.7% (−1.9 … +0.9) | −0.6% (−1.1 … −0.0) |
| 100 | −2.4% (−3.0 … −2.0) | −0.4% (−1.5 … +1.3) | +0.2% (−0.5 … +0.6) | +0.0% (−0.3 … +0.5) |
| 500 | −2.1% (−2.7 … −0.9) | −0.0% (−0.4 … +0.3) | +0.5% (+0.0 … +1.0) | +0.1% (−0.1 … +0.7) |
- **Late param hit at 10 routes:** the old harness had a +8.3% bias here, and it is gone.
- **Static hit at 10 routes:** this cell still varies by several percent. It is the cheapest cell, about 80 ns per radix lookup. Radix is −58% on it, so this does not affect the verdict.
## Files
| File | What it is |
| --------------------------------------- | ------------------------------------------------------------------------------------- |
| `lookup-raw.json`, `lookup-summary.txt` | The D4 run: environment, method, every sample of every round, and the summary tables. |
| `aa-raw.json`, `aa-summary.txt` | The A/A run. |
| `load.txt` | Load average before and after each run. |
| `run.sh` | The exact script run on jarvis. |
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle | 184.9 | 161.5 / 191.2 / 171.2 / 197.5 / 177.1 / 188.6 / 160.5 / 198.9 / 170.6 / 197.6 / 169.9 / 199.4 / 157.8 / 185.4 / 173.3 / 193.4 | 22.5% |
| 10 | static hit | oracle-copy | 193.0 | 201.2 / 164.3 / 204.2 / 177.6 / 207.4 / 158.2 / 192.9 / 159.0 / 194.1 / 162.4 / 202.0 / 210.2 / 193.6 / 158.7 / 205.0 / 152.7 | 29.8% |
| 10 | late param hit | oracle | 338.6 | 313.5 / 352.1 / 322.0 / 348.0 / 328.9 / 341.3 / 318.8 / 345.6 / 337.1 / 353.2 / 325.0 / 351.8 / 315.3 / 341.8 / 323.6 / 357.5 | 13.0% |
| 10 | late param hit | oracle-copy | 335.9 | 363.8 / 326.6 / 352.0 / 321.1 / 357.7 / 320.7 / 358.3 / 303.6 / 352.0 / 328.2 / 357.7 / 320.6 / 341.9 / 317.9 / 369.6 / 317.1 | 19.7% |
| 10 | method miss | oracle | 778.0 | 754.3 / 784.9 / 782.6 / 789.8 / 781.1 / 774.3 / 771.4 / 765.4 / 767.2 / 801.7 / 778.0 / 785.8 / 762.0 / 777.7 / 780.3 / 775.2 | 6.1% |
| 10 | method miss | oracle-copy | 770.3 | 768.7 / 767.8 / 805.3 / 757.9 / 796.7 / 759.9 / 804.6 / 743.0 / 796.8 / 759.1 / 799.6 / 764.3 / 777.8 / 745.2 / 784.3 / 752.3 | 8.1% |
| 10 | path miss | oracle | 611.4 | 575.6 / 616.4 / 603.4 / 618.0 / 647.3 / 615.9 / 595.0 / 596.9 / 601.3 / 625.8 / 616.0 / 620.5 / 583.5 / 602.3 / 616.6 / 593.0 | 11.7% |
| 10 | path miss | oracle-copy | 609.4 | 619.1 / 595.4 / 613.5 / 591.6 / 642.4 / 583.6 / 628.4 / 575.4 / 611.3 / 601.3 / 628.2 / 610.0 / 609.6 / 583.7 / 635.8 / 589.3 | 11.0% |
| 100 | static hit | oracle | 208.7 | 207.7 / 210.4 / 207.8 / 210.4 / 221.5 / 199.1 / 206.7 / 211.5 / 201.0 / 217.3 / 204.9 / 213.8 / 203.7 / 206.4 / 208.5 / 210.1 | 10.7% |
| 100 | static hit | oracle-copy | 205.8 | 208.9 / 196.3 / 212.2 / 203.7 / 217.6 / 194.6 / 213.2 / 202.2 / 208.2 / 205.8 / 215.3 / 206.1 / 214.3 / 197.2 / 202.9 / 195.2 | 11.2% |
| 100 | late param hit | oracle | 877.6 | 863.1 / 894.9 / 864.3 / 876.5 / 872.4 / 875.8 / 876.0 / 878.3 / 871.3 / 903.5 / 878.7 / 906.6 / 857.8 / 886.7 / 876.3 / 883.0 | 5.6% |
| 100 | late param hit | oracle-copy | 876.0 | 873.7 / 878.7 / 894.7 / 863.0 / 907.0 / 850.4 / 907.8 / 855.8 / 884.5 / 873.4 / 901.1 / 869.7 / 875.8 / 854.7 / 940.3 / 854.8 | 10.3% |
| 100 | method miss | oracle | 2516.5 | 2453.3 / 2483.4 / 2487.6 / 2558.5 / 2523.3 / 2540.6 / 2488.3 / 2511.2 / 2525.1 / 2558.0 / 2516.4 / 2500.7 / 2417.7 / 2536.5 / 2524.2 / 2465.4 | 5.6% |
| 100 | method miss | oracle-copy | 2502.9 | 2471.0 / 2451.7 / 2510.4 / 2516.7 / 2542.0 / 2508.5 / 2552.8 / 2465.8 / 2594.2 / 2495.7 / 2545.8 / 2462.7 / 2485.8 / 2452.2 / 2616.0 / 2448.2 | 6.7% |
| 100 | path miss | oracle | 3037.3 | 2978.5 / 3022.9 / 3006.6 / 3103.8 / 3101.2 / 3046.5 / 2979.6 / 3040.1 / 3049.6 / 3118.8 / 3025.8 / 3011.0 / 2935.2 / 3071.9 / 3099.1 / 2965.5 | 6.0% |
| 100 | path miss | oracle-copy | 3037.9 | 3041.2 / 2996.5 / 3028.4 / 3045.4 / 3096.7 / 2975.0 / 3079.9 / 2962.1 / 3136.0 / 3026.7 / 3094.9 / 2984.3 / 3048.0 / 2955.6 / 3244.1 / 2972.6 | 9.5% |
| 500 | static hit | oracle | 209.3 | 211.9 / 210.6 / 208.7 / 215.4 / 215.7 / 200.7 / 206.6 / 209.7 / 203.8 / 214.9 / 203.8 / 214.2 / 202.2 / 206.1 / 209.9 / 208.0 | 7.2% |
| 500 | static hit | oracle-copy | 208.2 | 212.9 / 195.6 / 214.1 / 208.4 / 212.5 / 194.1 / 210.6 / 201.8 / 209.8 / 207.9 / 216.0 / 208.0 / 205.3 / 197.4 / 209.5 / 196.0 | 10.5% |
| 500 | late param hit | oracle | 2892.8 | 2922.3 / 2909.8 / 2907.3 / 2869.4 / 2896.2 / 2838.4 / 3127.0 / 2843.3 / 2856.8 / 2899.0 / 2850.2 / 2986.6 / 2834.3 / 2949.8 / 2921.4 / 2805.8 | 11.1% |
| 500 | late param hit | oracle-copy | 2875.6 | 2954.7 / 2820.6 / 2892.0 / 2910.9 / 2838.5 / 2846.3 / 3085.2 / 2805.9 / 2875.2 / 2907.8 / 2915.2 / 2838.5 / 2831.3 / 2821.6 / 3177.4 / 2860.3 | 12.9% |
| 500 | method miss | oracle | 11983.6 | 11847.4 / 12882.7 / 12017.7 / 12459.0 / 11847.8 / 11892.0 / 11939.7 / 12016.0 / 12380.8 / 12269.0 / 11950.3 / 12261.1 / 11912.2 / 11840.5 / 11665.5 / 11457.1 | 11.9% |
| 500 | method miss | oracle-copy | 12159.0 | 11968.8 / 12588.8 / 12425.4 / 12422.9 / 11777.1 / 11917.7 / 12422.4 / 11747.1 / 12906.7 / 12187.0 / 12176.6 / 11921.2 / 11987.1 / 11776.4 / 12248.0 / 11684.3 | 10.1% |
| 500 | path miss | oracle | 15652.9 | 15474.0 / 15789.1 / 15842.1 / 16100.5 / 16618.4 / 15582.3 / 15494.8 / 15694.0 / 15182.6 / 15975.5 / 15348.8 / 16286.0 / 15438.4 / 16749.9 / 15374.9 / 15001.2 | 11.2% |
| 500 | path miss | oracle-copy | 15838.8 | 15516.0 / 15429.6 / 16192.3 / 16110.5 / 16422.0 / 15446.7 / 16269.8 / 15092.8 / 15859.0 / 15826.1 / 15883.9 / 15583.2 / 15528.5 / 16004.2 / 16248.8 / 15284.5 | 8.4% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle-copy / oracle | 1.0793 (+7.9%) | 1.0522 – 1.1409 (+5.2% … +14.1%) | 336 |
| 10 | late param hit | oracle-copy / oracle | 0.9945 (-0.6%) | 0.9364 – 1.0536 (-6.4% … +5.4%) | 336 |
| 10 | method miss | oracle-copy / oracle | 0.9933 (-0.7%) | 0.9813 – 1.0087 (-1.9% … +0.9%) | 336 |
| 10 | path miss | oracle-copy / oracle | 0.9941 (-0.6%) | 0.9890 – 1.0000 (-1.1% … -0.0%) | 336 |
| 100 | static hit | oracle-copy / oracle | 0.9757 (-2.4%) | 0.9702 – 0.9803 (-3.0% … -2.0%) | 336 |
| 100 | late param hit | oracle-copy / oracle | 0.9955 (-0.4%) | 0.9846 – 1.0128 (-1.5% … +1.3%) | 336 |
| 100 | method miss | oracle-copy / oracle | 1.0023 (+0.2%) | 0.9951 – 1.0057 (-0.5% … +0.6%) | 336 |
| 100 | path miss | oracle-copy / oracle | 1.0001 (+0.0%) | 0.9966 – 1.0049 (-0.3% … +0.5%) | 336 |
| 500 | static hit | oracle-copy / oracle | 0.9786 (-2.1%) | 0.9727 – 0.9915 (-2.7% … -0.9%) | 336 |
| 500 | late param hit | oracle-copy / oracle | 0.9998 (-0.0%) | 0.9957 – 1.0028 (-0.4% … +0.3%) | 336 |
| 500 | method miss | oracle-copy / oracle | 1.0051 (+0.5%) | 1.0004 – 1.0104 (+0.0% … +1.0%) | 336 |
| 500 | path miss | oracle-copy / oracle | 1.0010 (+0.1%) | 0.9987 – 1.0074 (-0.1% … +0.7%) | 336 |
load average: start 1.02 0.97 0.62, end 1.07 1.03 0.75; cpuset 6-7,14-15
raw samples: out/aa-raw.json
+3
View File
@@ -0,0 +1,3 @@
d4 before: 2026-10-12T20:16:20Z 15:16:20 up 46 days, 15:05, 2 users, load average: 0.89, 0.83, 0.44
d4 after / aa before: 2026-10-12T20:21:20Z 15:21:20 up 46 days, 15:10, 2 users, load average: 1.02, 0.97, 0.62
aa after: 2026-10-12T20:26:20Z 15:26:20 up 46 days, 15:15, 2 users, load average: 1.07, 1.03, 0.75
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle | 183.5 | 170.9 / 196.0 / 159.6 / 207.7 / 162.1 / 212.6 / 165.0 / 190.8 / 163.7 / 185.1 / 164.6 / 199.1 / 155.7 / 192.8 / 164.1 / 195.6 | 31.0% |
| 10 | static hit | radix | 77.7 | 74.8 / 75.8 / 79.8 / 75.6 / 81.1 / 78.2 / 91.4 / 74.7 / 80.8 / 76.5 / 81.8 / 79.1 / 81.1 / 72.6 / 77.2 / 71.4 | 25.7% |
| 10 | late param hit | oracle | 344.2 | 343.1 / 352.8 / 313.5 / 373.3 / 321.1 / 377.3 / 326.4 / 349.7 / 317.4 / 355.7 / 320.6 / 357.8 / 312.4 / 346.3 / 316.1 / 364.3 | 18.9% |
| 10 | late param hit | radix | 364.0 | 353.5 / 360.3 / 365.2 / 355.0 / 361.4 / 380.8 / 371.1 / 369.5 / 367.3 / 361.5 / 375.1 / 362.1 / 372.5 / 365.1 / 361.5 / 357.7 | 7.5% |
| 10 | method miss | oracle | 773.0 | 746.5 / 785.3 / 758.8 / 759.6 / 765.0 / 820.1 / 768.3 / 780.1 / 765.4 / 780.6 / 761.5 / 775.7 / 773.2 / 782.9 / 744.8 / 796.6 | 9.8% |
| 10 | method miss | radix | 723.0 | 734.2 / 714.1 / 698.9 / 716.7 / 763.9 / 723.3 / 814.9 / 709.9 / 733.4 / 696.8 / 751.3 / 722.2 / 715.6 / 755.9 / 723.8 / 719.0 | 16.3% |
| 10 | path miss | oracle | 607.3 | 596.1 / 616.6 / 573.2 / 603.4 / 591.4 / 645.9 / 593.2 / 614.0 / 587.3 / 624.1 / 589.8 / 612.6 / 607.9 / 621.6 / 574.2 / 640.0 | 12.0% |
| 10 | path miss | radix | 593.5 | 584.4 / 603.9 / 593.1 / 581.4 / 603.8 / 592.6 / 602.8 / 582.1 / 596.8 / 589.9 / 611.5 / 594.9 / 571.5 / 590.5 / 605.0 / 584.4 | 6.7% |
| 100 | static hit | oracle | 206.6 | 213.9 / 206.7 / 196.7 / 217.4 / 199.7 / 213.5 / 225.5 / 205.7 / 194.3 / 208.8 / 203.9 / 216.4 / 197.6 / 204.8 / 204.0 / 211.0 | 15.1% |
| 100 | static hit | radix | 92.4 | 91.2 / 92.3 / 93.3 / 87.3 / 89.0 / 90.9 / 101.9 / 92.4 / 98.0 / 85.6 / 100.2 / 93.9 / 98.8 / 81.5 / 97.7 / 87.1 | 22.1% |
| 100 | late param hit | oracle | 889.6 | 866.4 / 897.8 / 852.5 / 888.2 / 887.2 / 902.6 / 896.5 / 914.7 / 861.6 / 879.4 / 869.5 / 905.6 / 870.3 / 906.5 / 855.8 / 910.7 | 7.0% |
| 100 | late param hit | radix | 370.2 | 368.5 / 355.8 / 369.2 / 371.2 / 363.5 / 386.8 / 384.7 / 355.4 / 371.7 / 366.8 / 386.6 / 363.3 / 385.2 / 382.4 / 359.7 / 381.2 | 8.5% |
| 100 | method miss | oracle | 2523.3 | 2478.4 / 2543.4 / 2454.7 / 2465.9 / 2556.8 / 2556.0 / 2572.0 / 2518.0 / 2506.3 / 2527.4 / 2491.5 / 2507.7 / 2529.7 / 2588.4 / 2437.8 / 2635.8 | 7.8% |
| 100 | method miss | radix | 742.6 | 752.0 / 724.4 / 736.4 / 724.1 / 755.3 / 737.5 / 747.6 / 738.0 / 761.9 / 723.8 / 773.0 / 738.3 / 743.8 / 727.2 / 748.1 / 746.0 | 6.6% |
| 100 | path miss | oracle | 3064.0 | 2996.5 / 3098.5 / 2949.4 / 2992.4 / 3066.7 / 3109.7 / 3092.9 / 3104.7 / 3033.1 / 3054.4 / 3007.8 / 3073.7 / 3033.7 / 3154.8 / 2945.8 / 3178.4 | 7.6% |
| 100 | path miss | radix | 601.4 | 593.1 / 594.2 / 597.1 / 601.0 / 630.5 / 591.5 / 624.1 / 617.2 / 578.7 / 611.0 / 622.7 / 599.9 / 603.3 / 555.5 / 604.3 / 602.1 | 12.5% |
| 500 | static hit | oracle | 208.9 | 214.7 / 208.6 / 195.7 / 217.1 / 198.1 / 210.1 / 222.5 / 207.1 / 194.3 / 209.3 / 200.2 / 216.9 / 195.1 / 200.3 / 209.6 / 211.9 | 13.5% |
| 500 | static hit | radix | 94.3 | 91.4 / 97.9 / 89.9 / 89.5 / 86.3 / 89.1 / 104.5 / 100.4 / 100.1 / 86.5 / 97.5 / 98.9 / 97.3 / 77.8 / 102.6 / 89.5 | 28.4% |
| 500 | late param hit | oracle | 2888.2 | 2786.7 / 2872.4 / 2767.8 / 2860.5 / 2993.3 / 2794.6 / 2875.9 / 2952.6 / 2916.0 / 2898.9 / 2798.5 / 2896.8 / 2814.6 / 2907.4 / 2931.7 / 2967.0 | 7.8% |
| 500 | late param hit | radix | 366.8 | 356.9 / 356.5 / 359.8 / 363.2 / 367.0 / 368.5 / 385.1 / 359.3 / 370.1 / 359.1 / 371.8 / 363.8 / 374.1 / 374.1 / 366.4 / 372.0 | 7.8% |
| 500 | method miss | oracle | 11874.2 | 11413.6 / 11968.3 / 11607.4 / 11878.7 / 11790.1 / 11980.8 / 11864.2 / 12272.0 / 12594.5 / 11869.7 / 11764.9 / 11698.0 / 11665.0 / 11709.8 / 11844.9 / 12182.7 | 9.9% |
| 500 | method miss | radix | 742.6 | 745.3 / 732.5 / 723.4 / 729.2 / 751.7 / 720.7 / 751.0 / 755.4 / 745.2 / 731.5 / 751.2 / 741.4 / 740.2 / 709.8 / 763.6 / 755.6 | 7.2% |
| 500 | path miss | oracle | 15410.9 | 14864.1 / 15496.8 / 14872.3 / 15422.0 / 15357.7 / 15515.3 / 15290.8 / 15967.8 / 16266.8 / 15399.2 / 15008.4 / 15404.7 / 15121.7 / 15493.3 / 15280.0 / 16059.3 | 9.1% |
| 500 | path miss | radix | 597.3 | 597.3 / 576.9 / 596.6 / 592.0 / 605.6 / 589.7 / 620.5 / 628.8 / 598.2 / 596.8 / 586.1 / 589.7 / 625.4 / 595.5 / 644.3 / 612.2 | 11.3% |
| routes | workload | B / A | median ratio | 95% CI | rounds |
| --- | --- | --- | --- | --- | --- |
| 10 | static hit | radix / oracle | 0.4230 (-57.7%) | 0.4115 – 0.4410 (-58.8% … -55.9%) | 336 |
| 10 | late param hit | radix / oracle | 1.0562 (+5.6%) | 1.0490 – 1.0656 (+4.9% … +6.6%) | 336 |
| 10 | method miss | radix / oracle | 0.9389 (-6.1%) | 0.9306 – 0.9483 (-6.9% … -5.2%) | 336 |
| 10 | path miss | radix / oracle | 0.9749 (-2.5%) | 0.9678 – 0.9796 (-3.2% … -2.0%) | 336 |
| 100 | static hit | radix / oracle | 0.4456 (-55.4%) | 0.4420 – 0.4480 (-55.8% … -55.2%) | 336 |
| 100 | late param hit | radix / oracle | 0.4209 (-57.9%) | 0.4190 – 0.4226 (-58.1% … -57.7%) | 336 |
| 100 | method miss | radix / oracle | 0.2939 (-70.6%) | 0.2928 – 0.2944 (-70.7% … -70.6%) | 336 |
| 100 | path miss | radix / oracle | 0.1986 (-80.1%) | 0.1979 – 0.1992 (-80.2% … -80.1%) | 336 |
| 500 | static hit | radix / oracle | 0.4585 (-54.2%) | 0.4530 – 0.4620 (-54.7% … -53.8%) | 336 |
| 500 | late param hit | radix / oracle | 0.1267 (-87.3%) | 0.1261 – 0.1273 (-87.4% … -87.3%) | 336 |
| 500 | method miss | radix / oracle | 0.0620 (-93.8%) | 0.0617 – 0.0622 (-93.8% … -93.8%) | 336 |
| 500 | path miss | radix / oracle | 0.0388 (-96.1%) | 0.0386 – 0.0390 (-96.1% … -96.1%) | 336 |
load average: start 0.89 0.83 0.44, end 1.02 0.97 0.62; cpuset 6-7,14-15
raw samples: out/lookup-raw.json
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -e
cd "$(dirname "$0")"
run() { docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 -e HOME=/tmp -v "$PWD":/w -w /w -e LOOKUP_ROUTERS="$2" -e LOOKUP_RUNS=16 -e LOOKUP_ROUNDS=21 -e LOOKUP_OUT="$1" -e LOOKUP_COMMIT=ed19f16c70bcc70bd762c627d8d2dd78645a6c4d -e LOOKUP_HOST=jarvis -e LOOKUP_CPUSET=6,7,14,15 -e LOOKUP_IMAGE="$(docker image inspect node:22 --format '{{.Id}}')" node:22 node --import tsx bench/lookup.ts; }
echo "d4 before: $(date -u +%FT%TZ) $(uptime)" > out/load.txt
run out/lookup-raw.json oracle=test/router-parity/oracle.ts,radix=src/http/router.ts > out/lookup-summary.txt 2> out/lookup-stderr.txt
echo "d4 after / aa before: $(date -u +%FT%TZ) $(uptime)" >> out/load.txt
run out/aa-raw.json oracle=test/router-parity/oracle.ts,oracle-copy=test/router-parity/oracle-copy.ts > out/aa-summary.txt 2> out/aa-stderr.txt
echo "aa after: $(date -u +%FT%TZ) $(uptime)" >> out/load.txt
Generated
+6 -4
View File
@@ -27,7 +27,7 @@
"npm:@types/autocannon@^7.12.7",
"npm:@types/busboy@^1.5.4",
"npm:@types/express@^5.0.6",
"npm:@types/node@^18.19.0",
"npm:@types/node@^22.20.5",
"npm:@types/ws@^8.18.1",
"npm:autocannon@8",
"npm:busboy@^1.6.0",
@@ -35,7 +35,7 @@
"npm:esbuild@0.27.2",
"npm:eslint@^9.39.5",
"npm:express@^5.2.1",
"npm:fastify@^5.11.0",
"npm:fastify@^5.12.5",
"npm:graphql@^16.9.0",
"npm:miniflare@^4.20260730.0",
"npm:prettier@^3.9.6",
@@ -46,7 +46,7 @@
"npm:typescript-eslint@^8.65.0",
"npm:typescript@^5.5.0",
"npm:vite@^6.4.3",
"npm:vitest@^3.2.7",
"npm:vitest@^4.1.11",
"npm:ws@^8.21.1"
],
"overrides": {
@@ -56,7 +56,9 @@
"uuid": "11.1.1"
}
},
"undici": "7.29.0"
"undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
}
}
}
+379 -529
View File
File diff suppressed because it is too large. Load diff
+9 -5
View File
@@ -26,7 +26,7 @@
"node"
],
"engines": {
"node": ">=18"
"node": ">=22"
},
"publishConfig": {
"access": "public"
@@ -103,6 +103,8 @@
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts",
"bench:compare": "tsx bench/compare.ts",
"bench:lookup": "tsx bench/lookup.ts",
"parity:mutants": "tsx test/router-parity/mutants.ts",
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true"
},
@@ -128,7 +130,9 @@
"uuid": "11.1.1"
}
},
"undici": "7.29.0"
"undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
@@ -140,7 +144,7 @@
"@types/autocannon": "^7.12.7",
"@types/busboy": "^1.5.4",
"@types/express": "^5.0.6",
"@types/node": "^18.19.0",
"@types/node": "^22.20.5",
"@types/ws": "^8.18.1",
"autocannon": "^8.0.0",
"busboy": "^1.6.0",
@@ -148,7 +152,7 @@
"eslint": "^9.39.5",
"esbuild": "0.27.2",
"express": "^5.2.1",
"fastify": "^5.11.0",
"fastify": "^5.12.5",
"graphql": "^16.9.0",
"miniflare": "^4.20260730.0",
"prettier": "^3.9.6",
@@ -158,7 +162,7 @@
"typescript": "^5.5.0",
"typescript-eslint": "^8.65.0",
"vite": "^6.4.3",
"vitest": "^3.2.7",
"vitest": "^4.1.11",
"ws": "^8.21.1"
}
}
+191 -21
View File
@@ -8,7 +8,18 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
import {
boundInbound,
controlBounds,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
matchWsRoute,
runWsConnection,
trackUntil,
type WsRequest,
type WsSocket,
} from '../http/ws-core';
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -34,12 +45,13 @@ import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
import { buildManifest, controlFrameLimit, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
@@ -195,6 +207,8 @@ export function createApp(opts: {
);
}
validateWsLimits(opts.limits);
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger);
@@ -254,6 +268,7 @@ export function createApp(opts: {
orderedProviders,
orderedSteps,
deps: pipelineDeps,
maxBodyBytes: opts.limits?.maxBodyBytes,
});
};
@@ -318,7 +333,13 @@ export function createApp(opts: {
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
// socket before it awaits the boot (#120).
const meshBounds = controlBounds(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes));
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits,
meshBounds,
});
const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps;
@@ -387,7 +408,7 @@ export function createApp(opts: {
return wrapped;
};
return {
const app: App = {
listen,
close,
handleSignals,
@@ -405,6 +426,10 @@ export function createApp(opts: {
bus,
logger,
};
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: nativeWsBytes(opts.mesh, registry, opts.limits, meshBounds),
});
}
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
@@ -519,14 +544,72 @@ function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void
const conflict = existing.find(
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
);
if (!conflict) return;
if (conflict) {
throw new Error(
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
);
}
for (const plan of existing) if (plan.method === candidate.method) assertNoSiblingConflict(plan, candidate);
}
/** The lookup tables a plan is served from. `negotiate` sits in both (see buildHttpRoutes / buildWsRoutes). */
const inHttpTable = (plan: RoutePlan): boolean => plan.transport !== 'ws';
const inWsTable = (plan: RoutePlan): boolean => plan.transport === 'ws' || plan.transport === 'negotiate';
/**
* Rejects a constrained param that can never be reached, or that ties with a sibling (CARD-13, #127).
* `earlier` was declared first. Each table is checked under its own precedence: HTTP ranks by
* specificity, WebSocket takes the first declared match. See `routeConflict` for the definitions.
*/
function assertNoSiblingConflict(earlier: RoutePlan, candidate: RoutePlan): void {
const tables: Array<[boolean, Precedence]> = [
[inHttpTable(earlier) && inHttpTable(candidate), 'specificity'],
[inWsTable(earlier) && inWsTable(candidate), 'registration'],
];
for (const [shared, precedence] of tables) {
if (!shared) continue;
const conflict = routeConflict(compilePattern(earlier.pattern), compilePattern(candidate.pattern), precedence);
if (conflict) throw new Error(localConflictMessage(conflict, [earlier, candidate], precedence));
}
}
function localConflictMessage(conflict: RouteConflict, plans: [RoutePlan, RoutePlan], precedence: Precedence): string {
const label = (plan: RoutePlan) =>
`${plan.transport === 'ws' ? 'WS' : plan.method} ${plan.pattern} at ${plan.declaration}`;
const ws = precedence === 'registration';
if (conflict.kind === 'ambiguous') {
const [earlier, candidate] = plans;
return (
`ambiguous route ${label(candidate)} conflicts with ${label(earlier)}: ` +
`both match ${quoteWitness(conflict.segment)} (${ws ? 'WebSocket' : candidate.method} ${shorten(conflict.path)}), ` +
'so only declaration order would choose between them — give the constraints disjoint languages, or merge the routes'
);
}
const loser = plans[conflict.loser];
const winner = plans[1 - conflict.loser];
const reason = ws
? 'WebSocket routes are matched in declaration order, and it is declared first'
: 'its constraint accepts every segment, and a constrained parameter outranks a plain one';
return (
`unreachable route ${label(loser)}: ${label(winner)} matches every request it would, and wins each one — ` +
`${reason}. Remove one of them, or narrow the constraint`
);
}
/** Quotes a witness segment for an error message, escaping control characters and eliding long ones. */
function quoteWitness(segment: string): string {
const shown = JSON.stringify(segment.length > 32 ? segment.slice(0, 32) : segment).slice(1, -1);
return segment.length > 32 ? `'${shown}…' (${segment.length} characters)` : `'${shown}'`;
}
const shorten = (path: string): string => (path.length > 80 ? `${path.slice(0, 80)}…` : path);
/**
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
@@ -856,6 +939,41 @@ function warnIfCleartext(url: string, logger: Logger): void {
);
}
/** A route a teapot exported, and the teapot it came from. */
interface RemoteRoute {
method: string;
pattern: string;
url: string;
}
/**
* The same sibling check local routes get (CARD-13, #127), between routes from teapots. They share the
* remote tree, ranked by specificity. A local route against a remote one is not checked here: the
* local one wins by design, and a same-shape pair is warned about below.
*/
function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRoute): void {
for (const prior of accepted) {
if (prior.method !== route.method) continue;
const conflict = routeConflict(compilePattern(prior.pattern), compilePattern(route.pattern), 'specificity');
if (!conflict) continue;
const show = (r: RemoteRoute) => `'${r.method} ${r.pattern}' from ${r.url}`;
if (conflict.kind === 'ambiguous') {
throw new Error(
`mesh: ambiguous remote route ${show(route)} conflicts with ${show(prior)}: ` +
`both match ${quoteWitness(conflict.segment)} (${route.method} ${shorten(conflict.path)}) — ` +
'green-tea will not choose one for you. Export only one of them, or give their constraints disjoint languages.',
);
}
const [loser, winner] = conflict.loser === 0 ? [prior, route] : [route, prior];
throw new Error(
`mesh: unreachable remote route ${show(loser)}: ${show(winner)} matches every request it would, and wins each one — ` +
'its constraint accepts every segment, and a constrained parameter outranks a plain one. Export only one of them.',
);
}
}
/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */
async function spliceRemoteScopes(
mesh: MeshConfig,
@@ -867,6 +985,7 @@ async function spliceRemoteScopes(
const meshLinks: Link[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order
try {
for (const teapot of mesh.teapots ?? []) {
@@ -917,6 +1036,12 @@ async function spliceRemoteScopes(
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
assertNoRemoteSiblingConflict(remoteAccepted, {
method: route.method,
pattern: route.pattern,
url: teapot.url,
});
remoteAccepted.push({ method: route.method, pattern: route.pattern, url: teapot.url });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
@@ -936,7 +1061,9 @@ async function spliceRemoteScopes(
);
}
remoteRoutes.push({
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
remoteRoutes.push(
markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
@@ -953,7 +1080,8 @@ async function spliceRemoteScopes(
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}),
);
}
}
} catch (err) {
@@ -1105,6 +1233,21 @@ function makeAppBooter(
return once(runBoot);
}
/**
* The one inbound bound Bun applies natively to every socket (`WS_MAX_MESSAGE_BYTES`). A teapot
* raises it to its control channel's (#120); user routes still close at `maxWsMessageBytes`,
* because `app.upgrade` bounds them itself.
*/
function nativeWsBytes(
mesh: MeshConfig | undefined,
registry: Registry,
limits: RequestLimits | undefined,
meshBounds: ReturnType<typeof controlBounds>,
): number {
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits);
}
/**
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
@@ -1112,7 +1255,13 @@ function makeAppBooter(
function buildMeshControl(
mesh: MeshConfig | undefined,
registry: Registry,
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
deps: {
container: Container;
orderedProviders: GraphNode[];
orderedSteps: GraphNode[];
deps: PipelineDeps;
maxBodyBytes?: number;
},
): MeshControl | undefined {
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
@@ -1183,7 +1332,14 @@ function buildMeshControl(
return result;
};
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
return createMeshControl({
secret: mesh.secret,
manifest,
resolveScope,
resolveRoute,
bus,
maxBodyBytes: deps.maxBodyBytes,
});
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
@@ -1275,22 +1431,36 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
bounds: { limits?: RequestLimits; meshBounds: ReturnType<typeof controlBounds> },
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
// subscriber is dropped, so anything the peer sends while providers are still booting would be
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
// until timeout against a teapot whose providers happened to boot slowly.
const frames = socket.inbound[Symbol.asyncIterator]();
const ready: WsSocket = Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
}) as WsSocket;
// Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
// with no subscriber is dropped, so anything the peer sends while providers are still booting
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// hang until timeout against a teapot whose providers happened to boot slowly.
// The path comes first, though, because it decides the bound: the mesh control channel carries
// whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120) — once
// its peer authenticates. Until then, and so throughout the boot, it takes hello-sized frames.
let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
// otherwise reject out of the matcher and close with 1011, a server-error code for a client error.
try {
path = normalizeRequestPath(request.url.split('?')[0]);
} catch {
socket.close(1008, 'invalid request path');
return;
}
const ready =
path === MESH_CONTROL_PATH
? boundInbound(socket, bounds.meshBounds.preAuth, bounds.meshBounds.authed)
: boundInbound(socket, bounds.limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
const path = request.url.split('?')[0];
const meshControl = getMeshControl();
// The reserved mesh path, checked before route matching: this is what lets a teapot export
@@ -1489,8 +1659,8 @@ function closeApp(
timeoutMs,
});
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
// below — `engines` in package.json only guarantees >=18, so this matters.
// closeAllConnections() and closeIdleConnections() below both arrived in Node 18.2;
// `engines` guarantees >=22, so both are always present.
server.closeAllConnections();
finish();
}, drainBudget);
+45 -4
View File
@@ -1,9 +1,16 @@
import { channel } from './channel';
import type { Channel } from './channel';
import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core';
import {
WS_MAX_MESSAGE_BYTES,
DEFAULT_MAX_WS_MESSAGE_BYTES,
WS_HIGH_WATER_MARK,
type WsSocket,
type WsRequest,
} from './http/ws-core';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -13,11 +20,15 @@ interface BunServerWebSocket {
send(data: string): number;
close(code?: number, reason?: string): void;
terminate?(): void;
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
getBufferedAmount?(): number;
}
interface BunWebSocketHandler {
maxPayloadLength?: number;
open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void;
drain?(ws: BunServerWebSocket): void;
error?(ws: BunServerWebSocket, error?: unknown): void;
}
interface BunServer {
@@ -55,6 +66,13 @@ interface BunConnData {
wsReq: WsRequest;
inbound: Channel<unknown>;
ac: AbortController;
/** `drained` callers waiting for Bun's `drain` callback or the close (#41). */
drainWaiters: Array<() => void>;
}
/** Wakes every `drained` caller; each rechecks the buffer and waits again if it is still over. */
function releaseDrain(ws: BunServerWebSocket): void {
(ws.data as BunConnData).drainWaiters.splice(0).forEach((resolve) => resolve());
}
/**
@@ -63,9 +81,17 @@ interface BunConnData {
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
*/
function bunSocket(ws: BunServerWebSocket): WsSocket {
const { inbound, ac } = ws.data as BunConnData;
const { inbound, ac, drainWaiters } = ws.data as BunConnData;
return neutralSocket(ws, inbound, ac);
// Bun has no `bufferedAmount` property, so the generic poll would never wait. It has better: a
// `getBufferedAmount()` to read and a server-level `drain` callback to wait on, no timer needed.
const drained = async (): Promise<void> => {
while (!ac.signal.aborted && (ws.getBufferedAmount?.() ?? 0) > WS_HIGH_WATER_MARK) {
await new Promise<void>((resolve) => drainWaiters.push(resolve));
}
};
return Object.assign(neutralSocket(ws, inbound, ac), { drained });
}
/**
@@ -95,14 +121,24 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
const inbound = channel();
const ac = new AbortController();
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
const data: BunConnData = { wsReq, inbound, ac };
const data: BunConnData = { wsReq, inbound, ac, drainWaiters: [] };
if (server.upgrade(request, { data })) return undefined;
return new Response('WebSocket upgrade failed', { status: 400 });
}
// The same object goes to `app.fetch`, which is what lets it find the peer again.
setPeer(request, server.requestIP(request)?.address ?? '');
return app.fetch(request);
},
websocket: {
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
// `app.upgrade` checks the same bound again on the decoded text.
// On a teapot the value is the mesh control channel's larger bound (#120), and `app.upgrade`
// alone holds user routes to `maxWsMessageBytes`, closing 1009 on every Bun version.
maxPayloadLength:
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
open(ws) {
const { wsReq } = ws.data as BunConnData;
@@ -113,15 +149,20 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
inbound.push(decodeMessage(message));
},
drain(ws) {
releaseDrain(ws);
},
close(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.close();
ac.abort();
releaseDrain(ws);
},
error(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.fail(new Error('websocket error'));
ac.abort();
releaseDrain(ws);
},
},
});
+31 -2
View File
@@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
}
/**
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
* because each tsup entry carries its own copy of this module.
*/
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
export interface ChannelSink<T> {
push(value: T): void;
end(): void;
fail(err: unknown): void;
}
/** A channel that can be tapped; every channel built by {@link channel} is one. */
export interface TappableChannel<T> extends Channel<T> {
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
}
interface Sub<T> {
iterator: AsyncIterator<T>;
push(value: T, cap: number): void;
@@ -84,9 +104,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
*/
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> {
const cap = opts.buffer ?? Infinity;
const subs = new Set<Sub<T>>();
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false;
let closedFlag = false;
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
subs.add(sub);
return sub.iterator;
},
[CHANNEL_TAP](sink) {
if (done) {
sink.end();
return () => {};
}
subs.add(sink);
return () => subs.delete(sink);
},
};
}
+6 -2
View File
@@ -1,9 +1,10 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
// The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
// Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
interface WebSocket extends EventfulSocket {
binaryType: string;
}
@@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
return response;
}
// The same object goes to `app.fetch`, which is what lets it find the peer again. A unix socket
// has no `hostname`, and records nothing.
setPeer(request, info.remoteAddr.hostname);
return app.fetch(request);
});
+14 -6
View File
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
/**
* Reads the raw request body, enforcing `limit`.
*
* The adapter owns this and nothing else about the body, because enforcement is the one place the
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
* without bound first.
* The adapter owns this and nothing else about the body, because getting the bytes is the one place
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
* possible — measuring afterwards would force the reader to buffer without bound first.
*
* The failure branch is opaque on purpose: Node answers an over-limit request with
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
@@ -41,6 +40,15 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
*/
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/**
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
* and the running total still enforces the limit on whatever actually arrives.
*/
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
+5 -21
View File
@@ -9,31 +9,15 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
* `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
*
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
*
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release.
*
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
* Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
* Node 18 floor.
*/
const randomUUID: () => string = (() => {
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
const randomUUID = (): string => crypto.randomUUID();
/**
* A runtime-neutral inbound request.
+27
View File
@@ -0,0 +1,27 @@
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
// Internal: not exported from the package.
//
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
// bare `app.fetch` from user code has always seen.
//
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
// with no shared chunk, so each carries its own copy of this one: a module-private map in
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
// that loads core both as ESM and as CommonJS has the same split.
const KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, ip: string): void {
if (ip) peers.set(request, ip);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
+5
View File
@@ -1,8 +1,13 @@
import type http from 'http';
import { HttpError } from '../signals';
import { declaresOverLimit } from './body';
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
// A declared length over the limit is refused without waiting for the first chunk, which could
// otherwise sit until the request timeout. The fetch adapter makes the same check.
if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large');
const chunks: Buffer[] = [];
let total = 0;
+814
View File
@@ -0,0 +1,814 @@
/**
* Boot-time detection of route params that can never be reached, or that tie with a sibling
* (FPRD-001 CARD-13, #127).
*
* `assertSafeConstraint` admits only a linear, group-free regex subset, so every constraint reads back
* as a sequence of blocks — (set of characters, min, max). Intersection and the "accepts every segment"
* question are then decided exactly, from the sets and counts, with no pattern lists and no sampling:
*
* - {@link intersectionWitness} walks the product of two block sequences and returns a segment both
* accept, or proves there is none.
* - {@link acceptsEverySegment} is a closed-form test on the blocks; the proof is in its comment.
*
* The universe is what the router can actually hand a param: a *decoded*, non-empty path segment —
* any Unicode scalar value, `/` included (from `%2F`) — except `.` and `..`, which normalization
* resolves away before matching. Everything here is measured against that universe, so a witness is a
* segment a real request can carry.
*
* Nothing here runs per request. The lookup path does not import this module.
*/
import { CONSTRAINT_ATOM, CONSTRAINT_QUANTIFIER } from './router';
import type { CompiledPattern, CompiledSegment } from './router';
// ---------------------------------------------------------------------------------------------
// Character sets: sorted, disjoint, non-adjacent inclusive ranges, flattened [lo0, hi0, lo1, hi1, …].
// ---------------------------------------------------------------------------------------------
/** A set of Unicode scalar values. */
export type CharSet = readonly number[];
const MAX_CODE_POINT = 0x10ffff;
const DOT = 0x2e;
/** Every Unicode scalar value: what a decoded segment can contain. Lone surrogates fail `decodeURIComponent`. */
const SIGMA: CharSet = [0, 0xd7ff, 0xe000, MAX_CODE_POINT];
function fromRanges(ranges: Array<[number, number]>): CharSet {
const sorted = ranges.filter(([lo, hi]) => lo <= hi).sort((a, b) => a[0] - b[0]);
const out: number[] = [];
for (const [lo, hi] of sorted) {
const last = out.length - 1;
if (last > 0 && lo <= out[last] + 1) out[last] = Math.max(out[last], hi);
else out.push(lo, hi);
}
return intersect(out, SIGMA);
}
function intersect(a: CharSet, b: CharSet): CharSet {
const out: number[] = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const lo = Math.max(a[i], b[j]);
const hi = Math.min(a[i + 1], b[j + 1]);
if (lo <= hi) out.push(lo, hi);
if (a[i + 1] < b[j + 1]) i += 2;
else j += 2;
}
return out;
}
/** Σ minus `set`. */
function complement(set: CharSet): CharSet {
const out: number[] = [];
let next = 0;
for (let i = 0; i < set.length; i += 2) {
if (set[i] > next) out.push(next, set[i] - 1);
next = set[i + 1] + 1;
}
if (next <= MAX_CODE_POINT) out.push(next, MAX_CODE_POINT);
return intersect(out, SIGMA);
}
function has(set: CharSet, cp: number): boolean {
for (let i = 0; i < set.length; i += 2) if (cp >= set[i] && cp <= set[i + 1]) return true;
return false;
}
const isEmptySet = (set: CharSet): boolean => set.length === 0;
const isSigma = (set: CharSet): boolean => set.length === SIGMA.length && set.every((v, i) => v === SIGMA[i]);
/** Readable witness characters first: digits, lowercase, uppercase, then printable ASCII. */
const PREFERRED: Array<[number, number]> = [
[0x30, 0x39],
[0x61, 0x7a],
[0x41, 0x5a],
[0x21, 0x7e],
];
/** Picks one member of a non-empty set, preferring a character a person can read in an error message. */
function pick(set: CharSet): number {
for (const [lo, hi] of PREFERRED) {
const within = intersect(set, [lo, hi]);
if (within.length) return within[0];
}
return set[0];
}
// ---------------------------------------------------------------------------------------------
// Atoms → character sets, with the semantics of a `u`-flag RegExp (no `i`, no `s`).
// ---------------------------------------------------------------------------------------------
const DIGIT: CharSet = [0x30, 0x39];
const WORD: CharSet = [0x30, 0x39, 0x41, 0x5a, 0x5f, 0x5f, 0x61, 0x7a];
/** ECMAScript WhiteSpace ∪ LineTerminator, which is what `\s` matches. */
const SPACE: CharSet = fromRanges([
[0x09, 0x0d],
[0x20, 0x20],
[0xa0, 0xa0],
[0x1680, 0x1680],
[0x2000, 0x200a],
[0x2028, 0x2029],
[0x202f, 0x202f],
[0x205f, 0x205f],
[0x3000, 0x3000],
[0xfeff, 0xfeff],
]);
/** Unescaped `.` without the `s` flag: anything but a line terminator. */
const ANY_BUT_LINE_TERMINATOR: CharSet = complement(
fromRanges([
[0x0a, 0x0a],
[0x0d, 0x0d],
[0x2028, 0x2029],
]),
);
const CLASS_ESCAPES: Record<string, CharSet> = {
d: DIGIT,
D: complement(DIGIT),
w: WORD,
W: complement(WORD),
s: SPACE,
S: complement(SPACE),
};
const CONTROL_ESCAPES: Record<string, number> = { b: 0x08, f: 0x0c, n: 0x0a, r: 0x0d, t: 0x09, v: 0x0b };
const IDENTITY_ESCAPES = new Set('^$\\.*+?()[]{}|/-');
/** One parsed class atom: a single code point (a valid range end) or a class escape such as `\d`. */
type ClassAtom = { cp: number; end: number } | { set: CharSet; end: number };
/** Signals a construct this reader does not model; the caller then asks the RegExp engine directly. */
class Unmodelled extends Error {}
function hexAt(source: string, start: number, length: number): number {
const text = source.slice(start, start + length);
if (!/^[0-9a-fA-F]+$/.test(text) || text.length !== length) throw new Unmodelled();
return parseInt(text, 16);
}
/** Reads `\u…` (four hex digits, a surrogate pair of two, or `\u{…}`) starting after the `u`. */
function unicodeEscape(source: string, at: number): { cp: number; end: number } {
if (source[at] === '{') {
const close = source.indexOf('}', at);
if (close < 0) throw new Unmodelled();
return { cp: hexAt(source, at + 1, close - at - 1), end: close + 1 };
}
const cp = hexAt(source, at, 4);
const isLead = cp >= 0xd800 && cp <= 0xdbff;
if (isLead && source.startsWith('\\u', at + 4)) {
const trail = hexAt(source, at + 6, 4);
if (trail >= 0xdc00 && trail <= 0xdfff)
return { cp: (cp - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000, end: at + 10 };
}
return { cp, end: at + 4 };
}
/** Reads the escape whose backslash is at `at - 1`, inside a class. */
function classEscape(source: string, at: number): ClassAtom {
const c = source[at];
if (CLASS_ESCAPES[c]) return { set: CLASS_ESCAPES[c], end: at + 1 };
if (c in CONTROL_ESCAPES) return { cp: CONTROL_ESCAPES[c], end: at + 1 };
if (IDENTITY_ESCAPES.has(c)) return { cp: c.charCodeAt(0), end: at + 1 };
if (c === '0' && !/[0-9]/.test(source[at + 1] ?? '')) return { cp: 0, end: at + 1 };
if (c === 'c' && /[A-Za-z]/.test(source[at + 1] ?? '')) return { cp: source.charCodeAt(at + 1) % 32, end: at + 2 };
if (c === 'x') return { cp: hexAt(source, at + 1, 2), end: at + 3 };
if (c === 'u') return unicodeEscape(source, at + 1);
// `\p{…}` / `\P{…}` need Unicode property tables; anything else would not have compiled.
throw new Unmodelled();
}
function classAtom(source: string, at: number): ClassAtom {
if (source[at] === '\\') return classEscape(source, at + 1);
const cp = source.codePointAt(at)!;
return { cp, end: at + (cp > 0xffff ? 2 : 1) };
}
/** Parses the body of a `[...]` class (between the brackets) in `u` mode. */
function classSet(body: string): CharSet {
const negated = body.startsWith('^');
const ranges: Array<[number, number]> = [];
const sets: CharSet[] = [];
let at = negated ? 1 : 0;
while (at < body.length) {
const first = classAtom(body, at);
at = first.end;
// `a-z`: a dash between two single characters. A dash first, last, or next to a class escape is
// literal — and in `u` mode a class escape next to a range dash does not compile at all.
if (body[at] === '-' && at + 1 < body.length && 'cp' in first) {
const last = classAtom(body, at + 1);
if (!('cp' in last)) throw new Unmodelled();
ranges.push([first.cp, last.cp]);
at = last.end;
continue;
}
if ('cp' in first) ranges.push([first.cp, first.cp]);
else sets.push(first.set);
}
const union = fromRanges([...ranges, ...sets.flatMap((set) => pairs(set))]);
return negated ? complement(union) : union;
}
function pairs(set: CharSet): Array<[number, number]> {
const out: Array<[number, number]> = [];
for (let i = 0; i < set.length; i += 2) out.push([set[i], set[i + 1]]);
return out;
}
/** The engine's own answer, one code point at a time. Only for constructs {@link classSet} does not model. */
function enumerateSet(atom: string): CharSet {
const test = new RegExp(`^${atom}$`, 'u');
const ranges: Array<[number, number]> = [];
let start = -1;
for (let cp = 0; cp <= MAX_CODE_POINT + 1; cp++) {
const inside = cp <= MAX_CODE_POINT && (cp < 0xd800 || cp > 0xdfff) && test.test(String.fromCodePoint(cp));
if (inside && start < 0) start = cp;
if (!inside && start >= 0) {
ranges.push([start, cp - 1]);
start = -1;
}
}
return fromRanges(ranges);
}
/** The set of characters one atom of the safe subset matches. */
export function atomSet(atom: string): CharSet {
if (atom === '.') return ANY_BUT_LINE_TERMINATOR;
if (atom.length === 1) return [atom.charCodeAt(0), atom.charCodeAt(0)];
if (atom[0] === '\\' && CLASS_ESCAPES[atom[1]]) return CLASS_ESCAPES[atom[1]];
if (atom[0] === '\\') return [atom.charCodeAt(1), atom.charCodeAt(1)];
try {
return classSet(atom.slice(1, -1));
} catch (error) {
if (!(error instanceof Unmodelled)) throw error;
return enumerateSet(atom);
}
}
// ---------------------------------------------------------------------------------------------
// Constraints → block sequences.
// ---------------------------------------------------------------------------------------------
/** `set` repeated between `min` and `max` times; `max` is `Infinity` for `+`, `*` and `{n,}`. */
export interface Block {
set: CharSet;
min: number;
max: number;
}
function bounds(quantifier: string): { min: number; max: number } {
if (quantifier === '') return { min: 1, max: 1 };
if (quantifier === '?') return { min: 0, max: 1 };
if (quantifier === '*') return { min: 0, max: Infinity };
if (quantifier === '+') return { min: 1, max: Infinity };
const [minText, maxText] = quantifier.slice(1, -1).split(',');
const min = Number(minText);
if (maxText === undefined) return { min, max: min };
return { min, max: maxText === '' ? Infinity : Number(maxText) };
}
const chainCache = new Map<string, Block[]>();
/** Reads a constraint that `compilePattern` already accepted back as its sequence of blocks. */
export function constraintBlocks(source: string): Block[] {
const cached = chainCache.get(source);
if (cached) return cached;
const blocks: Block[] = [];
let offset = 0;
while (offset < source.length) {
const rest = source.slice(offset);
const atom = CONSTRAINT_ATOM.exec(rest)![0];
const quantifier = CONSTRAINT_QUANTIFIER.exec(rest.slice(atom.length))?.[0] ?? '';
blocks.push({ set: atomSet(atom), ...bounds(quantifier) });
offset += atom.length + quantifier.length;
}
chainCache.set(source, blocks);
return blocks;
}
/** What a plain `:param` accepts: any non-empty segment. */
const ANY_SEGMENT: Block[] = [{ set: SIGMA, min: 1, max: Infinity }];
// ---------------------------------------------------------------------------------------------
// Universality.
// ---------------------------------------------------------------------------------------------
/**
* Whether a block sequence accepts every segment a request can carry.
*
* True exactly when (1) some block is Σ with no upper bound, (2) every block with `min ≥ 1` is Σ, and
* (3) the mins add up to at most 1. Sufficient: skip every optional block, and the unbounded Σ block
* takes whatever the mandatory ones leave over. Necessary, each against a segment in the universe:
* (3) fails on `a`, too short; (2) fails on `zzz…`, with `z` outside the mandatory block's set; and
* without (1), take `zⱼ` outside each unbounded block's set and repeat the round `z₁…zₜ` more times
* than the bounded blocks' total capacity plus `t`. Blocks are consumed in order, so some round
* lands wholly inside one unbounded block, which cannot hold its own `zⱼ`.
*
* Excluding `.` and `..` from the universe changes nothing: every counterexample above is longer or
* is `a`.
*/
export function acceptsEverySegment(blocks: Block[]): boolean {
const unboundedSigma = blocks.some((block) => block.max === Infinity && isSigma(block.set));
const mandatoryAreSigma = blocks.every((block) => block.min === 0 || isSigma(block.set));
const minLength = blocks.reduce((sum, block) => sum + block.min, 0);
return unboundedSigma && mandatoryAreSigma && minLength <= 1;
}
// ---------------------------------------------------------------------------------------------
// Intersection with a witness.
// ---------------------------------------------------------------------------------------------
/** Entry `i`: every block after block `i` is optional, so the sequence may stop once block `i` is done. */
function endsAfter(blocks: Block[]): boolean[] {
const out = new Array<boolean>(blocks.length);
let optionalTail = true;
for (let i = blocks.length - 1; i >= 0; i--) {
out[i] = optionalTail;
optionalTail &&= blocks[i].min === 0;
}
return out;
}
/**
* The reachable configurations on entry to one pair of blocks (`a` in sequence A, `b` in sequence B).
*
* `fresh` names the side that has just entered its block and has consumed nothing in it yet; the
* other side, the carry, has already consumed `value` characters of its block. Both fresh is `fresh
* = 'a'` with `value = 0`. Unbounded blocks clamp the counter at their `min`, since every count past
* it behaves the same, so `value` never exceeds the carry block's `max`, or its `min` when unbounded.
*
* `dotsOnly` stays true while every character so far is `.`: a witness must not be `.` or `..`.
*/
interface EntryState {
a: number;
b: number;
fresh: 'a' | 'b';
dotsOnly: boolean;
reached: Uint8Array;
/** Union-find "next unreached value", so each value is filled once however many predecessors reach it. */
free: Int32Array;
prev: Array<EntryState | undefined>;
prevValue: Int32Array;
runChar: Int32Array;
runLength: Int32Array;
}
/** How a state was reached: from `(from, value)` by a run of `char`, at least `tLo` long. */
interface Run {
from: EntryState | undefined;
value: number;
char: number;
tLo: number;
}
/** Who is fresh in the next state: both sides, the same side as now, or the side that was the carry. */
type NextFresh = 'both' | 'same' | 'flip';
const counterCap = (block: Block): number => (block.max === Infinity ? block.min : block.max);
const clampTo = (block: Block, count: number): number => (block.max === Infinity ? Math.min(count, block.min) : count);
function findFree(state: EntryState, x: number): number {
while (state.free[x] !== x) x = state.free[x] = state.free[state.free[x]];
return x;
}
class ProductWalk {
private readonly states = new Map<string, EntryState>();
private readonly endA: boolean[];
private readonly endB: boolean[];
constructor(
private readonly A: Block[],
private readonly B: Block[],
) {
this.endA = endsAfter(A);
this.endB = endsAfter(B);
}
/** Returns a non-empty string in both languages that is neither `.` nor `..`, or `undefined` if none exists. */
witness(): string | undefined {
this.fill(this.state(0, 0, 'a', true), 0, 0, { from: undefined, value: 0, char: 0, tLo: 0 }, 0);
// Every transition moves to a later `a`, or to the same `a` and a later `b`, so visiting pairs in
// that order sees each state after everything that reaches it.
for (let a = 0; a < this.A.length; a++)
for (let b = 0; b < this.B.length; b++)
for (const key of [`${a},${b},a,1`, `${a},${b},a,0`, `${a},${b},b,1`, `${a},${b},b,0`]) {
const state = this.states.get(key);
const found = state && this.expand(state);
if (found !== undefined) return found;
}
return undefined;
}
private state(a: number, b: number, fresh: 'a' | 'b', dotsOnly: boolean): EntryState {
const key = `${a},${b},${fresh},${dotsOnly ? 1 : 0}`;
let state = this.states.get(key);
if (!state) {
const size = counterCap(fresh === 'a' ? this.B[b] : this.A[a]) + 1;
state = {
a,
b,
fresh,
dotsOnly,
reached: new Uint8Array(size),
free: new Int32Array(size + 1).map((_, i) => i),
prev: new Array(size),
prevValue: new Int32Array(size),
runChar: new Int32Array(size),
runLength: new Int32Array(size),
};
this.states.set(key, state);
}
return state;
}
/** Marks `[lo, hi]` reached in `target`; value `w` came by a run of length `max(tLo, w - offset)`. */
private fill(target: EntryState, lo: number, hi: number, run: Run, offset: number): void {
for (let w = findFree(target, lo); w <= hi; w = findFree(target, w + 1)) {
target.reached[w] = 1;
target.prev[w] = run.from;
target.prevValue[w] = run.value;
target.runChar[w] = run.char;
target.runLength[w] = Math.max(run.tLo, w - offset);
target.free[w] = w + 1;
}
}
/**
* The state after one or both sides move to their next block, from the current fresh side's point
* of view: `freshAt` is the fresh side's block index, `carryAt` the carry side's. `undefined` when
* a side would run past its last block.
*/
private next(state: EntryState, freshAt: number, carryAt: number, mode: NextFresh, dotsOnly: boolean) {
const freshIsA = state.fresh === 'a';
const [a, b] = freshIsA ? [freshAt, carryAt] : [carryAt, freshAt];
if (a >= this.A.length || b >= this.B.length) return undefined;
const nextFreshIsA = mode === 'both' || (mode === 'same' ? freshIsA : !freshIsA);
return this.state(a, b, nextFreshIsA ? 'a' : 'b', dotsOnly);
}
/** Follows every move out of one entry state. Returns a witness as soon as one completes. */
private expand(state: EntryState): string | undefined {
this.skip(state);
const shared = intersect(this.A[state.a].set, this.B[state.b].set);
if (isEmptySet(shared)) return undefined;
const notDot = intersect(shared, complement([DOT, DOT]));
const char = isEmptySet(notDot) ? DOT : pick(notDot);
const dotsOnly = state.dotsOnly && char === DOT;
for (let value = 0; value < state.reached.length; value++) {
if (!state.reached[value]) continue;
const found = this.runFrom(state, value, char, dotsOnly);
if (found !== undefined) return found;
}
return undefined;
}
/**
* Zero-length moves past optional blocks. The fresh side may skip a `min = 0` block it has not
* started, keeping the carry's count; a carry still at 0 in a `min = 0` block may skip it too.
* Skipping one block at a time keeps every value's moves O(1); runs of optional blocks chain.
*/
private skip(state: EntryState): void {
const freshIsA = state.fresh === 'a';
const [freshAt, carryAt] = freshIsA ? [state.a, state.b] : [state.b, state.a];
const fresh = freshIsA ? this.A[state.a] : this.B[state.b];
const carry = freshIsA ? this.B[state.b] : this.A[state.a];
const keep = (value: number): Run => ({ from: state, value, char: 0, tLo: 0 });
const freshSkip = fresh.min === 0 ? this.next(state, freshAt + 1, carryAt, 'same', state.dotsOnly) : undefined;
for (let value = 0; freshSkip && value < state.reached.length; value++)
if (state.reached[value]) this.fill(freshSkip, value, value, keep(value), value);
const carrySkip =
carry.min === 0 && state.reached[0] && this.next(state, freshAt, carryAt + 1, 'same', state.dotsOnly);
if (carrySkip) this.fill(carrySkip, 0, 0, keep(0), 0);
}
/** A run of `t ≥ 1` copies of `char` in the current pair, then one or both sides leave their block. */
private runFrom(state: EntryState, value: number, char: number, dotsOnly: boolean): string | undefined {
const freshIsA = state.fresh === 'a';
const [freshAt, carryAt] = freshIsA ? [state.a, state.b] : [state.b, state.a];
const fresh = freshIsA ? this.A[state.a] : this.B[state.b];
const carry = freshIsA ? this.B[state.b] : this.A[state.a];
const tHi = Math.min(fresh.max, carry.max - value);
if (tHi < 1) return undefined;
// Both leave: the run completes both blocks at once — and may complete the whole string.
const bothLo = Math.max(1, fresh.min, carry.min - value);
if (bothLo <= tHi) {
if (!dotsOnly && this.endA[state.a] && this.endB[state.b]) return this.trace(state, value, char, bothLo);
const target = this.next(state, freshAt + 1, carryAt + 1, 'both', dotsOnly);
if (target) this.fill(target, 0, 0, { from: state, value, char, tLo: bothLo }, 0);
}
// The fresh side leaves; the carry stays in its block, `t` characters further on.
const freshLo = Math.max(1, fresh.min);
const same = freshLo <= tHi && this.next(state, freshAt + 1, carryAt, 'same', dotsOnly);
if (same)
this.fill(
same,
clampTo(carry, value + freshLo),
clampTo(carry, value + tHi),
{ from: state, value, char, tLo: freshLo },
value,
);
// The carry leaves; the fresh side stays, `t` characters in, and becomes the carry.
const carryLo = Math.max(1, carry.min - value);
const flip = carryLo <= tHi && this.next(state, freshAt, carryAt + 1, 'flip', dotsOnly);
if (flip)
this.fill(flip, clampTo(fresh, carryLo), clampTo(fresh, tHi), { from: state, value, char, tLo: carryLo }, 0);
return undefined;
}
/** Rebuilds the witness by following predecessors back to the start. */
private trace(state: EntryState, value: number, char: number, length: number): string {
const runs: string[] = [String.fromCodePoint(char).repeat(length)];
let at: EntryState | undefined = state;
let v = value;
while (at) {
if (at.runLength[v]) runs.push(String.fromCodePoint(at.runChar[v]).repeat(at.runLength[v]));
const prev: EntryState | undefined = at.prev[v];
v = at.prevValue[v];
at = prev;
}
return runs.reverse().join('');
}
}
/** The lengths of the all-dot strings a sequence accepts: an interval, since a sum of intervals is one. */
function dotLengths(blocks: Block[]): [number, number] | undefined {
let lo = 0;
let hi = 0;
for (const block of blocks) {
const dot = has(block.set, DOT);
if (!dot && block.min > 0) return undefined;
lo += block.min;
if (dot) hi += block.max;
}
return [lo, hi];
}
/**
* A segment both block sequences accept, or `undefined` when their languages share none.
*
* Exact over the decoded-segment universe. The product walk finds any common string containing a
* character other than `.`; the all-dot strings are an interval of lengths per side, and a common one
* of length 3 or more is `...`, a segment normalization keeps.
*
* Cost: at most 4·|A|·|B| entry states, each holding at most K + 1 counter values (K ≤ 2048, the
* largest quantifier bound the subset allows), each value expanded into at most |A| + |B| successor
* fills that union-find keeps linear. O(|A|·|B|·(|A| + |B|)·K), with |A|, |B| ≤ 128 blocks.
*/
export function intersectionWitness(A: Block[], B: Block[]): string | undefined {
const found = new ProductWalk(A, B).witness();
if (found !== undefined) return found;
const dotsA = dotLengths(A);
const dotsB = dotLengths(B);
if (!dotsA || !dotsB) return undefined;
const length = Math.max(3, dotsA[0], dotsB[0]);
return length <= Math.min(dotsA[1], dotsB[1]) ? '.'.repeat(length) : undefined;
}
// ---------------------------------------------------------------------------------------------
// Route patterns.
// ---------------------------------------------------------------------------------------------
/**
* How a table picks between two routes that match the same request.
*
* `specificity` is the HTTP router: static > constrained > plain at the first differing segment,
* registration order on a tie. `registration` is the WebSocket matcher, which takes the first route
* declared that matches (frozen as observed by the parity corpus, `matcher-ws.json`).
*/
export type Precedence = 'specificity' | 'registration';
export type RouteConflict =
/** Two constrained siblings accept a common segment: `segment` decoded, `path` a request both match. */
| { kind: 'ambiguous'; segment: string; path: string }
/** The route at `loser` (0 = first argument, 1 = second) can never be selected: the other wins every request it matches. */
| { kind: 'unreachable'; loser: 0 | 1 };
type Param = Extract<CompiledSegment, { kind: 'param' }>;
const blocksOf = (segment: Param): Block[] =>
segment.constraintSource ? constraintBlocks(segment.constraintSource) : ANY_SEGMENT;
function decodedStatic(value: string): string | undefined {
try {
const decoded = decodeURIComponent(value);
// A request segment spelling `.` or `..` is resolved away before matching, so no request reaches it.
return decoded === '.' || decoded === '..' ? undefined : decoded;
} catch {
return undefined;
}
}
/** A raw request segment that `segment` alone accepts, or `undefined` if it accepts none. */
function segmentWitness(segment: CompiledSegment): string | undefined {
if (segment.kind === 'static') return decodedStatic(segment.value) === undefined ? undefined : segment.value;
if (segment.kind === 'catchAll') return undefined;
const value = intersectionWitness(blocksOf(segment), ANY_SEGMENT);
return value === undefined ? undefined : encodeURIComponent(value);
}
/** A raw request segment both accept, or `undefined`. */
function overlapWitness(x: CompiledSegment, y: CompiledSegment): string | undefined {
if (x.kind === 'static' && y.kind === 'static') return x.value === y.value ? segmentWitness(x) : undefined;
if (x.kind === 'static' || y.kind === 'static') {
const [fixed, param] = (x.kind === 'static' ? [x, y] : [y, x]) as [
Extract<CompiledSegment, { kind: 'static' }>,
Param,
];
const decoded = decodedStatic(fixed.value);
return decoded !== undefined && (!param.constraint || param.constraint.test(decoded)) ? fixed.value : undefined;
}
const value = intersectionWitness(blocksOf(x as Param), blocksOf(y as Param));
return value === undefined ? undefined : encodeURIComponent(value);
}
/** Witness segments for every fixed segment from `from` on, or `undefined` if one accepts nothing. */
function restWitness(segments: CompiledSegment[], from: number): string[] | undefined {
const out: string[] = [];
for (const segment of segments.slice(from)) {
if (segment.kind === 'catchAll') break;
const witness = segmentWitness(segment);
if (witness === undefined) return undefined;
out.push(witness);
}
return out;
}
/** Raw segments of a request both patterns match from position `from` on, or `undefined` if none exists. */
function overlapFrom(a: CompiledPattern, b: CompiledPattern, from: number): string[] | undefined {
const out: string[] = [];
for (let m = from; ; m++) {
const x = a.segments[m];
const y = b.segments[m];
// A catch-all takes zero or more segments, so it absorbs whatever the other side still needs.
if (x?.kind === 'catchAll') return concat(out, restWitness(b.segments, m));
if (y?.kind === 'catchAll') return concat(out, restWitness(a.segments, m));
if (!x || !y) return x || y ? undefined : out;
const witness = overlapWitness(x, y);
if (witness === undefined) return undefined;
out.push(witness);
}
}
const concat = (head: string[], tail: string[] | undefined): string[] | undefined => tail && [...head, ...tail];
/** Whether every segment `lower` accepts, `higher` accepts too. Two different constraints are not compared. */
function segmentIncluded(lower: CompiledSegment, higher: CompiledSegment): boolean {
if (higher.kind === 'static') return lower.kind === 'static' && lower.value === higher.value;
if (higher.kind === 'catchAll' || lower.kind === 'catchAll') return false;
if (!higher.constraintSource) return true;
if (lower.kind === 'static') {
const decoded = decodedStatic(lower.value);
return decoded === undefined || higher.constraint!.test(decoded);
}
return lower.constraintSource === higher.constraintSource || acceptsEverySegment(blocksOf(higher));
}
/** Whether `higher` matches every request `lower` matches, from position `from` on. */
function includedFrom(lower: CompiledPattern, higher: CompiledPattern, from: number): boolean {
for (let m = from; ; m++) {
const l = lower.segments[m];
const h = higher.segments[m];
if (h?.kind === 'catchAll') return true;
if (!l || !h) return !l && !h;
if (!segmentIncluded(l, h)) return false;
}
}
/** The position of the first segment whose shape differs — the radix node where the two routes branch. */
function branchPoint(a: CompiledPattern, b: CompiledPattern): number {
const length = Math.max(a.segments.length, b.segments.length);
for (let k = 0; k < length; k++) {
const x = a.segments[k];
const y = b.segments[k];
if (!x || !y || shapeOf(x) !== shapeOf(y)) return k;
}
return -1;
}
/**
* Whether `first` beats `second` on a request both match, given that they branch at a constrained
* param against a plain one. `firstConstrained` says which side holds the constraint.
*
* Under `specificity` this is the router's own ranking: an exact route beats a catch-all route
* outright, and otherwise the constrained param beats the plain one at the branch, since every
* segment before it has the same kind. Under `registration` the earlier declaration wins.
*/
function winsBranch(
first: CompiledPattern,
second: CompiledPattern,
firstConstrained: boolean,
precedence: Precedence,
) {
if (precedence === 'registration') return true;
if (first.catchAll !== second.catchAll) return !first.catchAll;
return firstConstrained;
}
function shapeOf(segment: CompiledSegment): string {
if (segment.kind === 'static') return `s:${segment.value}`;
if (segment.kind === 'catchAll') return 'c';
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
}
/**
* Whether two routes of the same method, in the same table, conflict. `first` was declared before
* `second`.
*
* **Siblings.** Two routes are siblings at position `k` when their segments before `k` have the same
* shape — they share a node of the radix tree — and both segments at `k` are params, at least one of
* them constrained. Statics and catch-alls are not sibling params: a static wins on the raw segment
* (a constrained twin is still reachable through a percent-encoded spelling), and a catch-all ranks
* below every exact route. Equal shapes everywhere is the duplicate-shape error, checked elsewhere.
*
* **Ambiguous** (both constrained): the two constraints accept a common segment, *and* the full
* patterns can match one request — every later position pair overlaps, a catch-all absorbing the
* rest. `/u/:id(\d+)/a` and `/u/:n(\d{1,3})/b` share digits at the branch but no request, so they do
* not conflict. The witness is the common segment at the branch, plus a whole request path.
*
* **Unreachable** (one constrained, one plain): the route that loses the branch can never be chosen
* when the winner also matches everything it matches. The winner is the constrained one under
* `specificity`, which then needs a constraint that accepts every segment; under `registration` it is
* whichever was declared first. (An exact route beats a catch-all one under `specificity` whatever
* the branch holds, and no exact route can include a catch-all.) Later positions must be included
* segment by segment. Inclusion
* between two *different* constraints at a later position is not attempted — it is not known to be
* polynomial for this grammar — and counts as not included, so such a route boots.
*/
export function routeConflict(
first: CompiledPattern,
second: CompiledPattern,
precedence: Precedence,
): RouteConflict | undefined {
const k = branchPoint(first, second);
const x = first.segments[k];
const y = second.segments[k];
if (k < 0 || x?.kind !== 'param' || y?.kind !== 'param') return undefined;
if (!x.constraintSource && !y.constraintSource) return undefined;
const prefix = restWitness(first.segments.slice(0, k), 0);
if (!prefix) return undefined;
if (x.constraintSource && y.constraintSource) {
const segment = intersectionWitness(blocksOf(x), blocksOf(y));
const rest = segment === undefined ? undefined : overlapFrom(first, second, k + 1);
if (segment === undefined || !rest) return undefined;
return { kind: 'ambiguous', segment, path: `/${[...prefix, encodeURIComponent(segment), ...rest].join('/')}` };
}
const firstWins = winsBranch(first, second, Boolean(x.constraintSource), precedence);
const [winner, loser] = firstWins ? [first, second] : [second, first];
const winnerParam = firstWins ? x : y;
if (winnerParam.constraintSource && !acceptsEverySegment(blocksOf(winnerParam))) return undefined;
return includedFrom(loser, winner, k + 1) ? { kind: 'unreachable', loser: firstWins ? 1 : 0 } : undefined;
}
+371 -55
View File
@@ -33,13 +33,21 @@ interface ConstraintToken {
separator: boolean;
}
/**
* One atom of the safe constraint subset, and the quantifier that may follow it. Shared with
* `route-conflicts.ts`, which reads accepted constraints back as (character set, min, max) blocks, so
* the two cannot disagree about what an atom is.
*/
export const CONSTRAINT_ATOM = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u;
export const CONSTRAINT_QUANTIFIER = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u;
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
function readConstraintToken(source: string): ConstraintToken | undefined {
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
const atom = CONSTRAINT_ATOM.exec(source)?.[0];
if (!atom) return undefined;
const rest = source.slice(atom.length);
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
const quantifier = CONSTRAINT_QUANTIFIER.exec(rest)?.[0] ?? '';
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
return {
@@ -139,8 +147,19 @@ function segmentShape(segment: CompiledSegment): string {
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
}
/**
* Calls into the compile and index-build seams. `compilePattern` is called inside this module, where a
* spy on the export cannot see it, so the counts are kept here; they let a test prove that misses
* after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
*/
const seamCounts = { compilePattern: 0, indexBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */
export function compilePattern(pattern: string): CompiledPattern {
seamCounts.compilePattern++;
const cached = compiledCache.get(pattern);
if (cached) return cached;
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
@@ -325,65 +344,354 @@ function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
return 0;
}
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
interface IndexedRoute {
/**
* One route at a terminal of the index.
*
* `rank` is the route's place in its method's specificity order — exactly the order the linear
* matcher sorted its bucket into: `moreSpecific` first, declaration order on ties. Lower wins. The
* tree only decides which routes *can* match; this number alone decides which one *does*, so the
* shape of the tree can never override the global ranking (two overlapping constraints, a catch-all
* at one depth against a param at another, an equal-rank tie).
*/
interface Terminal {
def: RouteDef;
compiled: CompiledPattern;
rank: number;
/** Position in the route array the index was built from. Breaks a tie between the two trees. */
order: number;
/** Every segment static: the route has no params to collect. */
allStatic: boolean;
}
/** A `:param` edge. Plain params share one edge; constrained ones share an edge per constraint source. */
interface ParamEdge {
constraintSource: string | undefined;
constraint: RegExp | undefined;
node: RadixNode;
}
// ponytail: a segment trie — one edge per whole path segment, no compression of single-child static
// chains. Lookup cost already follows path depth, not route count; compressing would save a few map
// hops on long static prefixes and costs a split/merge routine nobody has measured a need for.
interface RadixNode {
statics: Map<string, RadixNode>;
params: ParamEdge[];
/** Routes whose last segment ends at this node, by rank. */
exact: Terminal[];
/** Catch-all routes whose fixed prefix ends at this node, by rank. They match zero or more segments. */
catchAll: Terminal[];
/** Lowest rank anywhere below this node: a branch that cannot beat the best match so far is skipped. */
min: number;
}
/** One method's routes: the tree, plus its all-static routes by exact path. */
interface MethodTree {
root: RadixNode;
/**
* All-static routes keyed by their normalized pattern, by rank. A hit here is the tree's best
* match for that path: any other non-catch-all route matching it has as many segments, none of
* them more specific than static, and every catch-all ranks below every exact route. So a static
* request is answered without splitting the path. A miss proves nothing and falls through to the
* walk, as does a path spelled differently from its pattern (`/a/`, `/a//b` on a direct call).
*/
exactPaths: Map<string, Terminal[]>;
}
/**
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
* they were built from.
* The lookup index for one route array: a tree per HTTP method, local and remote kept apart.
*
* Mesh-spliced remote routes get their own trees so they can later be rebuilt alone when peers come
* and go. Precedence stays the single list's: both trees answer, the more specific match wins, and
* a tie goes to the earlier declaration — a local one, since local routes come first.
*/
interface RouteIndex {
/** Length of the array at build time; a cached index for an array that has since grown or shrunk is rebuilt. */
size: number;
local: Map<string, MethodTree>;
/** Absent for an app without mesh routes, which then does a single lookup. */
remote: Map<string, MethodTree> | undefined;
/** Every method with at least one route, in either tree. */
methods: string[];
}
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
const remoteRouteDefs = new WeakSet<RouteDef>();
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def);
return def;
}
/**
* Route indexes 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.
* table it describes. Both callers (`buildAppFetch` and `listen()`) assemble that array after boot,
* from local, remote and dev routes, and never touch it again. A table assembled fresh is a
* different array and gets its own index.
*/
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
const routeIndexCache = new WeakMap<RouteDef[], RouteIndex>();
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
const cached = routeIndexCache.get(routes);
if (cached) return cached;
function newNode(): RadixNode {
return { statics: new Map(), params: [], exact: [], catchAll: [], min: Infinity };
}
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]);
function childFor(node: RadixNode, segment: Exclude<CompiledSegment, { kind: 'catchAll' }>): RadixNode {
if (segment.kind === 'static') {
let next = node.statics.get(segment.value);
if (!next) node.statics.set(segment.value, (next = newNode()));
return next;
}
// 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));
let edge = node.params.find((candidate) => candidate.constraintSource === segment.constraintSource);
routeIndexCache.set(routes, byMethod);
return byMethod;
if (!edge) {
edge = { constraintSource: segment.constraintSource, constraint: segment.constraint, node: newNode() };
node.params.push(edge);
}
return edge.node;
}
/** Files one terminal. Insertion runs in rank order, so every list stays sorted and `min` is set once. */
function insert(tree: MethodTree, terminal: Terminal): void {
let node = tree.root;
if (node.min === Infinity) node.min = terminal.rank;
for (const segment of terminal.compiled.segments) {
if (segment.kind === 'catchAll') {
node.catchAll.push(terminal);
return;
}
node = childFor(node, segment);
if (node.min === Infinity) node.min = terminal.rank;
}
node.exact.push(terminal);
if (terminal.allStatic) {
const key = terminal.compiled.normalized;
const same = tree.exactPaths.get(key);
if (same) same.push(terminal);
else tree.exactPaths.set(key, [terminal]);
}
}
/** Builds one tree per method from `(route, array position)` pairs, ranked as the linear matcher sorted them. */
function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
const byMethod = new Map<string, Terminal[]>();
for (const { def, order } of entries) {
const compiled = compilePattern(def.pattern);
const allStatic = compiled.segments.every((segment) => segment.kind === 'static');
const terminal: Terminal = { def, compiled, rank: 0, order, allStatic };
const bucket = byMethod.get(def.method);
if (bucket) bucket.push(terminal);
else byMethod.set(def.method, [terminal]);
}
const trees = new Map<string, MethodTree>();
for (const [method, bucket] of byMethod) {
// `sort` is stable, so equal patterns keep registration order.
bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
const tree: MethodTree = { root: newNode(), exactPaths: new Map() };
bucket.forEach((terminal, rank) => insert(tree, Object.assign(terminal, { rank })));
trees.set(method, tree);
}
return trees;
}
function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached;
seamCounts.indexBuilds++;
const local: Array<{ def: RouteDef; order: number }> = [];
const remote: Array<{ def: RouteDef; order: number }> = [];
routes.forEach((def, order) => (remoteRouteDefs.has(def) ? remote : local).push({ def, order }));
const index: RouteIndex = {
size: routes.length,
local: buildTrees(local),
remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))],
};
routeIndexCache.set(routes, index);
return index;
}
/**
* One request's lookup state, shared by every tree it searches: the path, its segments (split only
* if a walk needs them), decoded values memoized by position, and the current search's filter and
* best terminal. One object per call rather than one per tree keeps the small-table cost down.
*/
interface Search {
path: string;
segs: string[] | undefined;
decoded: Array<string | undefined>;
accept: ((def: RouteDef) => boolean) | undefined;
best: Terminal | undefined;
}
/** Placeholder until a walk splits the path; nothing reads or writes it before then. */
const NO_DECODED: Array<string | undefined> = [];
function newSearch(path: string): Search {
return { path, segs: undefined, decoded: NO_DECODED, accept: undefined, best: undefined };
}
function segmentsOf(search: Search): string[] {
if (search.segs) return search.segs;
const segs = splitPath(search.path);
search.segs = segs;
search.decoded = new Array(segs.length);
return segs;
}
/** Takes the best-ranked acceptable terminal of a rank-ordered list, if it beats the best so far. */
function offer(search: Search, terminals: Terminal[]): void {
for (let i = 0; i < terminals.length; i++) {
const terminal = terminals[i];
if (search.best && terminal.rank >= search.best.rank) return;
if (search.accept && !search.accept(terminal.def)) continue;
search.best = terminal;
return;
}
}
/**
* Pending walk frames, shared by every lookup. A frame is a node and its depth; `POST` marks the
* frame that offers a node's catch-alls once its children are done. The walk is synchronous and
* calls no user code, and each call pops only what it pushed, so sharing is safe.
*/
const stackNodes: RadixNode[] = [];
const stackDepths: number[] = [];
const POST = -1;
/** @internal Pending frames left on the shared walk stack; zero between lookups. For tests. */
export const walkStackSize = (): number => stackNodes.length;
/**
* Depth-first walk with backtracking: a static branch that dead-ends deeper falls back to its param,
* constrained and catch-all siblings. Params are decoded after splitting, so `%2F` stays inside one
* segment. Every branch that could still hold a better rank is visited; `min` prunes the rest.
*
* It runs on an explicit stack, not recursion, so a deep path that the linear matcher accepts cannot
* overflow the call stack. Frames pop in the order the recursive walk visited them: static child,
* then params in insertion order, then the node's catch-alls.
*
* The indexed loops and the empty-collection guards are measured, not style: at 10 routes the old
* linear scan is a handful of string compares, and these keep the walk within D4 of it (FPRD-001).
*/
function walk(root: RadixNode, search: Search, segs: string[]): void {
const base = stackNodes.length;
stackNodes.push(root);
stackDepths.push(0);
try {
while (stackNodes.length > base) {
const node = stackNodes.pop()!;
const depth = stackDepths.pop()!;
if (depth === POST) {
offer(search, node.catchAll);
continue;
}
if (search.best && node.min >= search.best.rank) continue;
if (node.catchAll.length) {
stackNodes.push(node);
stackDepths.push(POST);
}
if (depth === segs.length) {
if (node.exact.length) offer(search, node.exact);
continue;
}
const segment = segs[depth];
const params = node.params;
for (let i = params.length - 1; i >= 0; i--) {
const edge = params[i];
const value = (search.decoded[depth] ??= decodeSegment(segment));
if (edge.constraint && !edge.constraint.test(value)) continue;
stackNodes.push(edge.node);
stackDepths.push(depth + 1);
}
const next = node.statics.size ? node.statics.get(segment) : undefined;
if (next) {
stackNodes.push(next);
stackDepths.push(depth + 1);
}
}
} catch (error) {
// A malformed `%` escape throws out of `decodeSegment` with frames still pending; drop them.
// Not in a `finally`: a normal walk already ends at `base`, and writing `length` on every lookup
// drops the arrays' storage, which cost D4 at 10 routes (FPRD-001 CARD-10).
stackNodes.length = base;
stackDepths.length = base;
throw error;
}
}
function searchTree(
tree: MethodTree | undefined,
search: Search,
accept: ((def: RouteDef) => boolean) | undefined,
): Terminal | undefined {
if (!tree) return undefined;
search.accept = accept;
search.best = undefined;
const exact = tree.exactPaths.get(search.path);
if (exact) offer(search, exact);
if (!search.best) walk(tree.root, search, segmentsOf(search));
return search.best;
}
/** Looks a method up in both trees. The more specific match wins; an equal one goes to the earlier declaration. */
function findRoute(
index: RouteIndex,
method: string,
search: Search,
accept?: (def: RouteDef) => boolean,
): Terminal | undefined {
const local = searchTree(index.local.get(method), search, accept);
if (!index.remote) return local;
const remote = searchTree(index.remote.get(method), search, accept);
if (!local || !remote) return local ?? remote;
const order = moreSpecific(local.compiled, remote.compiled);
if (order !== 0) return order > 0 ? local : remote;
return local.order < remote.order ? local : remote;
}
/** Collects the winning route's own param names and values. The walk already proved it matches. */
function paramsOf(terminal: Terminal, search: Search): Record<string, string> {
return terminal.allStatic ? {} : matchCompiled(terminal.compiled, segmentsOf(search), search.decoded)!;
}
const isBuffered = (def: RouteDef): boolean => def.transport === 'buffer';
/**
* 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.
* The ranking is settled when the index is built, not per request. What is left here is a walk down
* the method's tree that visits only the branches the path can follow.
*/
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 decoded: Array<string | undefined> = new Array(pathSegs.length);
for (const { def, compiled } of candidates) {
const params = matchCompiled(compiled, pathSegs, decoded);
if (params) return { params, def };
}
return undefined;
const search = newSearch(path);
const hit = findRoute(routeIndex(routes), method, search);
return hit && { params: paramsOf(hit, search), def: hit.def };
}
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
@@ -392,29 +700,37 @@ export interface ResolvedRoute extends MatchedRoute {
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
const explicit = matchRoute(routes, method, path);
if (explicit) return { ...explicit, implicitHead: false };
const index = routeIndex(routes);
const search = newSearch(path);
const explicit = findRoute(index, method, search);
if (explicit) return { params: paramsOf(explicit, search), def: explicit.def, implicitHead: false };
if (method !== 'HEAD') return undefined;
const fallback = matchRoute(
routes.filter((route) => route.transport === 'buffer'),
'GET',
path,
);
return fallback ? { ...fallback, implicitHead: true } : undefined;
// Only a buffered GET can answer HEAD. The filter applies inside the ranking, so a higher-ranked
// streaming GET is passed over for a lower-ranked buffered one rather than ending the search.
const fallback = findRoute(index, 'GET', search, isBuffered);
return fallback ? { params: paramsOf(fallback, search), def: fallback.def, implicitHead: true } : undefined;
}
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
/**
* Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header.
*
* One lookup per registered method over the union of both trees. Nothing is recompiled or rescanned
* on a miss.
*/
export function allowedMethods(routes: RouteDef[], path: string): string[] {
const pathSegs = splitPath(path);
const index = routeIndex(routes);
const search = newSearch(path);
const methods = new Set<string>();
for (const route of routes) {
if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
methods.add(route.method);
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
for (const method of index.methods) {
// A buffered GET answers both GET and HEAD, so it is looked for first; only a GET path served
// by streaming routes alone needs the second lookup.
if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD');
else if (findRoute(index, method, search)) methods.add(method);
}
if (methods.size) methods.add('OPTIONS');
+43 -3
View File
@@ -18,6 +18,7 @@ import {
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
interface HandlerConfig {
@@ -78,7 +79,7 @@ export function createHttpServer(
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits);
return server;
}
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
// `http.createServer` ignores the promise a listener returns, so a rejection that escapes `serve`
// would be an `unhandledRejection` — and under Node's default mode, the end of the process.
// Caught here, at the one place every request passes through (#108).
return (req: http.IncomingMessage, res: http.ServerResponse): void => {
serve(req, res).catch((err: unknown) => failSafe(res, err, opts?.logger));
};
async function serve(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
// Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy);
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body);
};
}
}
/**
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
* runs because something already failed past the point where errors convert to a response, and user
* code that may be the thing failing is the wrong place to send it. Must never throw — nothing
* catches it.
*
* Writable: a fixed 500 with `connection: close`, still through the patched `writeHead`, so the
* security headers land. Output already started, or the client gone: there is no honest response
* left to send, so the socket is destroyed and the client sees a truncated reply rather than a
* complete-looking one. No `request:end` is emitted — observers do not alter the response, and the
* core never completed this request.
*/
function failSafe(res: http.ServerResponse, err: unknown, logger: Logger | undefined): void {
try {
logger?.error('request listener failed', { err: err instanceof Error ? err.message : String(err) });
} catch {
/* a broken logger must not stop the response below */
}
if (res.headersSent || res.destroyed || !res.writable) {
res.destroy();
return;
}
try {
res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
res.end('{"error":"Internal Server Error"}');
} catch {
res.destroy();
}
}
/**
+31
View File
@@ -16,6 +16,31 @@ export interface RequestLimits {
headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000
maxParts?: number; // default 1000
/**
* Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default
* `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`);
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
*
* Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's
* `maxPayloadLength`). Before Bun 1.4, Bun then drops the connection without a close frame, so
* the peer sees `1006` instead of `1009`; Bun 1.4 and later send `1009`. Deno and the edge offer no such option: there the runtime
* receives the whole message first, so its memory is bounded by the platform's own cap, and this
* limit is checked after receipt — the connection still closes `1009`.
*
* Server-level only; there is no per-route override.
*/
maxWsMessageBytes?: number;
/**
* Inbound WebSocket messages a connection may hold that the handler has not read yet. Default
* `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping
* anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages.
* Must be a positive integer, or `createApp` throws. Applies on every runtime.
*
* Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`:
* ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at
* the platform or proxy there. Server-level only; there is no per-route override.
*/
maxWsQueue?: number;
}
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
@@ -89,6 +114,12 @@ export interface WsRouteDef {
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
export interface MeshControl {
path: string;
/**
* Inbound bound for this channel's socket, in bytes, used in place of
* `limits.maxWsMessageBytes` when larger (#120): an RPC carries a whole request body, which
* `maxBodyBytes` bounds, not the WebSocket message limit.
*/
maxFrameBytes?: number;
/**
* Serves one control connection over the neutral socket — the same capability every other ws
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
+66 -18
View File
@@ -11,7 +11,8 @@ import {
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { peerOf } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
@@ -97,9 +98,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
/**
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
*
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
* or not at all, so the limit can only be checked once the bytes are already in memory. That
* difference is exactly why the limit is passed in rather than applied by the shared core.
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* the whole body or not at all and so could only check the limit once every byte was in memory.
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
*/
function readFetchBytes(
source: unknown,
@@ -110,8 +111,54 @@ function readFetchBytes(
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => {
if (arrayBuffer.byteLength > limit) {
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
// effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
request.body.cancel().catch(() => {});
return tooLarge(request, opts);
}
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
return readBounded(request.body.getReader(), limit).then((bytes) =>
bytes === null ? tooLarge(request, opts) : { bytes },
);
}
/**
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
* propagates exactly as a rejected `arrayBuffer()` used to.
*
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
* The answer is the same 413 either way; only how early it comes differs.
*/
async function readBounded(
reader: ReadableStreamDefaultReader<Uint8Array>,
limit: number,
): Promise<Buffer | undefined | null> {
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
reader.cancel().catch(() => {});
return null;
}
chunks.push(value);
}
return total === 0 ? undefined : Buffer.concat(chunks, total);
}
/** The over-limit answer, shared by the declared-length check and the stream count. */
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
@@ -121,10 +168,6 @@ function readFetchBytes(
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
}
/**
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
return new Response(body, { status: result.outcome.status, headers });
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim();
}
/**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
@@ -244,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// `app.fetch` has none, so there the answer is still ''.
ip: forwardedFor(headers, opts) || peerOf(request),
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
+54 -7
View File
@@ -1,6 +1,6 @@
import { channel } from '../channel';
import { channel, type Channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
import { WS_HIGH_WATER_MARK, type WsRequest, type WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
/**
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
*/
const decoder = new TextDecoder();
const CONNECTING = 0; // WebSocket.CONNECTING
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
@@ -39,6 +40,8 @@ export function toWsRequest(request: Request, ip: string): WsRequest {
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
export interface EventfulSocket {
readonly readyState: number;
/** Bytes queued by `send` and not yet written. Deno reports it; a host without it is never waited on. */
readonly bufferedAmount?: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener(
@@ -69,7 +72,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
ac.abort();
});
return neutralSocket(host, inbound, ac);
const socket = neutralSocket(host, inbound, ac);
const closeNow = socket.close;
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
// Deferring to 'open' is what lets that close reach the client at all.
return Object.assign(socket, {
close: (code?: number, reason?: string) => {
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
else closeNow(code, reason);
},
});
}
/**
@@ -78,8 +92,8 @@ export function eventSocket(host: EventfulSocket): WsSocket {
* callers never have to guard an already-closed socket.
*/
export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>,
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
inbound: Channel<unknown>,
ac: AbortController,
): WsSocket {
return {
@@ -91,6 +105,7 @@ export function neutralSocket(
send: (data) => {
host.send(data);
},
drained: () => pollDrained(host, ac.signal),
close: (code, reason) => {
try {
host.close(code, reason);
@@ -108,12 +123,44 @@ export function neutralSocket(
};
}
/** How often {@link pollDrained} rereads `bufferedAmount` while a socket is backed up. */
const DRAIN_POLL_MS = 10;
/**
* {@link WsSocket.drained} for a host that reports `bufferedAmount` but fires no drain event —
* the Web `WebSocket` API has none. Polls only while the socket is over the mark, so a socket that
* keeps up never starts a timer; the close (`signal`) ends the wait at once.
*
* A socket still CONNECTING is not writable either, and waits too. Deno hands its socket over in
* that state, and a route that yielded at once had its first frame pulled, found the socket not
* open, and the pump gave up on the connection.
*/
async function pollDrained(host: Pick<EventfulSocket, 'readyState' | 'bufferedAmount'>, signal: AbortSignal) {
const backedUp = () =>
host.readyState === CONNECTING || (host.readyState === OPEN && (host.bufferedAmount ?? 0) > WS_HIGH_WATER_MARK);
while (!signal.aborted && backedUp()) {
await new Promise<void>((resolve) => {
const done = () => {
clearTimeout(timer);
signal.removeEventListener('abort', done);
resolve();
};
const timer = setTimeout(done, DRAIN_POLL_MS);
signal.addEventListener('abort', done, { once: true });
});
}
}
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
export type SocketCtor = new (url: string) => EventfulSocket;
/**
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
* The WebSocket client implementation: the platform global where it exists, else the `ws`
* optional peer. Every supported runtime has the global — Deno, Bun, and Node from 22, the
* declared floor — so the fallback is reached only when Node runs with the global switched off
* (`--no-experimental-websocket`). `ws` is installed anyway for the server side.
*
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
+307 -2
View File
@@ -1,8 +1,9 @@
import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
import type { WsRouteDef, RequestLimits } from './types';
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
export interface WsRequest {
@@ -20,6 +21,301 @@ export interface WsSocket {
send(data: string): void;
close(code?: number, reason?: string): void;
terminate(): void;
/**
* Resolves once the socket's send buffer is at or below the adapter's high-water mark, or the
* socket has closed — at once when it already is (#41). The outbound pump awaits it before
* pulling the next value, so a fast producer cannot grow the buffer without limit.
*
* Optional: a socket without it is never waited on, which is how every socket behaved before.
* The mark is the adapter's; {@link WS_HIGH_WATER_MARK} is what the built-in adapters use.
*/
drained?(): Promise<void>;
}
/**
* Send-buffer level, in bytes, above which the built-in adapters report a socket as backed up
* (#41). Internal, not an option: it bounds what one slow peer can make the process hold, and
* a frame is sent whole, so the buffer peaks at this plus one frame.
*/
export const WS_HIGH_WATER_MARK = 1_048_576;
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
export const DEFAULT_MAX_WS_QUEUE = 16;
/**
* Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as
* Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part
* of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this
* module, and only the global registry resolves to one symbol across them.
*/
export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes');
/** The effective `limits.maxWsMessageBytes`. */
export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'> | undefined): number {
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
}
/**
* Undelivered inbound frames the mesh control channel may hold once its peer is authenticated
* (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never
* awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of
* one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control
* frame (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
* 16-frame user default closed with 1013.
*/
const CONTROL_QUEUE = 4096;
/**
* Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello
* is a version and a secret; nothing larger has a reason to arrive first.
*/
export const HELLO_FRAME_BYTES = 65_536;
/** Inbound bounds for one socket, as {@link boundInbound} takes them. */
type InboundLimits = { maxWsMessageBytes: number; maxWsQueue: number };
/**
* The bounds of the mesh control channel's socket, in two phases.
*
* - `preAuth`, until the peer's `hello` is accepted: hello-sized frames and the default 16-frame
* queue, so an unauthenticated peer can make the process hold about 1 MiB at most — including
* while `app.upgrade` waits for a slow boot, before anything reads the queue.
* - `authed`, after: `maxWsMessageBytes` raised to the channel's frame bound (#120) and `maxWsQueue`
* to {@link CONTROL_QUEUE} (#148), each only when larger. The peer holds the mesh secret by then.
*
* A user route never goes through this, so it keeps both limits as configured.
*/
export function controlBounds(
limits: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
maxFrameBytes: number | undefined,
): { preAuth: InboundLimits; authed: InboundLimits } {
return {
preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE },
authed: {
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE),
},
};
}
/** Where a socket bounded with a second phase keeps the switch to it; `Symbol.for`, as above. */
const WIDEN_INBOUND: unique symbol = Symbol.for('green-tea.widen-inbound');
/**
* Switches a socket from {@link boundInbound}'s first bounds to the `widened` ones it was given —
* for the mesh control channel, once the peer has authenticated. A no-op on any other socket.
* Frames already queued stay; the new bounds apply to the frames that arrive next.
*/
export function widenInbound(socket: WsSocket): void {
(socket as { [WIDEN_INBOUND]?: () => void })[WIDEN_INBOUND]?.();
}
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
export function validateWsLimits(limits: RequestLimits | undefined): void {
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
const value: unknown = limits?.[key];
if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue;
const shown = typeof value === 'string' ? `'${value}'` : String(value);
throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`);
}
}
const encoder = new TextEncoder();
/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */
function exceedsBytes(msg: unknown, max: number): boolean {
if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure
// A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in
// between pays for the encode — which is never one of the short messages that dominate.
if (msg.length * 3 <= max) return false;
if (msg.length > max) return true;
return encoder.encode(msg).byteLength > max;
}
/**
* Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a
* frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is
* dropped silently — the peer learns which bound it hit from the close code.
*
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
* subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first
* frames — for the mesh control channel, the `hello` itself. Those early frames go to the first
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
* Every other capability is the original socket's.
*
* `widened`, when given, is a second set of bounds that {@link widenInbound} switches to later: the
* mesh control channel starts at hello size and widens once its peer authenticates.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
widened?: InboundLimits,
): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
const tap = (socket.inbound as Partial<TappableChannel<unknown>>)[CHANNEL_TAP];
if (tap) fanout.tap(tap);
else void fanout.pump();
return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
}) as WsSocket;
}
/** The fan-out behind {@link boundInbound}: one bounded queue per consumer. */
class InboundFanout {
private readonly subs = new Set<InboundSub>();
/** Holds the frames that arrive before anyone reads; handed to the first consumer. */
private first: InboundSub | null;
private ended = false;
private failure: { err: unknown } | null = null;
constructor(
private readonly socket: WsSocket,
private maxBytes: number,
private maxQueue: number,
) {
this.first = this.add();
}
/** Applies the second phase's bounds; see {@link widenInbound}. */
widen(limits: InboundLimits): void {
this.maxBytes = limits.maxWsMessageBytes;
this.maxQueue = limits.maxWsQueue;
}
/**
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
* unbounded queue has already taken the burst. Here each frame is bounded before it is queued.
*/
tap(tap: TappableChannel<unknown>[typeof CHANNEL_TAP]): void {
const untap = tap({
push: (msg) => {
if (this.ended || this.accept(msg)) return;
untap();
this.settle();
},
end: () => this.settle(),
fail: (err) => this.settle({ err }),
});
}
// ponytail: only for an inbound that is not a channel (no adapter builds one); bounds late.
async pump(): Promise<void> {
try {
for await (const msg of this.socket.inbound) {
if (this.ended || !this.accept(msg)) break;
}
this.settle();
} catch (err) {
this.settle({ err });
}
}
subscribe(): AsyncIterator<unknown> {
const sub = this.first ?? this.add();
this.first = null;
return sub;
}
private add(): InboundSub {
const sub = new InboundSub(() => this.subs.delete(sub));
if (this.ended) sub.settle(this.failure ?? undefined);
else this.subs.add(sub);
return sub;
}
/** Delivers or queues one frame for every consumer; returns false once it has closed the socket. */
private accept(msg: unknown): boolean {
if (exceedsBytes(msg, this.maxBytes)) {
this.socket.close(1009, 'message too large');
return false;
}
// Capacity first, for every consumer: a frame that overflows one queue reaches none, so a
// rejected frame cannot run some handlers' side effects and not others'.
for (const sub of this.subs) {
if (sub.full(this.maxQueue)) {
this.socket.close(1013, 'inbound queue full');
return false;
}
}
for (const sub of this.subs) sub.offer(msg);
return true;
}
/** Ends every consumer once, cleanly or with a failure; whatever is still queued is delivered first. */
private settle(failure?: { err: unknown }): void {
if (this.ended) return;
this.ended = true;
this.failure = failure ?? null;
for (const sub of this.subs) sub.settle(failure);
this.subs.clear();
}
}
/** One consumer's queue; it is its own async iterator. */
class InboundSub implements AsyncIterator<unknown> {
private readonly queue: unknown[] = [];
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
private ended = false;
private failure: { err: unknown } | null = null;
constructor(private readonly onReturn: () => void) {}
/** True when `max` frames are already waiting and no `next()` is there to take another. */
full(max: number): boolean {
return !this.waiter && this.queue.length >= max;
}
/** Hands `msg` to a waiting `next()` or queues it; callers check {@link full} first. */
offer(msg: unknown): void {
const waiter = this.waiter;
if (waiter) {
this.waiter = null;
waiter.resolve({ value: msg, done: false });
return;
}
this.queue.push(msg);
}
next(): Promise<IteratorResult<unknown>> {
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
if (this.failure) return Promise.reject(this.failure.err);
if (this.ended) return Promise.resolve({ value: undefined, done: true });
return new Promise((resolve, reject) => {
this.waiter = { resolve, reject };
});
}
// A consumer that stops reading has said it wants no more; queueing for it would only close
// the connection for a bound it no longer cares about. Other consumers keep receiving.
return(): Promise<IteratorResult<unknown>> {
this.queue.length = 0;
this.onReturn();
this.settle();
return Promise.resolve({ value: undefined, done: true });
}
settle(failure?: { err: unknown }): void {
if (this.ended) return;
this.ended = true;
this.failure = failure ?? null;
const waiter = this.waiter;
this.waiter = null;
if (!waiter) return;
if (failure) waiter.reject(failure.err);
else waiter.resolve({ value: undefined, done: true });
}
}
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
@@ -65,9 +361,18 @@ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer:
return { closer };
}
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
/**
* Drives the outbound async iterator, sending each yielded value until done or the socket closes.
* Waits for {@link WsSocket.drained} before each pull (#41): a value pulled while the peer is
* backed up has nowhere to go but the send buffer, so it is not pulled until there is room.
*/
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
while (true) {
if (socket.drained) await socket.drained();
// Closed while waiting: stop before pulling a value nobody can receive. The abort listener in
// `runWsConnection` has already called the iterator's `return()`. `abort`, not `isOpen`: Deno
// hands a socket over still CONNECTING, which is not open yet and not closed either.
if (socket.abort.aborted) break;
const { value, done } = await iterator.next();
if (done) break;
if (!socket.isOpen) break;
+94 -15
View File
@@ -1,8 +1,19 @@
import type http from 'http';
import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
import {
runWsConnection,
matchWsRoute,
trackUntil,
boundInbound,
controlBounds,
wsMessageBytes,
WS_HIGH_WATER_MARK,
type WsSocket,
type WsRequest,
} from './ws-core';
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
import { normalizeRequestPath } from './router';
import { nodeRequire } from '../node-require';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
@@ -16,9 +27,9 @@ function loadWss(): any | null {
}
}
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
function reject501(socket: any): void {
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
function rejectUpgrade(socket: any, status: number, text: string): void {
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
socket.destroy();
}
@@ -31,21 +42,27 @@ function handleMeshUpgrade(
socket: any,
head: Buffer,
streams?: Set<() => void>,
limits?: RequestLimits,
): boolean {
if (path !== meshControl.path) return false;
if (!wss) {
reject501(socket);
rejectUpgrade(socket, 501, 'Not Implemented');
return true;
}
// An RPC carries a whole request body, so once the peer authenticates the channel is bounded by
// the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size.
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
// serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws);
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
@@ -66,10 +83,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
function nodeSocket(ws: any): WsSocket {
const inbound = channel<unknown>();
const ac = new AbortController();
// `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send
// callback, which `ws` runs once that frame is written to the TCP socket, or by the close.
const waiters: Array<() => void> = [];
const release = () => waiters.splice(0).forEach((resolve) => resolve());
const backedUp = () => ws.readyState === 1 && ws.bufferedAmount > WS_HIGH_WATER_MARK;
const written = () => {
if (!backedUp()) release();
};
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
ws.on('close', () => {
inbound.close();
ac.abort();
release();
});
ws.on('error', (err: unknown) => inbound.fail(err));
return {
@@ -78,7 +106,8 @@ function nodeSocket(ws: any): WsSocket {
get isOpen() {
return ws.readyState === 1; // 1 = OPEN
},
send: (data) => ws.send(data),
send: (data) => ws.send(data, written),
drained: () => (backedUp() ? new Promise<void>((resolve) => waiters.push(resolve)) : Promise.resolve()),
close: (code, reason) => {
try {
ws.close(code, reason);
@@ -97,29 +126,79 @@ export function attachWs(
bus?: Bus,
meshControl?: MeshControl,
streams?: Set<() => void>,
limits?: RequestLimits,
): void {
if (wsRoutes.length === 0 && !meshControl) return;
const WebSocketServer = loadWss();
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
// `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame,
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
// check on the decoded text, which is the only half Deno and the edge have.
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
// The control channel's own server, so its larger bound (#120) never reaches a user route.
const meshWss =
WebSocketServer && meshControl
? new WebSocketServer({
noServer: true,
maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes,
})
: null;
server.on('upgrade', (req, socket, head) => {
const path = (req.url ?? '/').split('?')[0];
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
// else is listening to yet: that is as fatal as a throw.
socket.on('error', () => {});
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
// uncaught exception that takes the whole process down, not a 500 for one client.
try {
routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
} catch {
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
else socket.destroy();
}
});
}
/** What every upgrade on one server shares. */
interface UpgradeEnv {
wss: any;
/** The mesh control channel's server, bounded by its own frame limit (#120). */
meshWss: any;
wsRoutes: WsRouteDef[];
bus?: Bus;
meshControl?: MeshControl;
streams?: Set<() => void>;
limits?: RequestLimits;
}
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
const { wss, meshWss, wsRoutes, bus, meshControl, streams, limits } = env;
let path: string;
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
// escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches.
try {
path = normalizeRequestPath((req.url ?? '/').split('?')[0]);
} catch {
rejectUpgrade(socket, 400, 'Bad Request');
return;
}
if (meshControl && handleMeshUpgrade(meshWss, meshControl, path, req, socket, head, streams, limits)) return;
const route = matchWsRoute(wsRoutes, path);
if (!route) {
socket.destroy();
rejectUpgrade(socket, 404, 'Not Found');
return;
}
if (!wss) {
reject501(socket);
rejectUpgrade(socket, 501, 'Not Implemented');
return;
}
wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
});
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
});
}
+49 -14
View File
@@ -3,7 +3,7 @@
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
import crypto from 'node:crypto';
import type { Bus } from '../bus';
import type { WsSocket } from '../http/ws-core';
import { HELLO_FRAME_BYTES, widenInbound, type WsSocket } from '../http/ws-core';
import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals';
import {
@@ -29,18 +29,34 @@ export const MESH_CONTROL_PATH = '/__mesh__/control';
*/
const HANDSHAKE_TIMEOUT_MS = 10_000;
/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
/**
* Largest control frame the teapot will parse, in characters.
*
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
* documented ceiling on the platform sockets Deno and Bun provide).
*
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
* overhead of the envelope around it.
* The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text
* body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
* non-ASCII text is not escaped at all.
*/
const MAX_FRAME_CHARS = 4_000_000;
const WORST_ESCAPE = 6;
/** Room in a frame for everything but the body: headers, params, query, url and the envelope. */
const ENVELOPE_HEADROOM = 1_048_576;
/**
* Largest control frame a teapot accepts, in characters, when the largest body it may be sent is
* `maxBodyBytes` (#120): the body at its worst escaping plus {@link ENVELOPE_HEADROOM}, so any body
* within the limit fits. 7,048,576 at the 1 MB default.
*
* `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure — and
* an unauthenticated peer never gets near it: until its `hello` is accepted, the channel takes only
* hello-sized frames (`HELLO_FRAME_BYTES`, `controlBounds` in `ws-core`). Applies to the control
* channel only: user WebSocket routes keep `limits.maxWsMessageBytes`.
*/
export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number {
return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM;
}
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
@@ -61,6 +77,11 @@ export interface MeshControlDeps {
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
bus?: Bus;
/**
* The largest request body this teapot accepts, which sizes the control frames it parses
* ({@link controlFrameLimit}). Defaults to the 1 MB body default.
*/
maxBodyBytes?: number;
}
/** The rpc-req member of the {@link Frame} union. */
@@ -101,6 +122,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
return false;
}
// The peer holds the secret now: lift the hello-sized bounds its socket was given to the ones
// that carry RPC bodies (#120, #148). A socket bounded without a second phase is left as it is.
widenInbound(socket);
socket.send(
encode({
type: 'manifest',
@@ -175,6 +199,7 @@ async function serveFrames(
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
maxFrameChars: number,
): Promise<void> {
let authed = false;
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
@@ -188,8 +213,9 @@ async function serveFrames(
for await (const data of socket.inbound) {
const raw = String(data);
// Checked before `decode`, because decoding is the expensive part being defended.
if (raw.length > MAX_FRAME_CHARS) {
// Checked before `decode`, because decoding is the expensive part being defended. Until the
// handshake, nothing larger than a hello is parsed, whatever the socket in front allowed.
if (raw.length > (authed ? maxFrameChars : HELLO_FRAME_BYTES)) {
socket.close(1009, 'mesh frame too large');
break;
}
@@ -232,13 +258,22 @@ async function serveFrames(
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
export function createMeshControl(deps: MeshControlDeps): {
path: string;
maxFrameBytes: number;
handle: (socket: WsSocket) => Promise<void>;
} {
const exportedScopes = new Set(deps.manifest.steps);
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
const maxFrameChars = controlFrameLimit(deps.maxBodyBytes);
return {
path: MESH_CONTROL_PATH,
/**
* The inbound bound a server puts on this channel's WebSocket in place of
* `limits.maxWsMessageBytes` (#120). The same figure as the character check below: the two agree
* on ASCII, and on other text the byte bound is the one that binds — a body measured in bytes by
* `maxBodyBytes` stays about that many bytes inside the envelope, so it still fits.
*/
maxFrameBytes: maxFrameChars,
/**
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
* the control channel's lifetime the same way it awaits a regular ws route's.
@@ -246,7 +281,7 @@ export function createMeshControl(deps: MeshControlDeps): {
* does synchronously, so the loop is live before any frame can arrive.
*/
handle(socket: WsSocket): Promise<void> {
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars);
},
};
}
+49 -6
View File
@@ -86,9 +86,40 @@ export interface StaticHit {
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
const real = await fs.promises.realpath(path);
return real === root || real.startsWith(root + sep) ? real : undefined;
}
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
async function readConfined(
fs: typeof import('node:fs'),
nodePath: typeof import('node:path'),
root: string,
full: string,
): Promise<StaticHit | undefined> {
let real = await confine(fs, nodePath.sep, root, full);
if (!real) return undefined;
const isDir = (await fs.promises.stat(real)).isDirectory();
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
if (!real) return undefined;
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
// on every path component, which Node, Deno and Bun do not offer portably.
const body = await fs.promises.readFile(real);
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
const target = isDir ? nodePath.join(full, 'index.html') : full;
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
}
/**
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss,
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
*/
export function buildStaticResolver(root: string | true): StaticResolver {
let fs: typeof import('node:fs');
@@ -105,6 +136,18 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
// The root's real path, resolved once on the first request rather than at build time, so a missing
// `public/` at boot is still not fatal — it just makes every request a miss, as before. Containment
// compares real paths, so the root must be real too: a symlinked `public/` would otherwise fail every
// check. Cached for the life of the app: re-pointing a root symlink at runtime needs a restart. A failed
// lookup is not cached, so a root created after boot starts serving, as it did before.
let realRoot: Promise<string | undefined> | undefined;
const resolveRoot = () =>
(realRoot ??= fs.promises.realpath(abs).catch(() => {
realRoot = undefined;
return undefined;
}));
return async (urlPath) => {
let rel: string;
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
const rootReal = await resolveRoot();
if (!rootReal) return undefined;
try {
const stat = await fs.promises.stat(full);
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
const body = await fs.promises.readFile(target);
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
return await readConfined(fs, nodePath, rootReal, full);
} catch {
return undefined;
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
}
};
}
+24 -1
View File
@@ -12,7 +12,16 @@ class Rt {
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
@Route('/room')
class Room {
@Ws('/:name')
join(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt, Room] })
class M {}
const app = createApp({ modules: [M] });
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
await app.upgrade(req, socket);
expect(closedCode).toBe(1008);
});
it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])(
'closes 1008 on the malformed path %s instead of rejecting (#104)',
async (url) => {
const { socket } = fakeSocket();
let closed: [number | undefined, string | undefined] | undefined;
socket.close = (c, r) => {
closed = [c, r];
};
const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' };
await app.upgrade(req, socket);
expect(closed).toEqual([1008, 'invalid request path']);
},
);
});
+87
View File
@@ -0,0 +1,87 @@
// #105 on the real Bun runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveBun`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(source.pulled).toBe(0);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
expect(res.status).toBe(413);
expect(source.pulled).toBeLessThanOrEqual(5);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
expect(at.status).toBe(200);
expect(await at.json()).toEqual({ length: LIMIT });
expect(over.status).toBe(413);
await app.close();
});
test('T11 serveBun: the same statuses over a real socket', async () => {
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
const base = `http://127.0.0.1:${server.port}`;
// A fresh connection per request. Bun's *client* reuses a kept-alive socket after a response that
// arrived before the server read the request body, and its next request on that socket comes back
// 400 or 431. Node's fetch against the same Bun server does not (Bun 1.3.14), so it is the client
// that misbehaves, not `serveBun`.
const send = (body: BodyInit, headers?: Record<string, string>) =>
fetch(post(`${base}/small`, body, headers), { keepalive: false } as RequestInit);
try {
expect((await send(new Uint8Array(2 * SMALL))).status).toBe(413);
expect((await send(countingStream(10, 300).stream)).status).toBe(413);
expect((await send('x'.repeat(SMALL), { 'content-type': 'text/plain' })).status).toBe(200);
expect((await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' })).status).toBe(413);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+208
View File
@@ -0,0 +1,208 @@
// #120 (CARD-24, D22) on Bun: an RPC whose body is within `maxBodyBytes` reaches the teapot,
// although the control channel is a WebSocket bounded like every other. Node twin:
// test/mesh/large-body.test.ts, which explains the cases.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
const WRAP = '{"data":""}'.length;
@Route('/big')
class BigCtl {
@Post('/echo', { export: true })
echo(@body() b: { data: string } | string) {
return { length: typeof b === 'string' ? b.length : b.data.length };
}
@Ws('/sock')
sock(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${String(msg).length}`;
})();
}
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api' })
class TeacupModule {}
async function serve(app: ReturnType<typeof createApp>) {
const server = await serveBun(app, { port: 0 });
return { server, port: server.port };
}
async function pair(maxBodyBytes?: number) {
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
const t = await serve(teapot);
const url = `ws://127.0.0.1:${t.port}/__mesh__/control`;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
limits,
});
const c = await serve(teacup);
const post = (payload: string, type = 'application/json') =>
fetch(`http://127.0.0.1:${c.port}/api/big/echo`, {
method: 'POST',
headers: { 'content-type': type },
body: payload,
});
const close = async () => {
await teacup.close();
await teapot.close();
c.server.stop(true);
t.server.stop(true);
};
return { post, close, tPort: t.port, teacup };
}
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
test('mesh on Bun: a 1 MB JSON body reaches the teapot (T1)', async () => {
const { post, close } = await pair();
try {
const res = await post(json(1_000_000));
expect(res.status).toEqual(200);
expect(await res.json()).toEqual({ length: 1_000_000 - WRAP });
expect((await post(json(1_000_000))).status).toEqual(200);
} finally {
await close();
}
});
test('mesh on Bun: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
const { post, close } = await pair();
try {
const res = await post('"'.repeat(999_000), 'text/plain');
expect(res.status).toEqual(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toEqual(200);
} finally {
await close();
}
});
test('mesh on Bun: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
const res = await post('\u0001'.repeat(999_000), 'text/plain');
expect(res.status).toEqual(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toEqual(200);
} finally {
await close();
}
});
test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
const { post, close, teacup } = await pair();
try {
// Through `app.fetch`, not the socket: a client still writing a 1 MB body when Bun's 413 lands
// can stall or reset (see body-limits.test.ts). That race is the transport's, not the mesh's.
const over = new Request('http://x/api/big/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: json(1_000_001),
});
expect((await teacup.fetch(over)).status).toEqual(413);
expect((await post(json(1_000))).status).toEqual(200);
} finally {
await close();
}
});
// A teapot raises Bun's native `maxPayloadLength` to the control channel's bound, so a user route's
// oversized frame is refused by `app.upgrade` instead, with a real 1009 close frame rather than the
// 1006 drop the native bound gives (see ws.test.ts).
test('mesh on Bun: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
ws.onopen = () => ws.send('x'.repeat(1_048_577));
ws.onclose = (e) => resolve(e.code);
});
expect(code).toEqual(1009);
} finally {
await close();
}
});
test('mesh on Bun: the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
const { post, close } = await pair(4_000_000);
try {
const res = await post(json(3_900_000));
expect(res.status).toEqual(200);
expect(await res.json()).toEqual({ length: 3_900_000 - WRAP });
} finally {
await close();
}
});
test('mesh on Bun: 64 concurrent RPCs on one link all succeed (#148)', async () => {
const { post, close, teacup } = await pair();
try {
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
const rpc = () =>
teacup.fetch(
new Request('http://x/api/big/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: json(100),
}),
);
const res = await Promise.all(Array.from({ length: 64 }, rpc));
expect(res.map((r) => r.status)).toEqual(Array(64).fill(200));
expect((await post(json(1_000))).status).toEqual(200);
} finally {
await close();
}
});
test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
ws.onopen = () => {
for (let i = 0; i < 17; i++) ws.send(String(i));
};
ws.onclose = (e) => resolve(e.code);
});
expect(code).toEqual(1013);
} finally {
await close();
}
});
test('mesh on Bun: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
ws.onopen = () => ws.send('x'.repeat(1_000_000));
ws.onclose = (e) => resolve(e.code);
});
expect(code).toEqual(1009);
} finally {
await close();
}
});
+63
View File
@@ -0,0 +1,63 @@
// #116 on the real Bun runtime: `serveBun` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createServer } from 'node:net';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveBun(createApp({ modules: [M], trustProxy: opts.trustProxy }), { hostname, port: 0 });
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${server.port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
const ipv6Available = await new Promise<boolean>((resolve) => {
const probe = createServer();
probe.once('error', () => resolve(false));
probe.listen(0, '::1', () => probe.close(() => resolve(true)));
});
test('T2 serveBun: ctx.ip is the socket peer address', async () => {
expect(await ipVia('127.0.0.1')).toBe('127.0.0.1');
});
// Skipped, not failed: the host has no IPv6 loopback to connect over.
test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun reports it', async () => {
expect(await ipVia('::1')).toBe('::1');
});
test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
expect(ip).toBe('203.0.113.7');
});
test('T5 serveBun: trustProxy without x-forwarded-for falls back to the peer', async () => {
expect(await ipVia('127.0.0.1', { trustProxy: true })).toBe('127.0.0.1');
});
test('T6 serveBun: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
expect(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } })).toBe('127.0.0.1');
});
+22
View File
@@ -0,0 +1,22 @@
// The frozen router-parity differential under the real Bun runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = (name: string) => Bun.file(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)).json();
test('router parity on Bun: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
expect(report.mismatches).toEqual([]);
expect(report.sets.length).toBe(5);
});
test('router parity on Bun: app.fetch cases', async () => {
const report = await runAppDifferential(load);
expect(report.mismatches).toEqual([]);
});
+51
View File
@@ -0,0 +1,51 @@
// Static-file confinement (#106) under the real Bun runtime, which reaches `realpath` through its
// `node:fs` compat — a third implementation of symlink resolution, so not something to assume from
// the Node suite.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createApp } from '../../src/index.ts';
const base = mkdtempSync(join(tmpdir(), 'gt-static-bun-'));
const root = join(base, 'root');
mkdirSync(join(root, 'sub'), { recursive: true });
writeFileSync(join(root, 'a.txt'), 'in root');
writeFileSync(join(root, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
symlinkSync('a.txt', join(root, 'in-link'));
symlinkSync('../secret.txt', join(root, 'out-link'));
symlinkSync('../nope.txt', join(root, 'dangling'));
symlinkSync('root', join(base, 'root-alias'));
const app = createApp({ modules: [], static: root });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
test('static on Bun: a link to a file outside the root is a miss', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
test('static on Bun: a link to a file inside the root is served', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
test('static on Bun: a dangling link is a 404, not a rejection', async () => {
expect((await get('/dangling')).status).toBe(404);
});
test('static on Bun: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
+78
View File
@@ -0,0 +1,78 @@
// #41 (CARD-26, D23) on Bun: the outbound pump waits while the socket is backed up. Bun has no
// `bufferedAmount` property; the adapter reads `getBufferedAmount()` and waits on `drain`.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
return { server, port: server.port };
}
test('serveBun: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
expect(state.pulled).toBe(stalled);
expect(stalled).toBeLessThan(FRAMES / 10);
expect(await client.readAll(FRAMES)).toEqual({ received: FRAMES, inOrder: true });
expect(state.pulled).toBe(FRAMES);
client.destroy();
} finally {
server.stop(true);
}
}, 60_000);
test('serveBun: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
expect(state.pulled).toBeLessThan(FRAMES / 10);
client.destroy();
await sleep(300);
expect(state.returned).toBe(true);
expect(state.pulled).toBeLessThan(FRAMES / 10);
} finally {
server.stop(true);
}
}, 60_000);
+92
View File
@@ -20,6 +20,22 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
@@ -47,3 +63,79 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
server.stop(true);
}
});
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
expect(closed).toEqual({ code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
expect(httpRes.status).toBe(200);
} finally {
server.stop(true);
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Up to
// Bun 1.3 its uWebSockets core dropped the TCP connection without a close frame, so the peer saw
// `1006`; from Bun 1.4 it sends a real `1009`, like Node, Deno and the edge. Asserted per version
// rather than papered over, so a further change in either direction fails here and is noticed.
const [bunMajor, bunMinor] = Bun.version.split('.').map(Number);
const OVERSIZE_CLOSE = bunMajor > 1 || (bunMajor === 1 && bunMinor >= 4) ? 1009 : 1006;
test('serveBun: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
expect(over.close?.code).toBe(OVERSIZE_CLOSE);
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
} finally {
server.stop(true);
}
});
test('serveBun: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
expect(atLimit.replies.length).toBe(1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
expect(over.close?.code).toBe(OVERSIZE_CLOSE);
} finally {
server.stop(true);
}
});
+95
View File
@@ -0,0 +1,95 @@
// #105 on the real Deno runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveDeno`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
Deno.test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
assertEquals(res.status, 413);
assertEquals(source.pulled, 0);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
assertEquals(res.status, 413);
if (source.pulled > 5) throw new Error(`pulled ${source.pulled} chunks — the read did not stop at the limit`);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
assertEquals(at.status, 200);
assertEquals(await at.json(), { length: LIMIT });
assertEquals(over.status, 413);
await over.body?.cancel();
await app.close();
});
Deno.test('T11 serveDeno: the same statuses over a real socket', async () => {
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
try {
const send = (body: BodyInit, headers?: Record<string, string>) => fetch(post(`${base}/small`, body, headers));
const declared = await send(new Uint8Array(2 * SMALL));
assertEquals(declared.status, 413);
await declared.body?.cancel();
const streamed = await send(countingStream(10, 300).stream);
assertEquals(streamed.status, 413);
await streamed.body?.cancel();
const at = await send('x'.repeat(SMALL), { 'content-type': 'text/plain' });
assertEquals(at.status, 200);
await at.body?.cancel();
const over = await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' });
assertEquals(over.status, 413);
await over.body?.cancel();
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+204
View File
@@ -0,0 +1,204 @@
// #120 (CARD-24, D22) on Deno: an RPC whose body is within `maxBodyBytes` reaches the teapot,
// although the control channel is a WebSocket bounded like every other. Node twin:
// test/mesh/large-body.test.ts, which explains the cases.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
const WRAP = '{"data":""}'.length;
@Route('/big')
class BigCtl {
@Post('/echo', { export: true })
echo(@body() b: { data: string } | string) {
return { length: typeof b === 'string' ? b.length : b.data.length };
}
@Ws('/sock')
sock(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${String(msg).length}`;
})();
}
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api' })
class TeacupModule {}
async function serve(app: ReturnType<typeof createApp>) {
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
return { server, port };
}
async function pair(maxBodyBytes?: number) {
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
const t = await serve(teapot);
const url = `ws://127.0.0.1:${t.port}/__mesh__/control`;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
limits,
});
const c = await serve(teacup);
const post = (payload: string, type = 'application/json') =>
fetch(`http://127.0.0.1:${c.port}/api/big/echo`, {
method: 'POST',
headers: { 'content-type': type },
body: payload,
});
const close = async () => {
await teacup.close();
await teapot.close();
await c.server.shutdown();
await t.server.shutdown();
};
return { post, close, tPort: t.port, teacup };
}
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
Deno.test('mesh on Deno: a 1 MB JSON body reaches the teapot (T1)', async () => {
const { post, close } = await pair();
try {
const res = await post(json(1_000_000));
assertEquals(res.status, 200);
assertEquals(await res.json(), { length: 1_000_000 - WRAP });
assertEquals((await post(json(1_000_000))).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
const { post, close } = await pair();
try {
const res = await post('"'.repeat(999_000), 'text/plain');
assertEquals(res.status, 200);
assertEquals(await res.json(), { length: 999_000 });
assertEquals((await post('ok', 'text/plain')).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
const res = await post('\u0001'.repeat(999_000), 'text/plain');
assertEquals(res.status, 200);
assertEquals(await res.json(), { length: 999_000 });
assertEquals((await post('ok', 'text/plain')).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
const { post, close } = await pair();
try {
assertEquals((await post(json(1_000_001))).status, 413);
assertEquals((await post(json(1_000))).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
ws.onopen = () => ws.send('x'.repeat(1_048_577));
ws.onclose = (e) => resolve(e.code);
});
assertEquals(code, 1009);
} finally {
await close();
}
});
Deno.test('mesh on Deno: the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
const { post, close } = await pair(4_000_000);
try {
const res = await post(json(3_900_000));
assertEquals(res.status, 200);
assertEquals(await res.json(), { length: 3_900_000 - WRAP });
} finally {
await close();
}
});
Deno.test('mesh on Deno: 64 concurrent RPCs on one link all succeed (#148)', async () => {
const { post, close, teacup } = await pair();
try {
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
const rpc = () =>
teacup.fetch(
new Request('http://x/api/big/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: json(100),
}),
);
const res = await Promise.all(Array.from({ length: 64 }, rpc));
assertEquals(res.map((r) => r.status), Array(64).fill(200));
assertEquals((await post(json(1_000))).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
ws.onopen = () => {
for (let i = 0; i < 17; i++) ws.send(String(i));
};
ws.onclose = (e) => resolve(e.code);
});
assertEquals(code, 1013);
} finally {
await close();
}
});
Deno.test('mesh on Deno: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
ws.onopen = () => ws.send('x'.repeat(1_000_000));
ws.onclose = (e) => resolve(e.code);
});
assertEquals(code, 1009);
} finally {
await close();
}
});
+73
View File
@@ -0,0 +1,73 @@
// #116 on the real Deno runtime: `serveDeno` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveDeno(createApp({ modules: [M], trustProxy: opts.trustProxy }), {
hostname,
port: 0,
onListen: () => {},
});
const port = (server as unknown as { addr: { port: number } }).addr.port;
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
function ipv6Available(): boolean {
try {
Deno.listen({ hostname: '::1', port: 0 }).close();
return true;
} catch {
return false;
}
}
Deno.test('T1 serveDeno: ctx.ip is the socket peer address', async () => {
assertEquals(await ipVia('127.0.0.1'), '127.0.0.1');
});
Deno.test({
name: 'T3 serveDeno: an IPv6 peer is passed through as Deno reports it',
ignore: !ipv6Available(), // skipped, not failed: the host has no IPv6 loopback to connect over
fn: async () => {
assertEquals(await ipVia('::1'), '::1');
},
});
Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
assertEquals(ip, '203.0.113.7');
});
Deno.test('T5 serveDeno: trustProxy without x-forwarded-for falls back to the peer', async () => {
assertEquals(await ipVia('127.0.0.1', { trustProxy: true }), '127.0.0.1');
});
Deno.test('T6 serveDeno: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
assertEquals(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } }), '127.0.0.1');
});
+23
View File
@@ -0,0 +1,23 @@
// The frozen router-parity differential under the real Deno runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = async (name: string) =>
JSON.parse(await Deno.readTextFile(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)));
Deno.test('router parity on Deno: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
assertEquals(report.mismatches, []);
assertEquals(report.sets.length, 5);
});
Deno.test('router parity on Deno: app.fetch cases', async () => {
const report = await runAppDifferential(load);
assertEquals(report.mismatches, []);
});
+37
View File
@@ -74,3 +74,40 @@ Deno.test('multipart resolves the busboy peer dependency instead of reporting it
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close();
});
// #106 on Deno, which reaches `realpath` through its `node:fs` compat. Committed symlinks rather than
// a temp tree, for the same `--allow-write` reason as above; `secret.txt` sits beside the root.
const linked = 'test/fixtures/static';
Deno.test('static: a link to a file outside the root is a miss', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/out-link'));
assertEquals(res.status, 404);
assertEquals((await res.text()).includes('TOP SECRET'), false);
await app.close();
});
Deno.test('static: a link to a file inside the root is served', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/in-link'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'in root');
await app.close();
});
Deno.test('static: a dangling link is a 404, not a rejection', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
assertEquals((await app.fetch(new Request('http://x/dangling'))).status, 404);
await app.close();
});
Deno.test('static: a root that is itself a symlink still serves its files', async () => {
const app = createApp({ modules: [], static: `${linked}/root-alias` });
const a = await app.fetch(new Request('http://x/a.txt'));
assertEquals(a.status, 200);
assertEquals(await a.text(), 'in root');
const sub = await app.fetch(new Request('http://x/sub/'));
assertEquals(sub.status, 200);
assertEquals(await sub.text(), '<h1>Sub</h1>');
await app.close();
});
+114
View File
@@ -0,0 +1,114 @@
// #41 (CARD-26, D23) on Deno: the outbound pump waits while the socket is backed up. Deno's
// WebSocket fires no drain event, so the adapter polls `bufferedAmount` while over the mark.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assert, assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Route('/early')
class Early {
// Yields before Deno's socket has left CONNECTING. The pump used to pull 'hi', find the socket
// not open, and give up: the client got no frame and a close without a code (1005).
@Ws('/hi')
hi() {
return (async function* () {
yield 'hi';
await new Promise<never>(() => {});
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood, Early] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
let port = 0;
const server = await serveDeno(createApp({ modules: [M] }), {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await sleep(50);
return { server, port };
}
Deno.test('serveDeno: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
assertEquals(state.pulled, stalled);
assert(stalled < FRAMES / 10, `pulled ${stalled} of ${FRAMES} with nobody reading`);
assertEquals(await client.readAll(FRAMES), { received: FRAMES, inOrder: true });
assertEquals(state.pulled, FRAMES);
client.destroy();
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
assert(state.pulled < FRAMES / 10);
client.destroy();
await sleep(300);
assertEquals(state.returned, true);
assert(state.pulled < FRAMES / 10);
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: a ws route that yields at once still delivers its first frame', async () => {
const { server, port } = await serve();
try {
const first = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/early/hi`);
ws.onmessage = (e) => {
resolve(String(e.data));
ws.close();
};
ws.onclose = (e) => reject(new Error(`closed ${e.code} before any frame`));
});
assertEquals(first, 'hi');
} finally {
await server.shutdown();
}
});
+112
View File
@@ -28,6 +28,22 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
await server.shutdown();
}
});
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
assertEquals(closed, { code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
assertEquals(httpRes.status, 200);
await httpRes.body?.cancel();
} finally {
await server.shutdown();
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: on Deno the runtime receives the whole message before user code sees it, so the size
// bound is checked after receipt — the close code is the same as on Node and Bun.
Deno.test('serveDeno: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
assertEquals(atLimit.replies, [`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
assertEquals(over.close, { code: 1009, reason: 'message too large' });
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
assertEquals(full.close, { code: 1013, reason: 'inbound queue full' });
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
assertEquals(atLimit.replies.length, 1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
assertEquals(over.close?.code, 1009);
} finally {
await server.shutdown();
}
});
+32
View File
@@ -0,0 +1,32 @@
// Worker entry that runs the frozen router-parity differential inside workerd: every matcher case
// through the oracle and the live router, and the app.fetch cases, against the same frozen files the
// Node suite uses. The frozen JSON is bundled in, since a worker has no file system. Driven by
// test/edge/run.ts; see test/router-parity/README.md.
import { runDifferential } from '../router-parity/differential';
import { runAppDifferential } from '../router-parity/app-fixture';
import matcherHand from '../router-parity/frozen/matcher-hand.json';
import matcherOwner from '../router-parity/frozen/matcher-owner.json';
import matcherGenerated from '../router-parity/frozen/matcher-generated.json';
import matcherGeneratedV2 from '../router-parity/frozen/matcher-generated-v2.json';
import matcherWs from '../router-parity/frozen/matcher-ws.json';
import appFetch from '../router-parity/frozen/app-fetch.json';
import ownerAppAllow from '../router-parity/frozen/owner-app-allow.json';
const FROZEN: Record<string, unknown> = {
'matcher-hand': matcherHand,
'matcher-owner': matcherOwner,
'matcher-generated': matcherGenerated,
'matcher-generated-v2': matcherGeneratedV2,
'matcher-ws': matcherWs,
'app-fetch': appFetch,
'owner-app-allow': ownerAppAllow,
};
export default {
fetch: async (): Promise<Response> => {
const load = (name: string) => FROZEN[name];
const matcher = await runDifferential(load);
const app = await runAppDifferential(load);
return Response.json({ matcher, app });
},
};
+132 -3
View File
@@ -66,6 +66,33 @@ async function main() {
assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
const res = await mf.dispatchFetch('http://localhost/rt/body', {
method: 'POST',
headers: { 'content-type': 'text/plain' },
body,
duplex: 'half',
} as Parameters<typeof mf.dispatchFetch>[1]);
await res.arrayBuffer();
return res.status;
};
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
let sent = 0;
return new ReadableStream({
pull(controller) {
if (sent++ === count) controller.close();
else controller.enqueue(new Uint8Array(size).fill(0x61));
},
});
};
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
// WebSocket
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' },
@@ -84,13 +111,115 @@ async function main() {
});
assert.equal(got, 'echo:hi');
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
// #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
headers: { Upgrade: 'websocket' },
});
const bad = badRes.webSocket;
assert.ok(bad, 'expected a client webSocket on the 101 response');
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
bad.addEventListener('close', (e: { code: number; reason: string }) =>
resolve({ code: e.code, reason: e.reason }),
),
);
bad.accept();
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
// #107: workerd delivers the whole message before user code sees it, so the size bound is
// checked after receipt; the close codes match Node and Deno.
const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames);
assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]);
assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' });
assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, {
code: 1013,
reason: 'inbound queue full',
});
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
} finally {
await mf.dispose();
}
}
main().catch((err) => {
const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs';
/**
* The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling
* as the main worker; the worker runs every case itself and answers with its mismatch report.
*/
async function parity() {
await build({
entryPoints: ['test/edge/parity-worker.ts'],
bundle: true,
format: 'esm',
outfile: PARITY_BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: PARITY_BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
const res = await mf.dispatchFetch('http://localhost/');
const report = (await res.json()) as {
matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] };
app: { requests: number; mismatches: string[] };
};
assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd');
assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd');
const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0);
console.log(
`edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`,
);
} finally {
await mf.dispose();
}
}
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
const ws = res.webSocket;
assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`);
const replies: string[] = [];
const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, ms);
ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data)));
ws.addEventListener('close', (e: { code: number; reason: string }) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
});
});
ws.accept();
for (const frame of frames) ws.send(frame);
return result;
}
main()
.then(parity)
.catch((err) => {
console.error(err);
process.exit(1);
});
});
+32 -2
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index';
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
import { edgeHandler } from '../../src/edge';
@Route('/rt')
@@ -11,17 +11,47 @@ class Rt {
return { ok: true };
}
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer.
@Post('/body', { maxBodyBytes: 1000 })
body(@body() b: unknown) {
return { length: String(b).length };
}
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
export default { fetch: edgeHandler(app) };
export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
};
+155 -1
View File
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
import { countingStream } from './helpers/counting-stream';
import { setPeer } from '../src/http/peer';
@Provider({ provides: 'store' })
class Store {
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
);
expect(await res.json()).toEqual({ ip: '' });
});
// #116: the Deno and Bun adapters now hand `buildFetch` the socket peer. A bare `app.fetch` from
// user code has none to hand, so it must keep answering exactly what it did before.
it('T7: bare app.fetch without peer metadata is unchanged', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
expect(await (await untrusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(await (await trusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(
await (
await trusting.fetch(new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9' } }))
).json(),
).toEqual({ ip: '9.9.9.9' });
});
it('the peer an adapter recorded reaches ctx.ip, and trustProxy without XFF falls back to it', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
const spoofed = new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '1.2.3.4' } });
const plain = new Request('http://x/ip/whoami');
setPeer(spoofed, '127.0.0.1');
setPeer(plain, '::1');
expect(await (await untrusting.fetch(spoofed)).json()).toEqual({ ip: '127.0.0.1' });
expect(await (await trusting.fetch(plain)).json()).toEqual({ ip: '::1' });
});
// The published CommonJS build bundles `index`, `deno` and `bun` as separate files, each with its
// own copy of every module they share, so `serveBun` from `@green-tea/core/bun` and `app.fetch`
// from `@green-tea/core` do not run the same `peer.ts`. A store private to the module would be two
// stores, and the peer recorded by one would never be found by the other.
it('a second copy of the peer module sees the peer the first one recorded', async () => {
const request = new Request('http://x/');
setPeer(request, '192.0.2.1'); // through the copy this file imported
vi.resetModules();
const copy = await import('../src/http/peer');
expect(copy.setPeer).not.toBe(setPeer); // really a second instance of the module
expect(copy.peerOf(request)).toBe('192.0.2.1');
});
it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => {
const original = new Request('http://x/ip/whoami');
setPeer(original, '127.0.0.1');
const res = await createApp({ modules: [IpModule] }).fetch(new Request(original));
expect(await res.json()).toEqual({ ip: '' });
});
});
describe('app.fetch on a mesh app', () => {
@@ -145,3 +198,104 @@ describe('app.fetch on a mesh app', () => {
}
});
});
// #105: the limit is enforced while the body is read, not after it has been buffered. A status code
// cannot tell the two apart — both answer 413 — so the counting stream is what these assert on.
@Route('/limits')
class LimitsCtl {
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
@Post('/small', { maxBodyBytes: 10 }) small(@body() b: any) {
return { got: b };
}
@Post('/large', { maxBodyBytes: 2_000_000 }) large(@body() b: any) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [LimitsCtl] })
class LimitsModule {}
const post = (path: string, body: RequestInit['body'], headers: Record<string, string> = {}) =>
new Request(`http://x${path}`, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
describe('app.fetch bounded body reads (#105)', () => {
const limitsApp = createApp({ modules: [LimitsModule] }); // server limit: the 1 MB default
it('T1: a declared content-length over the limit is refused without reading the body', async () => {
const body = countingStream(10, 300_000);
const res = await limitsApp.fetch(post('/limits/echo', body.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(body.pulled).toBe(0);
expect(body.cancelled).toBe(true);
});
it('T3: a streamed body stops at the chunk that crosses the limit, and the reader is cancelled', async () => {
const body = countingStream(10, 300_000); // 3 MB, no content-length
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
// 4 read, the 4th crossing 1 MB, plus at most one the stream queued ahead of the reader.
expect(body.pulled).toBeLessThanOrEqual(5);
expect(body.cancelled).toBe(true);
});
it('T4: a body of exactly the limit is accepted', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 8) });
expect(Buffer.byteLength(json)).toBe(1_000_000);
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(200);
expect(((await res.json()) as any).got.s).toHaveLength(1_000_000 - 8);
});
it('T5: one byte over the limit is refused', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 7) });
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(413);
});
it('T5: one byte over the limit is refused when streamed without a content-length', async () => {
const body = countingStream(1, 1_000_001);
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
});
it('T8: a route limit below the server limit wins', async () => {
const res = await limitsApp.fetch(post('/limits/small', 'x'.repeat(11), { 'content-type': 'text/plain' }));
expect(res.status).toBe(413);
});
it('T9: a route limit above the server limit wins', async () => {
const res = await limitsApp.fetch(
post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }),
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 1_500_000 });
});
it('a malformed content-length is ignored, and the stream count enforces the limit', async () => {
const body = countingStream(1, 20);
const res = await limitsApp.fetch(post('/limits/small', body.stream, { 'content-length': 'nope' }));
expect(res.status).toBe(413);
});
it('T10: a bodiless request is answered without reading anything', async () => {
const res = await limitsApp.fetch(new Request('http://x/limits/echo', { method: 'POST' }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({});
});
});
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
root
+1
View File
@@ -0,0 +1 @@
in root
+1
View File
@@ -0,0 +1 @@
../nope.txt
+1
View File
@@ -0,0 +1 @@
a.txt
+1
View File
@@ -0,0 +1 @@
../secret.txt
+1
View File
@@ -0,0 +1 @@
<h1>Sub</h1>
+1
View File
@@ -0,0 +1 @@
TOP SECRET
+44
View File
@@ -0,0 +1,44 @@
// A request body that records how much of it was consumed. Web APIs only, so the Node, Deno and Bun
// suites share it: the regression it guards (#105) is "read the whole body before checking the
// limit", which no status code can show on its own — a 413 looks the same either way.
export interface CountingStream {
stream: ReadableStream<Uint8Array>;
/** Chunks the consumer has pulled so far. */
readonly pulled: number;
/** Whether the consumer cancelled the stream. */
readonly cancelled: boolean;
}
/** `count` chunks of `size` bytes each, handed out one per pull. */
export function countingStream(count: number, size: number): CountingStream {
let pulled = 0;
let cancelled = false;
const stream = new ReadableStream<Uint8Array>({
// Pull-based, and only on demand: with a high-water mark of 0 the stream does not pre-fill its
// queue, so `pulled` counts what the consumer asked for. The default of 1 pulls a chunk at
// construction, before anyone reads, and would make "nothing was read" unprovable.
pull(controller) {
if (pulled === count) {
controller.close();
return;
}
pulled++;
controller.enqueue(new Uint8Array(size).fill(0x61));
},
cancel() {
cancelled = true;
},
}, { highWaterMark: 0 });
return {
stream,
get pulled() {
return pulled;
},
get cancelled() {
return cancelled;
},
};
}
+83
View File
@@ -0,0 +1,83 @@
// A WebSocket client over a bare `node:net` socket, for the backpressure tests (#41) on Deno and
// Bun. The platform `WebSocket` reads as fast as it can and cannot be told to stop; a TCP socket
// can be paused, which is the "client reads slowly" those tests need. Server frames are unmasked,
// and every frame these tests send is the same size, so frames are found by offset alone.
import net from 'node:net';
export interface RawWs {
/** Stop reading: the server's send buffer is all that can grow. */
pause(): void;
/** Resume reading; resolves once `count` frames have arrived, reporting whether they were in order. */
readAll(count: number): Promise<{ received: number; inOrder: boolean }>;
destroy(): void;
}
/**
* Opens `ws://127.0.0.1:<port><path>` and resolves once the 101 is in. Each server frame must be
* a text frame of exactly `payload` bytes (> 65535, so a 10-byte header) whose first 8 bytes are
* its zero-padded index.
*/
export function rawWs(port: number, path: string, payload: number): Promise<RawWs> {
const total = payload + 10;
const socket = net.connect(port, '127.0.0.1');
let head = '';
let upgraded = false;
let pos = 0;
let digits = '';
let received = 0;
let inOrder = true;
let onFrame = () => {};
const consume = (chunk: Uint8Array) => {
let i = 0;
while (i < chunk.length) {
if (pos < 18) {
if (pos === 0 && chunk[i] !== 0x81) inOrder = false;
if (pos >= 10) digits += String.fromCharCode(chunk[i]);
if (pos === 17) {
if (Number(digits) !== received) inOrder = false;
digits = '';
}
pos++;
i++;
} else {
const skip = Math.min(total - pos, chunk.length - i);
pos += skip;
i += skip;
}
if (pos === total) {
pos = 0;
received++;
onFrame();
}
}
};
return new Promise((resolve, reject) => {
socket.once('error', reject);
socket.on('data', (chunk: Uint8Array) => {
if (upgraded) return consume(chunk);
head += new TextDecoder('latin1').decode(chunk);
const end = head.indexOf('\r\n\r\n');
if (end < 0) return;
upgraded = true;
const rest = chunk.subarray(chunk.length - (head.length - end - 4));
resolve({
pause: () => socket.pause(),
readAll: (count) =>
new Promise((done) => {
onFrame = () => {
if (received === count) done({ received, inOrder });
};
socket.resume();
}),
destroy: () => socket.destroy(),
});
consume(rest);
});
socket.write(
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
);
});
}
+26
View File
@@ -123,6 +123,32 @@ describe('request hardening', () => {
server.close();
});
// #105: a declared length over the limit is answered before any of the body is sent. Without the
// header check, the reader waits for a first chunk that this client never sends — and times out.
it('T2: rejects a declared content-length over the limit before reading any body', async () => {
let ran = false;
const server = createHttpServer(
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
);
await new Promise<void>((r) => server.listen(0, r));
const socket = net.connect((server.address() as any).port, '127.0.0.1');
await once(socket, 'connect');
socket.write('POST /echo HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\n\r\n'); // headers only
let raw = '';
socket.setEncoding('utf8');
socket.on('data', (chunk: string) => (raw += chunk));
await once(socket, 'end');
expect(raw).toMatch(/^HTTP\/1\.1 413 /);
expect(raw.toLowerCase()).toContain('connection: close');
expect(ran).toBe(false);
socket.destroy();
server.close();
}, 2000);
it('sets the configured server timeouts and connection limit', async () => {
const server = createHttpServer([], [], undefined, undefined,
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
+285
View File
@@ -0,0 +1,285 @@
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import http from 'node:http';
import net from 'node:net';
import { once } from 'node:events';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import type { HttpOptions, RouteDef } from '../src/http/types';
import type { Logger } from '../src/logger';
// #108: `http.createServer` ignores the promise its listener returns, so a rejection inside the
// request listener used to be an `unhandledRejection` — fatal under Node's default mode. Every test
// here goes through a real socket, because the boundary under test is the Node listener itself.
interface Reply {
status?: number;
headers?: http.IncomingHttpHeaders;
body?: string;
/** Set when the connection ended without a complete response. */
error?: string;
}
/** A GET on a fresh connection (`agent: false`), bounded so a hung listener fails fast instead of at the 30 s request timeout. */
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<Reply> {
return new Promise((resolve) => {
const reply: Reply = {};
const req = http.request({ host: '127.0.0.1', port, path, headers, agent: false }, (res) => {
reply.status = res.statusCode;
reply.headers = res.headers;
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk: string) => (body += chunk));
res.on('end', () => resolve({ ...reply, body }));
res.on('error', (err) => resolve({ ...reply, body, error: err.message }));
res.on('aborted', () => resolve({ ...reply, body, error: 'aborted' }));
});
req.setTimeout(1_000, () => req.destroy(new Error('client timeout')));
req.on('error', (err) => resolve({ ...reply, error: err.message }));
req.end();
});
}
function spyLogger(): Logger & { error: Mock<(...args: unknown[]) => void> } {
return { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
}
const ok: RouteDef = {
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: { 'content-type': 'text/plain' }, body: 'ok' }),
};
const servers: http.Server[] = [];
async function start(routes: RouteDef[], opts: HttpOptions = {}, bus?: Bus): Promise<number> {
const server = createHttpServer([ok, ...routes], [], bus, undefined, opts);
servers.push(server);
server.listen(0, '127.0.0.1');
await once(server, 'listening');
return (server.address() as net.AddressInfo).port;
}
/** T10: after every injected failure, a normal request on a fresh connection still succeeds. */
async function expectServerStillServes(port: number): Promise<void> {
const next = await get(port, '/ok');
expect(next.status).toBe(200);
expect(next.body).toBe('ok');
}
const settle = () => new Promise((r) => setTimeout(r, 20));
let unhandled: Mock<(...args: unknown[]) => void>;
let uncaught: Mock<(...args: unknown[]) => void>;
beforeEach(() => {
unhandled = vi.fn();
uncaught = vi.fn();
process.on('unhandledRejection', unhandled);
process.on('uncaughtException', uncaught);
});
afterEach(async () => {
await settle();
process.off('unhandledRejection', unhandled);
process.off('uncaughtException', uncaught);
for (const server of servers.splice(0)) {
server.closeAllConnections();
server.close();
}
expect(unhandled).not.toHaveBeenCalled();
expect(uncaught).not.toHaveBeenCalled();
});
const rejectingStatic = (reason: unknown) => async () => {
throw reason;
};
describe('Node request-listener boundary (#108)', () => {
it('T1: a rejected request operation while writable answers a minimal 500 and closes', async () => {
const logger = spyLogger();
const port = await start([], { static: rejectingStatic(new Error('boom')), logger });
const res = await get(port, '/missing');
expect(res.status).toBe(500);
expect(res.headers?.connection).toBe('close');
expect(res.headers?.['content-type']).toBe('application/json');
expect(JSON.parse(res.body!)).toEqual({ error: 'Internal Server Error' });
// The security headers still land: the minimal path writes through the patched writeHead.
expect(res.headers?.['x-content-type-options']).toBe('nosniff');
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'boom' });
await expectServerStillServes(port);
});
it.each([['boom'], [undefined]])('T2: a non-Error rejection (%s) answers 500 and logs String(err)', async (reason) => {
const logger = spyLogger();
const port = await start([], { static: rejectingStatic(reason), logger });
const res = await get(port, '/missing');
expect(res.status).toBe(500);
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: String(reason) });
await expectServerStillServes(port);
});
// Deviation from the card: `originAllowed` already guards a throwing predicate and denies the origin
// (src/security.ts), so this never reaches the listener boundary. Kept as a regression test.
it('T3: a throwing cors.origins predicate denies the origin and serves the request', async () => {
const logger = spyLogger();
const port = await start([], {
logger,
cors: {
origins: () => {
throw new Error('allowlist down');
},
},
});
const res = await get(port, '/ok', { origin: 'https://a.example' });
expect(res.status).toBe(200);
expect(res.headers?.['access-control-allow-origin']).toBeUndefined();
await expectServerStillServes(port);
});
it('T4: an invalid handler header value answers 500 through the minimal path', async () => {
const logger = spyLogger();
const port = await start(
[
{
method: 'GET',
pattern: '/bad-header',
transport: 'buffer',
handler: async () => ({ status: 200, headers: { 'x-bad': 'a\nb' }, body: 'nope' }),
},
],
{ logger },
);
const res = await get(port, '/bad-header');
expect(res.status).toBe(500);
expect(res.headers?.connection).toBe('close');
expect(res.headers?.['x-bad']).toBeUndefined();
expect(logger.error).toHaveBeenCalledTimes(1);
await expectServerStillServes(port);
});
// The card's BigInt injection is caught inside `pipeStream`'s loop and becomes an error frame, so it
// never reaches the boundary; kept as a regression test. The second case fails after the 200 headers
// are flushed but before that loop, which is the "output already started" path.
it('T5a: a stream encoder failure on the first frame ends the stream with an error frame', async () => {
const port = await start([
{
method: 'GET',
pattern: '/big',
transport: 'ndjson',
handler: async () => ({
stream: (async function* () {
yield { n: BigInt(1) };
})(),
}),
},
]);
const res = await get(port, '/big');
expect(res.status).toBe(200);
expect(res.body).toContain('"error"');
await expectServerStillServes(port);
});
it('T5b: a failure after the 200 headers were sent destroys the connection and is logged', async () => {
const logger = spyLogger();
const port = await start(
[
{
method: 'GET',
pattern: '/broken-stream',
transport: 'ndjson',
handler: async () => ({
stream: {
[Symbol.asyncIterator]() {
throw new Error('iterator failed');
},
},
}),
},
],
{ logger },
);
const res = await get(port, '/broken-stream');
expect(res.status).toBe(200);
expect(res.error).toBeDefined();
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'iterator failed' });
await expectServerStillServes(port);
});
it('T6: a throwing onError still sends the built-in 404', async () => {
const logger = spyLogger();
const port = await start([], {
logger,
onError: () => {
throw new Error('renderer broke');
},
});
const res = await get(port, '/missing');
expect(res.status).toBe(404);
await expectServerStillServes(port);
});
it('T7: a throwing request:start observer does not alter the response', async () => {
const bus = new Bus();
bus.on('request:start', () => {
throw new Error('observer broke');
});
const port = await start([], { bus }, bus);
await expectServerStillServes(port);
await expectServerStillServes(port);
});
it('T8: a client abort racing a rejection leaves no unhandled rejection and no write after close', async () => {
const logger = spyLogger();
let rejected!: () => void;
const done = new Promise<void>((r) => (rejected = r));
const port = await start([], {
logger,
static: async () => {
await new Promise((r) => setTimeout(r, 50));
rejected();
throw new Error('late');
},
});
const socket = net.connect(port, '127.0.0.1');
await once(socket, 'connect');
socket.write('GET /missing HTTP/1.1\r\nHost: x\r\n\r\n');
await new Promise((r) => setTimeout(r, 10));
socket.destroy();
await done;
await settle();
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'late' });
await expectServerStillServes(port);
});
it('T9: a rejection releases its maxConcurrentRequests slot', async () => {
const port = await start(
[],
{ static: rejectingStatic(new Error('boom')), limits: { maxConcurrentRequests: 1 }, logger: spyLogger() },
);
expect((await get(port, '/missing')).status).toBe(500);
await expectServerStillServes(port);
await expectServerStillServes(port);
});
});
+100
View File
@@ -0,0 +1,100 @@
// Before a peer's `hello` is accepted, the mesh control channel takes only hello-sized frames and
// a small queue. The large bounds that carry RPC bodies (#120, #148) apply after authentication
// only, so an unauthenticated peer cannot make the process buffer `queue × frame` bytes — which
// at 4,096 × 7 MB was tens of GB, reachable while `app.upgrade` waits for a slow boot.
import { describe, it, expect } from 'vitest';
import { createApp, Module, Provider, Step } from '../../src/index';
import { channel } from '../../src/channel';
import { MESH_CONTROL_PATH } from '../../src/mesh/teapot';
import { encode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
@Provider({ provides: 'slow' })
class Slow {
async provide() {
await new Promise((resolve) => setTimeout(resolve, 300));
return { slow: true };
}
}
@Step({ provides: 'cfg', needs: [], export: true })
class Cfg {
run() {
return { cfg: 1 };
}
}
@Module({ mountpoint: '/api', providers: [Slow], steps: [Cfg] })
class SlowTeapot {}
function fakeSocket() {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: string[] = [];
const closes: number[] = [];
const socket: WsSocket = {
inbound,
abort: ac.signal,
get isOpen() {
return !ac.signal.aborted;
},
send: (d) => sent.push(d),
close: (code) => {
if (ac.signal.aborted) return;
closes.push(code ?? 1005);
ac.abort();
inbound.close();
},
terminate: () => ac.abort(),
};
return { socket, inbound, sent, closes };
}
const req: WsRequest = { url: MESH_CONTROL_PATH, headers: {}, protocol: 'http', ip: '' };
const teapot = () => createApp({ modules: [SlowTeapot], experimental: true, mesh: { secret: 's3cr3t' } });
describe('mesh control channel before authentication', () => {
it('closes 1009 on a frame over hello size while the boot is still running', async () => {
const app = teapot();
const { socket, inbound, closes } = fakeSocket();
const run = app.upgrade(req, socket);
inbound.push('x'.repeat(1_000_000));
expect(closes).toEqual([1009]); // at once: the boot has not finished, nothing was buffered
await run;
await app.close();
});
it('closes 1013 when an unauthenticated peer floods frames during the boot', async () => {
const app = teapot();
const { socket, inbound, closes } = fakeSocket();
const run = app.upgrade(req, socket);
let accepted = 0;
for (let i = 0; i < 64 && !closes.length; i++, accepted++) inbound.push('x'.repeat(1024));
expect(closes).toEqual([1013]);
expect(accepted).toBeLessThanOrEqual(17); // the user default, not the authenticated 4,096
await run;
await app.close();
});
it('lifts the bounds once the hello is accepted', async () => {
const app = teapot();
const { socket, inbound, sent, closes } = fakeSocket();
const run = app.upgrade(req, socket);
inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 's3cr3t' }));
await new Promise((resolve) => setTimeout(resolve, 400)); // boot, then the handshake
expect(JSON.parse(sent[0]).type).toBe('manifest');
// A frame far over hello size is accepted now (undecodable, so ignored), and a burst of 64
// fits the authenticated queue.
inbound.push('x'.repeat(1_000_000));
for (let i = 0; i < 64; i++) inbound.push(encode({ type: 'ping' }));
await new Promise((resolve) => setTimeout(resolve, 20));
expect(closes).toEqual([]);
expect(sent.filter((s) => s.includes('pong'))).toHaveLength(64);
socket.close(1000);
await run;
await app.close();
});
});
+2 -2
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { envelopeFrom } from '../../src/mesh/teacup';
import { createMeshControl } from '../../src/mesh/teapot';
import { controlFrameLimit, createMeshControl } from '../../src/mesh/teapot';
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
import { Bus } from '../../src/bus';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@@ -139,7 +139,7 @@ describe('teapot hardening', () => {
const fake = fakeSocket();
const running = control().handle(fake.socket as never);
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(controlFrameLimit() + 1)}"}`);
await running;
expect(fake.closes[0]?.code).toBe(1009);
+185
View File
@@ -0,0 +1,185 @@
// #120 (CARD-24, D22): an RPC whose body is within `maxBodyBytes` must reach the teapot.
//
// The control channel is a WebSocket, and every WebSocket was bounded by
// `limits.maxWsMessageBytes` (1 MiB by default, #107). A body at the HTTP limit (1,000,000 B by
// default) travels inside an `rpc-req` envelope, re-encoded as JSON:
// - a JSON body re-encodes to about its own size, so 1 MB fits under 1 MiB (T1);
// - a text body does not: every `"` or `\` doubles under JSON escaping, so a 999 KB text body
// became a ~2 MB frame and the teapot hung up the whole channel with 1009 (T1b);
// - a raised `maxBodyBytes` was capped at 1 MiB on the channel regardless (T4).
// Its queue bound had the same problem (#148): `maxWsQueue` (16) closed it 1013 under a burst of
// RPCs, which Node's `ws` delivers in one go. The Deno and Bun twins live in test/deno and test/bun.
import { describe, it, expect } from 'vitest';
import WebSocket from 'ws';
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index';
const SECRET = 's3cr3t';
const WRAP = '{"data":""}'.length;
@Route('/big')
class BigCtl {
@Post('/echo', { export: true })
echo(@body() b: { data: string } | string) {
return { length: typeof b === 'string' ? b.length : b.data.length };
}
@Ws('/sock')
sock(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${String(msg).length}`;
})();
}
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api' })
class TeacupModule {}
/** A JSON body of exactly `bytes` bytes: `{"data":"xxx…"}`. */
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
async function pair(maxBodyBytes?: number) {
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
const tServer = await teapot.listen(0);
const tPort = (tServer.address() as any).port;
const url = `ws://127.0.0.1:${tPort}/__mesh__/control`;
const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] }, limits });
const cServer = await teacup.listen(0);
const cPort = (cServer.address() as any).port;
const post = (payload: string, type = 'application/json') =>
fetch(`http://127.0.0.1:${cPort}/api/big/echo`, { method: 'POST', headers: { 'content-type': type }, body: payload });
const close = async () => {
await teacup.close();
await teapot.close();
};
return { post, close, tPort, teacup };
}
describe('mesh RPC body near maxBodyBytes (#120)', () => {
it('a 1 MB JSON body reaches the teapot, and the channel stays open (T1)', async () => {
const { post, close } = await pair();
try {
const res = await post(json(1_000_000));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 1_000_000 - WRAP });
expect((await post(json(1_000_000))).status).toBe(200);
} finally {
await close();
}
});
it('a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
const { post, close } = await pair();
try {
const res = await post('"'.repeat(999_000), 'text/plain');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toBe(200);
} finally {
await close();
}
});
it('a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
// `\u0001` re-encodes as the six characters `\u0001`: the worst escaping a body can get.
const res = await post('\u0001'.repeat(999_000), 'text/plain');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toBe(200);
} finally {
await close();
}
});
it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => {
const { post, close } = await pair();
try {
expect((await post(json(1_000_001))).status).toBe(413);
expect((await post(json(1_000))).status).toBe(200);
} finally {
await close();
}
});
it("a user ws route on the same teapot still closes 1009 over maxWsMessageBytes (T3)", async () => {
const { close, tPort } = await pair();
try {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
await new Promise((resolve) => ws.once('open', resolve));
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
ws.send('x'.repeat(1_048_577));
expect(await closed).toBe(1009);
} finally {
await close();
}
});
it('the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
const { post, close } = await pair(4_000_000);
try {
const res = await post(json(3_900_000));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 3_900_000 - WRAP });
} finally {
await close();
}
});
it('64 concurrent RPCs on one link all succeed: the control channel has its own queue bound (#148)', async () => {
const { post, close, teacup } = await pair();
try {
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
const rpc = () =>
teacup.fetch(
new Request('http://x/api/big/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: json(100),
}),
);
const res = await Promise.all(Array.from({ length: 64 }, rpc));
expect(res.map((r) => r.status)).toEqual(Array(64).fill(200));
expect((await post(json(1_000))).status).toBe(200);
} finally {
await close();
}
});
it('a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
const { close, tPort } = await pair();
try {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
await new Promise((resolve) => ws.once('open', resolve));
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
for (let i = 0; i < 17; i++) ws.send(String(i));
expect(await closed).toBe(1013);
} finally {
await close();
}
});
it('an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
await new Promise((resolve) => ws.once('open', resolve));
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
ws.send('x'.repeat(1_000_000)); // within the authenticated bound, far over a hello
expect(await closed).toBe(1009);
} finally {
await close();
}
});
});
+3 -3
View File
@@ -56,11 +56,11 @@ function startSkewedTeapot() {
/**
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
* list: it is the fallback for a Node run with the global WebSocket switched off, and every
* supported Node has the global, so it would otherwise never be covered and rot unnoticed.
*/
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]];
const CTORS: [string, SocketCtor][] = [['the ws package (fallback path)', WS as unknown as SocketCtor]];
if (platform) CTORS.push(['the platform global WebSocket', platform]);
describe('WebSocket client implementations', () => {
+75 -1
View File
@@ -1,6 +1,20 @@
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';
import { createApp, Route, Post, Module, body } from '../src';
// Counts calls into the multipart parser while still running the real one, so a test can prove
// busboy was never reached rather than inferring it from the status code.
const parsed = vi.hoisted(() => ({ calls: 0 }));
vi.mock('../src/multipart', async (importOriginal) => {
const real = await importOriginal<typeof import('../src/multipart')>();
return {
...real,
parseMultipart: (...args: Parameters<typeof real.parseMultipart>) => {
parsed.calls++;
return real.parseMultipart(...args);
},
};
});
let app: any;
afterEach(async () => { await app?.close(); });
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
expect(await post('/b')).toEqual({ x: ['1', '2'] });
});
});
// #105: multipart is parsed from the bytes the bounded reader returns, so the byte limit has to stop
// a request before busboy ever sees it, and `maxParts` has to keep working on what gets through.
describe('multipart limits on app.fetch (#105)', () => {
const form = (fields: number, size = 1) => {
const fd = new FormData();
for (let i = 0; i < fields; i++) fd.set(`f${i}`, 'x'.repeat(size));
return fd;
};
it('T6: a multipart body over maxBodyBytes is 413 and never reaches the parser', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1, 5000) }));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T6: the same holds when the multipart body arrives without a content-length', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const encoded = new Request('http://x', { method: 'POST', body: form(1, 5000) });
const r = await app.fetch(new Request('http://x/u', {
method: 'POST',
headers: { 'content-type': encoded.headers.get('content-type')! },
body: encoded.body,
duplex: 'half',
} as RequestInit));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T7: under the byte limit but over maxParts is 400 Invalid multipart body', async () => {
@Route('/') class C { @Post('/u', { maxParts: 2 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }));
expect(r.status).toBe(400);
expect(await r.text()).toContain('Invalid multipart body');
});
it('T7: the server-level maxParts applies when the route sets none', async () => {
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod], limits: { maxParts: 2 } });
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1) }))).status).toBe(200);
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }))).status).toBe(400);
});
});
-27
View File
@@ -1,27 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
// The `engines` floor is `>=18`, and the global `crypto` only arrived unflagged in Node 19. That gap
// shipped once: `correlateRequest` compiled cleanly against an ambient declaration and then threw
// `ReferenceError: crypto is not defined` on the first request of every Node 18 process.
//
// CI's Node 18 job is what caught it, and this test is what makes it catchable without one — every
// developer machine and every other runtime has the global, so the bug is invisible where it is
// written. Stubbing the global away reproduces the floor's condition on any Node.
//
// If the floor ever moves above 18, this test and the fallback it guards can both go.
describe('correlateRequest without a global crypto (Node 18)', () => {
it('falls back to node:crypto instead of throwing ReferenceError', async () => {
vi.stubGlobal('crypto', undefined);
vi.resetModules();
const { correlateRequest } = await import('../src/http/core');
const a = correlateRequest({});
const b = correlateRequest({});
expect(a.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
expect(a.requestId).not.toBe(b.requestId);
expect(correlateRequest({ 'x-request-id': 'from-gateway' }).requestId).toBe('from-gateway');
vi.unstubAllGlobals();
});
});
+279
View File
@@ -0,0 +1,279 @@
/**
* CARD-13 (#127) through `createApp`: the card's test cases T1–T9, at boot, with the exact messages.
* The decision procedure itself is covered in `route-conflicts.test.ts`.
*/
import 'reflect-metadata';
import { describe, it, expect, vi } from 'vitest';
import { createApp, Route, Get, Post, Ws, Stream, Module, param } from '../src/index';
import type { RouteDecorator } from '../src/metadata';
type Decl = [RouteDecorator, string];
/** One controller with a handler per declaration, `h0`, `h1`, … in order, each echoing its params. */
function moduleWith(decls: Decl[], options?: { export: boolean }) {
class Routes {}
decls.forEach(([decorator, path], index) => {
const name = `h${index}`;
Object.defineProperty(Routes.prototype, name, {
value: (p: Record<string, string>) => ({ route: name, params: p }),
configurable: true,
});
param()(Routes.prototype, name, 0);
(options ? decorator(path, options) : decorator(path))(
Routes.prototype,
name,
Object.getOwnPropertyDescriptor(Routes.prototype, name)!,
);
});
Route('/')(Routes);
class RoutesModule {}
Module({ mountpoint: '/', controllers: [Routes] })(RoutesModule);
return RoutesModule;
}
const boot = (decls: Decl[]) => createApp({ modules: [moduleWith(decls)] });
const bootError = (decls: Decl[]): string => {
try {
boot(decls);
} catch (error) {
return (error as Error).message;
}
throw new Error('expected the app to refuse to boot');
};
async function get(app: ReturnType<typeof createApp>, path: string) {
const res = await app.fetch(new Request(`http://x${path}`));
return res.json();
}
describe('CARD-13: constrained params that can never be reached, or tie with a sibling', () => {
it('T1: GET /algo/:id + GET /algo/:a(.*) boots — `.` leaves line terminators to :id', async () => {
// The card expected `:id` to be unreachable. It is not: without the `s` flag `.` excludes line
// terminators, so a segment such as `%0A` fails `(.*)` and lands on `:id`. Refusing to boot would
// claim something false about the router.
const app = boot([
[Get, '/algo/:id'],
[Get, '/algo/:a(.*)'],
]);
expect(await get(app, '/algo/x')).toEqual({ route: 'h1', params: { a: 'x' } });
expect(await get(app, '/algo/%0A')).toEqual({ route: 'h0', params: { id: '\n' } });
});
it('T1 (every segment): GET /algo/:id + GET /algo/:a([^]*) fails, naming both', () => {
expect(
bootError([
[Get, '/algo/:id'],
[Get, '/algo/:a([^]*)'],
]),
).toBe(
'unreachable route GET /algo/:id at Routes.h0: GET /algo/:a([^]*) at Routes.h1 matches every request it would, ' +
'and wins each one — its constraint accepts every segment, and a constrained parameter outranks a plain one. ' +
'Remove one of them, or narrow the constraint',
);
});
it('T2: GET /u/:id(\\d+) + GET /u/:n(\\d{1,3}) fails with a witness', () => {
expect(
bootError([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:n(\\d{1,3})'],
]),
).toBe(
"ambiguous route GET /u/:n(\\d{1,3}) at Routes.h1 conflicts with GET /u/:id(\\d+) at Routes.h0: both match '0' " +
'(GET /u/0), so only declaration order would choose between them — give the constraints disjoint languages, ' +
'or merge the routes',
);
});
it('T3: equivalent sources — GET /u/:id(\\d+) + GET /u/:id([0-9]+) fails', () => {
expect(
bootError([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:id([0-9]+)'],
]),
).toMatch(
/^ambiguous route GET \/u\/:id\(\[0-9\]\+\) at Routes\.h1 conflicts with GET \/u\/:id\(\\d\+\) .*both match '0'/,
);
});
it('T4: GET /u/:id(\\d+) + GET /u/:slug boots, and routing is unchanged', async () => {
for (const order of [
[
[Get, '/u/:id(\\d+)'],
[Get, '/u/:slug'],
],
[
[Get, '/u/:slug'],
[Get, '/u/:id(\\d+)'],
],
] as Decl[][]) {
const app = boot(order);
const idRoute = order[0][1].includes('(') ? 'h0' : 'h1';
const slugRoute = idRoute === 'h0' ? 'h1' : 'h0';
expect(await get(app, '/u/42')).toEqual({ route: idRoute, params: { id: '42' } });
expect(await get(app, '/u/bob')).toEqual({ route: slugRoute, params: { slug: 'bob' } });
}
});
it('T5: disjoint constraints — GET /u/:id(\\d+) + GET /u/:s([a-z]+) boots', () => {
expect(() =>
boot([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:s([a-z]+)'],
]),
).not.toThrow();
});
it('T6: different methods — GET /u/:id(\\d+) + POST /u/:n(\\d{1,3}) boots', () => {
expect(() =>
boot([
[Get, '/u/:id(\\d+)'],
[Post, '/u/:n(\\d{1,3})'],
]),
).not.toThrow();
});
it('T7: WS /r/:id + WS /r/:a(.*) fails — WebSocket routes match in declaration order', () => {
expect(
bootError([
[Ws, '/r/:id'],
[Ws, '/r/:a(.*)'],
]),
).toBe(
'unreachable route WS /r/:a(.*) at Routes.h1: WS /r/:id at Routes.h0 matches every request it would, and wins ' +
'each one — WebSocket routes are matched in declaration order, and it is declared first. Remove one of them, ' +
'or narrow the constraint',
);
});
it('T7 (more): WS follows rule 2, and only its own table', () => {
expect(
bootError([
[Ws, '/r/:id(\\d+)'],
[Ws, '/r/:n(\\d{1,3})'],
]),
).toMatch(/^ambiguous route WS \/r\/:n.*both match '0' \(WebSocket \/r\/0\)/);
// A WS route and an HTTP GET are different tables: an upgrade never reaches the HTTP route.
expect(() =>
boot([
[Ws, '/r/:id'],
[Get, '/r/:a([^]*)'],
]),
).not.toThrow();
// `@Stream` (negotiate) is served from both tables, so it is checked under both precedences.
expect(
bootError([
[Stream, '/s/:id'],
[Ws, '/s/:a(\\d+)'],
]),
).toMatch(/^unreachable route WS \/s\/:a\(\\d\+\) at Routes\.h1: GET \/s\/:id at Routes\.h0/);
});
it('T9: {0,2048} against {0,2048} at boot — result and time', () => {
const started = performance.now();
expect(
bootError([
[Get, '/t/:a(\\d{0,2048})'],
[Get, '/t/:b([0-9]{0,2048})'],
]),
).toMatch(/both match '0' \(GET \/t\/0\)/);
expect(() =>
boot([
[Get, '/t/:a(\\d{0,2048})'],
[Get, '/t/:b([a-z]{0,2048})'],
]),
).not.toThrow();
expect(() =>
boot([
[Get, `/w/:a(${'\\d{0,2048}'.repeat(12)}a)`],
[Get, `/w/:b(${'[0-9]{0,2048}'.repeat(9)}b)`],
]),
).not.toThrow();
expect(performance.now() - started).toBeLessThan(5000);
});
});
// ── T8: mesh ─────────────────────────────────────────────────────────────────────────────────────
const SECRET = 'card-13-secret';
const controlUrl = (server: { address(): unknown }) =>
`ws://127.0.0.1:${(server.address() as { port: number }).port}/__mesh__/control`;
async function teacupWith(teapots: Decl[][], local: Decl[] = [[Get, '/c/ok']]) {
const servers = await Promise.all(
teapots.map((decls) =>
createApp({
modules: [moduleWith(decls, { export: true })],
experimental: true,
mesh: { secret: SECRET },
}).listen(0),
),
);
const teacup = createApp({
modules: [moduleWith(local)],
experimental: true,
mesh: { teapots: servers.map((server) => ({ url: controlUrl(server), secret: SECRET })) },
});
return {
teacup,
urls: servers.map(controlUrl),
close: async () => {
await teacup.close();
servers.forEach((server) => server.close());
},
};
}
describe('CARD-13 T8: the same check between remote siblings', () => {
it("T8: two teapots exporting T2's pair refuse to boot the teacup", async () => {
const { teacup, urls, close } = await teacupWith([[[Get, '/u/:id(\\d+)']], [[Get, '/u/:n(\\d{1,3})']]]);
try {
await expect(teacup.ready()).rejects.toThrow(
`mesh: ambiguous remote route 'GET /u/:n(\\d{1,3})' from ${urls[1]} conflicts with 'GET /u/:id(\\d+)' ` +
`from ${urls[0]}: both match '0' (GET /u/0) — green-tea will not choose one for you. ` +
'Export only one of them, or give their constraints disjoint languages.',
);
} finally {
await close();
}
});
it('an unreachable remote sibling refuses to boot too', async () => {
const { teacup, close } = await teacupWith([[[Get, '/v/:id']], [[Get, '/v/:a([^]+)']]]);
try {
await expect(teacup.ready()).rejects.toThrow(
/^mesh: unreachable remote route 'GET \/v\/:id' from .*'GET \/v\/:a\(\[\^\]\+\)'/,
);
} finally {
await close();
}
});
it('a fallback pair across teapots boots and routes as before', async () => {
const { teacup, close } = await teacupWith([[[Get, '/u/:id(\\d+)']], [[Get, '/u/:slug']]]);
try {
expect(await get(teacup, '/u/42')).toEqual({ route: 'h0', params: { id: '42' } });
expect(await get(teacup, '/u/bob')).toEqual({ route: 'h0', params: { slug: 'bob' } });
} finally {
await close();
}
});
it('local against remote keeps the deliberate local override: no new error', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { teacup, close } = await teacupWith([[[Get, '/u/:n(\\d{1,3})']]], [[Get, '/u/:id(\\d+)']]);
try {
expect(await get(teacup, '/u/7')).toEqual({ route: 'h0', params: { id: '7' } });
} finally {
warn.mockRestore();
await close();
}
});
});
+296
View File
@@ -0,0 +1,296 @@
/**
* The decision procedure behind CARD-13 (#127): constraint atoms read back as character sets,
* intersection with a witness, "accepts every segment", and the route-level definitions.
*
* Every answer is checked against the RegExp engine itself, which is the router's ground truth: atom
* sets code point by code point, witnesses by matching them, and the product walk against brute-force
* enumeration over short strings (fixed seed).
*/
import { describe, it, expect } from 'vitest';
import { compilePattern } from '../src/http/router';
import {
acceptsEverySegment,
atomSet,
constraintBlocks,
intersectionWitness,
routeConflict,
type CharSet,
type Precedence,
} from '../src/http/route-conflicts';
const engine = (source: string) => new RegExp(`^(?:${source})$`, 'u');
/** What the router can hand a param: non-empty, and never `.` or `..` (normalization resolves them). */
const inUniverse = (segment: string) => segment.length > 0 && segment !== '.' && segment !== '..';
function inSet(set: CharSet, cp: number): boolean {
for (let i = 0; i < set.length; i += 2) if (cp >= set[i] && cp <= set[i + 1]) return true;
return false;
}
/** All of the BMP but surrogates, a stride through the astral planes, and every range edge ± 1. */
function probes(set: CharSet): number[] {
const out: number[] = [];
for (let cp = 0; cp <= 0xffff; cp++) if (cp < 0xd800 || cp > 0xdfff) out.push(cp);
for (let cp = 0x10000; cp <= 0x10ffff; cp += 97) out.push(cp);
for (const edge of set) out.push(edge - 1, edge, edge + 1);
return out.filter((cp) => cp >= 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff));
}
const ATOMS = [
'\\d',
'\\D',
'\\w',
'\\W',
'\\s',
'\\S',
'.',
'\\.',
'a',
'_',
'-',
'[a-z]',
'[^a-z]',
'[^]',
'[\\s\\S]',
'[\\d\\-x]',
'[-a]',
'[a-]',
'[^.]',
'[\\u0041-\\u005A]',
'[\\u{1F600}-\\u{1F602}]',
'[\\uD83D\\uDE00]',
'[\\x00-\\x1f]',
'[\\b\\cJ\\0\\t]',
'[\\]\\[\\\\\\/]',
'[😀-😂]',
'[\\p{L}]',
'[^\\P{Nd}]',
];
describe('constraint atoms read back as character sets', () => {
it.each(ATOMS)('%s matches exactly what the engine matches', (atom) => {
const set = atomSet(atom);
const test = engine(atom);
const wrong = probes(set).filter((cp) => inSet(set, cp) !== test.test(String.fromCodePoint(cp)));
expect(wrong.slice(0, 5)).toEqual([]);
});
it('an unescaped dot is not every character: line terminators are outside it', () => {
// Without the `s` flag, `.` excludes \n, \r, U+2028 and U+2029 — so `(.*)` does not cover every
// segment, and `/algo/%0A` still reaches a plain sibling. This is the router's real behaviour.
const dot = atomSet('.');
expect([0x0a, 0x0d, 0x2028, 0x2029].map((cp) => inSet(dot, cp))).toEqual([false, false, false, false]);
expect(acceptsEverySegment(constraintBlocks('.*'))).toBe(false);
expect(acceptsEverySegment(constraintBlocks('[^]*'))).toBe(true);
});
});
describe('acceptsEverySegment', () => {
it.each([
['[^]*', true],
['[^]+', true],
['[\\s\\S]*', true],
['[\\s\\S]{0,4}[^]*', true],
['[^]?[^]*', true],
['a?[^]*', true],
['[^][^]+', false], // needs two characters: `a` is a segment
['a[^]*', false], // a mandatory block narrower than Σ
['[^]{0,2048}', false], // bounded
['.*', false],
['\\S+', false],
['[a-z]*[^]{1,2048}', false],
])('%s → %s', (source, expected) => {
expect(acceptsEverySegment(constraintBlocks(source))).toBe(expected);
});
});
// ── property: the product walk against brute force ───────────────────────────────────────────────
/** mulberry32, fixed seed: the generated pairs are the same on every run. */
function rng(seed: number) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const SEED = 13127;
const GEN_ATOMS = [
'\\d',
'\\D',
'\\w',
'\\s',
'\\S',
'.',
'\\.',
'a',
'0',
'-',
'[a-c]',
'[^0-9]',
'[.a]',
'[^.]',
'[^]',
];
const GEN_QUANTIFIERS = ['', '', '?', '*', '+', '{0,2}', '{1,3}', '{2}', '{1,}'];
const PROBE_CHARS = ['0', '5', 'a', 'c', 'Z', '.', '-', '_', ' ', '\n', 'é', '😀', '/'];
function randomConstraint(next: () => number): string | undefined {
const pick = <T>(list: T[]) => list[Math.floor(next() * list.length)];
const atoms = 1 + Math.floor(next() * 3);
let source = '';
for (let i = 0; i < atoms; i++) source += pick(GEN_ATOMS) + pick(GEN_QUANTIFIERS);
try {
compilePattern(`/p/:x(${source})`); // only what the router accepts
return source;
} catch {
return undefined;
}
}
function shortStrings(maxLength: number): string[] {
let level = [''];
const out: string[] = [];
for (let length = 1; length <= maxLength; length++) {
level = level.flatMap((prefix) => PROBE_CHARS.map((c) => prefix + c));
out.push(...level);
}
return out.filter(inUniverse);
}
describe('intersectionWitness', () => {
const STRINGS = shortStrings(3);
it(`agrees with brute force over short strings (seed ${SEED})`, () => {
const next = rng(SEED);
let pairs = 0;
let intersecting = 0;
while (pairs < 300) {
const a = randomConstraint(next);
const b = randomConstraint(next);
if (!a || !b) continue;
pairs++;
const witness = intersectionWitness(constraintBlocks(a), constraintBlocks(b));
const [ra, rb] = [engine(a), engine(b)];
const brute = STRINGS.find((s) => ra.test(s) && rb.test(s));
// Sound: a witness is a real segment both accept.
if (witness !== undefined) {
intersecting++;
expect({ a, b, witness, ok: inUniverse(witness) && ra.test(witness) && rb.test(witness) }).toMatchObject({
ok: true,
});
}
// Complete: anything brute force finds, the walk finds too.
if (brute !== undefined) expect({ a, b, brute, found: witness !== undefined }).toMatchObject({ found: true });
}
// Both outcomes are exercised, not just one.
expect(intersecting).toBeGreaterThan(30);
expect(pairs - intersecting).toBeGreaterThan(30);
});
it.each([
['\\d+', '\\d{1,3}', '0'],
['\\d+', '[0-9]+', '0'],
['\\d+', '[a-z]+', undefined],
['\\d{2}', '\\d{3}', undefined],
['a\\d{2}', '\\w{3}', 'a00'],
['\\.', '[.]', undefined], // only `.`, which normalization removes
['\\.{1,2}', '[.]+', undefined], // `.` and `..` only
['\\.+', '[.]{2,5}', '...'],
['[^]{3}', '\\D\\d', undefined],
['[^]{3}', '\\D\\d-', 'a0-'],
['\\d{0,2048}', '[0-9]{0,2048}', '0'],
['\\d{0,2048}', '[a-z]{0,2048}', undefined],
['\\d{2048}', '\\d{0,2047}', undefined],
])('%s ∩ %s → %s', (a, b, expected) => {
const witness = intersectionWitness(constraintBlocks(a), constraintBlocks(b));
expect(witness).toBe(expected);
if (witness !== undefined) expect(engine(a).test(witness) && engine(b).test(witness)).toBe(true);
});
it('T9: {0,2048} against {0,2048}, and the largest product the grammar allows, stay well inside boot time', () => {
// A {0,2048} block is 10 source characters, so 12 fill the 128-character limit. The trailing
// `a` / `b` makes the intersection empty, so the walk must visit every reachable state.
const worstA = constraintBlocks('\\d{0,2048}'.repeat(12) + 'a');
const worstB = constraintBlocks('[0-9]{0,2048}'.repeat(9) + 'b');
const started = performance.now();
expect(intersectionWitness(constraintBlocks('\\d{0,2048}'), constraintBlocks('[0-9]{0,2048}'))).toBe('0');
expect(intersectionWitness(worstA, worstB)).toBeUndefined();
// Measured at ~0.1 ms and ~100 ms on an M-series laptop; the bound only guards against a
// regression to the exponential or quadratic-per-value walk.
expect(performance.now() - started).toBeLessThan(5000);
});
});
// ── route level ──────────────────────────────────────────────────────────────────────────────────
const conflict = (a: string, b: string, precedence: Precedence = 'specificity') =>
routeConflict(compilePattern(a), compilePattern(b), precedence);
describe('routeConflict', () => {
it.each([
// Rule 1: a constraint that accepts every segment outranks a plain sibling, whatever the order.
['/algo/:id', '/algo/:a([^]*)', { kind: 'unreachable', loser: 0 }],
['/algo/:a([\\s\\S]+)', '/algo/:id', { kind: 'unreachable', loser: 1 }],
['/algo/:id', '/algo/:a(.*)', undefined], // `.` leaves line terminators to `:id`
// Rule 2, with the whole-pattern condition.
['/u/:id(\\d+)', '/u/:n(\\d{1,3})', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/u/:id(\\d+)', '/u/:id([0-9]+)', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/b', undefined],
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/:x', { kind: 'ambiguous', segment: '0', path: '/u/0/a' }],
['/u/:id(\\d+)/:r*', '/u/:n(\\d{1,3})/x/y', { kind: 'ambiguous', segment: '0', path: '/u/0/x/y' }],
['/u/:id(\\d+)', '/u/:n(\\d{1,3})/:r*', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/:p([a-z]+)/:id(\\d+)', '/:p([a-z]+)/:n(\\d{2})', { kind: 'ambiguous', segment: '00', path: '/a/00' }],
// Rule 3 and other non-errors.
['/u/:id(\\d+)', '/u/:slug', undefined],
['/u/:id(\\d+)', '/u/:s([a-z]+)', undefined],
['/u/me', '/u/:id(me)', undefined], // a static is not a sibling param: `/u/%6De` still reaches `:id`
['/x/:a/:id(\\d+)', '/x/s/:n([0-9]+)', undefined], // different radix nodes: the static decides
['/a/:id', '/a/:x([^]*)/:r*', undefined], // an exact route outranks a catch-all one
// Rule 1 needs the rest included, segment by segment.
['/a/:x([^]+)/b', '/a/:id/c', undefined],
['/a/:x([^]+)/:y', '/a/:id/c', { kind: 'unreachable', loser: 1 }],
['/a/:x([^]+)/:y/:r*', '/a/:id/c/:s*', { kind: 'unreachable', loser: 1 }],
['/a/:x([^]+)/:r*', '/a/:id/c/d', undefined], // the exact route outranks the catch-all one
['/a/:x([^]+)/:y(\\d+)', '/a/:id/:z(\\d+)', { kind: 'unreachable', loser: 1 }],
// Different constraints at a later position are not compared, so this boots (documented limit).
['/a/:x([^]+)/:y(\\d+)', '/a/:id/:z([0-9]+)', undefined],
])('%s vs %s', (a, b, expected) => {
expect(conflict(a, b)).toEqual(expected);
});
it('WebSocket precedence is declaration order', () => {
expect(conflict('/r/:id', '/r/:a(.*)', 'registration')).toEqual({ kind: 'unreachable', loser: 1 });
expect(conflict('/r/:slug', '/r/:id(\\d+)', 'registration')).toEqual({ kind: 'unreachable', loser: 1 });
expect(conflict('/r/:id(\\d+)', '/r/:slug', 'registration')).toBeUndefined();
expect(conflict('/r/:id(\\d+)', '/r/:n(\\d{1,3})', 'registration')).toMatchObject({ kind: 'ambiguous' });
});
it('every ambiguous witness path is a request both routes really match', async () => {
const { matchPattern } = await import('../src/http/router');
const pairs: Array<[string, string]> = [
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/:x'],
['/v/:a([^a-z]+)', '/v/:b(\\s)'],
['/w/:a([%x]{2})', '/w/:b(\\W+)'],
['/k/:a(\\.+)', '/k/:b([.]{2,5})'],
];
for (const [a, b] of pairs) {
const found = conflict(a, b);
expect(found?.kind).toBe('ambiguous');
const path = (found as { path: string }).path;
expect([a, path, matchPattern(a, path)]).not.toContain(undefined);
expect([b, path, matchPattern(b, path)]).not.toContain(undefined);
}
});
});
+152
View File
@@ -0,0 +1,152 @@
/**
* The radix index's own seams, which the frozen parity corpus (test/router-parity/) cannot reach:
*
* - The local/remote split. The corpus drives the matcher with flat arrays, so every scenario lands
* in the local tree; only the app-level mesh captures reach the remote one. Here every frozen
* scenario is replayed with its declarations spread across both trees, and must still answer
* exactly as the oracle does on the same flat array.
* - Index lifetime: an array that changes length after its index was built is never served stale.
*/
import { describe, it, expect } from 'vitest';
import * as live from '../src/http/router';
import type { RouteDef } from '../src/http/types';
import { buildFetch } from '../src/http/web';
import * as oracle from './router-parity/oracle';
import { runScenario, type MatcherImpl, type Scenario } from './router-parity/matcher';
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './router-parity/cases';
import { generateScenarios, generateScenariosV2 } from './router-parity/generator';
const SCENARIOS: Scenario[] = [...HAND_SCENARIOS, ...OWNER_SCENARIOS, ...generateScenarios(), ...generateScenariosV2()];
/** Which positions of the declaration array go to the remote tree. */
const SPLITS: Record<string, (index: number, length: number) => boolean> = {
'all remote': () => true,
'second half remote': (index, length) => index >= length / 2,
'odd positions remote': (index) => index % 2 === 1,
// Not a shape mesh produces (remote routes are spliced after local ones), but the tie rule is
// array order either way, so the answer must not depend on it.
'first half remote': (index, length) => index < length / 2,
};
/** The live router, with some declarations marked remote before the first lookup builds the index. */
function splitImpl(isRemote: (index: number, length: number) => boolean): MatcherImpl {
const mark = (routes: RouteDef[]): RouteDef[] => {
routes.forEach((route, index) => isRemote(index, routes.length) && live.markRemoteRoute(route));
return routes;
};
return {
normalizeRequestPath: live.normalizeRequestPath,
matchRoute: (routes, method, path) => live.matchRoute(mark(routes), method, path),
resolveRoute: (routes, method, path) => live.resolveRoute(mark(routes), method, path),
allowedMethods: (routes, path) => live.allowedMethods(mark(routes), path),
};
}
function route(method: string, pattern: string, transport: RouteDef['transport'] = 'buffer'): RouteDef {
return { method, pattern, transport, handler: async () => ({ status: 200, headers: {}, body: pattern }) };
}
describe('radix index: local and remote trees', () => {
for (const [name, isRemote] of Object.entries(SPLITS)) {
it(`answers every frozen scenario like the flat oracle — ${name}`, () => {
const impl = splitImpl(isRemote);
for (const scenario of SCENARIOS) {
expect(runScenario(impl, scenario), scenario.id).toEqual(runScenario(oracle, scenario));
}
});
}
it('lets a remote static route outrank a local param route, and a local twin win a tie', () => {
const localParam = route('GET', '/items/:id');
const localTwin = route('GET', '/items/special');
const remoteStatic = live.markRemoteRoute(route('GET', '/items/special'));
const remoteOnly = live.markRemoteRoute(route('GET', '/items/other'));
expect(live.matchRoute([localParam, remoteStatic, remoteOnly], 'GET', '/items/other')?.def).toBe(remoteOnly);
expect(live.matchRoute([localParam, remoteStatic], 'GET', '/items/special')?.def).toBe(remoteStatic);
expect(live.matchRoute([localParam, localTwin, remoteStatic], 'GET', '/items/special')?.def).toBe(localTwin);
});
it('breaks a cross-tree tie by array position, so a later dev route never shadows a remote one', () => {
const remote = live.markRemoteRoute(route('GET', '/__dev'));
const dev = route('GET', '/__dev');
expect(live.matchRoute([remote, dev], 'GET', '/__dev')?.def).toBe(remote);
});
it('builds Allow and implicit HEAD over the union of both trees', () => {
const local = route('POST', '/a/:id');
const remoteGet = live.markRemoteRoute(route('GET', '/a/:id'));
const routes = [local, remoteGet];
expect(live.allowedMethods(routes, '/a/1')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
expect(live.resolveRoute(routes, 'HEAD', '/a/1')).toMatchObject({ def: remoteGet, implicitHead: true });
});
it('passes over a higher-ranked streaming GET in one tree for a buffered GET in the other', () => {
const stream = route('GET', '/s/live', 'sse');
const buffered = live.markRemoteRoute(route('GET', '/s/:name'));
expect(live.resolveRoute([stream, buffered], 'HEAD', '/s/live')).toMatchObject({
def: buffered,
params: { name: 'live' },
implicitHead: true,
});
});
});
describe('radix index: ranking across branches', () => {
it('lets an exact param route beat a catch-all the walk reached first through a static branch', () => {
// The static branch is walked first and yields the catch-all (rank 1); the param sibling still
// holds the rank-0 exact route, so pruning must not cut it, even by one.
for (const order of [
['/a/:rest*', '/:x/b'],
['/:x/b', '/a/:rest*'],
]) {
const routes = order.map((pattern) => route('GET', pattern));
const expected = oracle.matchRoute(routes, 'GET', '/a/b');
expect(expected?.def.pattern).toBe('/:x/b');
expect(live.matchRoute(routes, 'GET', '/a/b')).toEqual(expected);
}
});
});
describe('radix index: deep paths', () => {
it('matches a param under 4,999 static segments without overflowing the call stack', async () => {
// Every static segment is one walk frame, so a recursive walk throws RangeError here.
const prefix = '/s'.repeat(4999);
const routes = [route('GET', `${prefix}/:x`)];
const path = `${prefix}/a`;
const expected = oracle.matchRoute(routes, 'GET', path);
expect(expected?.params).toEqual({ x: 'a' });
expect(live.matchRoute(routes, 'GET', path)).toEqual(expected);
const res = await buildFetch(routes, undefined)(new Request(`http://x${path}`));
expect(res.status).toBe(200);
expect(await res.text()).toBe(`${prefix}/:x`);
});
});
describe('radix index: malformed paths', () => {
it('leaves no frames on the shared walk stack when a segment fails to decode', () => {
// `/:rest*` pushes a pending catch-all frame before `/:id` decodes `%GG` and throws.
const routes = [route('GET', '/:id'), route('GET', '/:rest*')];
for (let i = 0; i < 3; i++) expect(() => live.matchRoute(routes, 'GET', '/%GG')).toThrow(URIError);
expect(live.walkStackSize()).toBe(0);
expect(live.matchRoute(routes, 'GET', '/a')?.params).toEqual({ id: 'a' });
});
});
describe('radix index: lifetime', () => {
it('rebuilds when the array it was built from changes length', () => {
const routes = [route('GET', '/a')];
expect(live.matchRoute(routes, 'GET', '/b')).toBeUndefined();
const added = route('GET', '/b');
routes.push(added);
expect(live.matchRoute(routes, 'GET', '/b')?.def).toBe(added);
expect(live.allowedMethods(routes, '/b')).toEqual(['GET', 'HEAD', 'OPTIONS']);
routes.pop();
expect(live.matchRoute(routes, 'GET', '/b')).toBeUndefined();
});
});
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more