Author SHA1 Message Date
chrnx fe4827ccb3 perf(compression): send no Vary on a body under the threshold
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 22s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 33s
A buffered body under the threshold is sent identity whatever the client
accepts, so Accept-Encoding played no part in it and RFC 9110 asks for
no Vary. A cache that stores it for everyone is right to: every client
accepts identity. Responses that are encoded, or that are identity for
a request-side reason (identity client, HEAD), and every 304 keep Vary,
as does every compressible edge response, since Cloudflare encodes
there.

Deno pays about 10% of a small request for the header, Bun about 3%.
The size is also measured with Buffer.byteLength instead of allocating
the bytes, which are now built only when the body is encoded.

Measured on the Mac, hello with compression on against compression off:
Deno -17% -> -2%, Bun -7% -> -3%.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 22:39:06 -05:00
chrnx e8842e6e06 perf(compression): decide eligibility in one pass over the headers
eligible() read four headers through findHeader, each an Object.keys and
a toLowerCase per key, then ran two regexes, on every response while
compression is on. It now walks the keys once, keeps the first value of
each name as findHeader did, memoizes the content-type decision for the
last type seen, and tests no-transform only when cache-control is set.

Measured on Deno, hello with compression on (under the threshold): +2-5%.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 22:33:54 -05:00
chrnx 1935e8e047 Merge pull request 'perf(app): skip awaiting the boot in app.fetch once it has finished' (#178) from perf/fetch-skip-boot-await into develop
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 22s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 20s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 33s
2026-10-29 03:06:35 +00:00
chrnx d51ff3bee4 perf(app): skip awaiting the boot in app.fetch once it has finished
CI / dco (pull_request) Successful in 5s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (bun) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 23s
trackHealth wraps the memoized boot in an async function, so every
app.fetch request paid a new promise and microtask hops awaiting a boot
that had already settled. A built route table means the boot succeeded,
so the fetch handler now goes straight to it; only requests before the
table exists await the boot. A failed boot still rejects every request,
because the table is never built.

Measured in-process on Deno (app.fetch in a loop, param route): about
+3-6%.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 20:31:18 -05:00
chrnx 068614ef11 Merge pull request 'docs: bring the contributor docs and examples in line with the repository' (#177) from docs/repo-docs-refresh into develop
CI / runtimes (edge) (push) Successful in 23s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 21s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 34s
2026-10-28 19:37:16 +00:00
chrnx 02f0473bfc docs: bring the contributor docs and examples in line with the repository
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 22s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (bun) (pull_request) Successful in 21s
CONTRIBUTING said none of the Deno, Bun or edge suites run in CI. They do:
the runtimes job runs all three on every push and gates a merge. It now
says so, names test:all, and lists the audit step CI runs.

The README's benchmark section quoted a ranking against Fastify that went
stale with the next measurement. It now explains what the harness measures
and why, and leaves every number to BENCHMARKS.md. The install section
states the Node 22 floor and that Node 18 and 20 are not supported.

The PR template asks which runtime suites were run. The example README
pointed at ts-node, which is not a dependency, and a dist path tsup never
builds; it now runs each example with tsx. example/server.ts crashed at
boot because its teacup lacked experimental: true.

docs/plans held agent implementation plans from August and September.
Those belong in .specs/, which is not committed, so they leave the
repository. The three places that linked the mesh degrade plan now
describe the planned expects list instead.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 14:35:01 -05:00
chrnx 4e4553cdc8 Merge pull request 'perf(http): resolve ctx.ip on first read instead of on every request' (#176) from perf/lazy-ctx-ip into develop
CI / dco (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 23s
CI / runtimes (deno) (push) Successful in 34s
CI / build (push) Successful in 29s
2026-10-28 19:34:48 +00:00
chrnx b86cd605c4 perf(http): resolve ctx.ip on first read instead of on every request
CI / runtimes (bun) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / build (pull_request) Successful in 30s
Every Bun request called server.requestIP() for ctx.ip (#116), a native
call that builds an object, whether anything read the address or not. On
Mac that measured 7-11% of a small request; recording the server in the
peer map instead costs nothing.

The neutral request now carries a resolver rather than an address. The
handler request and the pipeline seed expose ctx.ip as an accessor that
resolves once on first read, and a step may still assign it. runPipeline
uses the seed it is given instead of spreading it, which would have
evaluated the accessor; both callers build the seed fresh per request.

Inside a stream body ctx.ip is '' unless a step or the handler read it
before the stream was returned: the body runs after the response has
started, when the socket may be gone.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 14:31:20 -05:00
chrnx 109297ca4c Merge pull request 'perf(http): recover the fetch adapter's per-request cost on Deno and Bun' (#175) from perf/web-headers-fast-path into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 22s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 33s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (edge) (push) Successful in 23s
2026-10-28 19:31:13 +00:00
chrnx 133af8dfe5 perf(http): read a declared-length fetch body with arrayBuffer()
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 32s
CI / build (pull_request) Successful in 29s
The chunked reader added for the incremental 413 (4d1639f) cut a Bun JSON
POST by more than half: 37.6k -> 11.7k req/s on jarvis. A well-formed
Content-Length inside the limit already bounds the body, because the
runtime frames it by that header, so arrayBuffer() is safe there and native
in Bun, Deno and workerd. byteLength is still checked for a Request built in
user code whose header and body disagree. Chunked uploads keep the bounded
read.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-27 22:35:06 -05:00
chrnx 5b2143fcb7 perf(http): hand plain-string response headers to the fetch Response as a record
toWebHeaders copied every response's headers into a Headers object one by
one, so set-cookie arrays survive. Deno and Bun build native headers from a
record directly, and the JS copy cost 5-8% on every Deno request (bisected to
50010da). A record holding only strings is now returned as it is; anything
else still goes through Headers.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-27 22:35:03 -05:00
chrnx 9648a9d1ed Merge pull request 'perf(http): trim per-request work on the Node path' (#174) from perf/node-request-path into develop
CI / runtimes (bun) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 33s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 23s
2026-10-27 08:03:09 +00:00
chrnx d626fadbfd docs(changelog): note the bodiless-request fast path
CI / runtimes (deno) (pull_request) Successful in 34s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 22s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-27 00:31:50 -05:00
chrnx 88be9b1cb2 perf(http): skip the body stream for a request without a body
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 32s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 21s
On Node every request goes through readBody, GET included. Subscribing
listeners to an empty request stream measured ~4% slower than the old
async iterator on an 8 KB GET response, in both orders on jarvis.

A request with no Transfer-Encoding and no or a zero Content-Length has
no body (RFC 9112 6.3), so resolve undefined without touching the
stream. Node drains the unread request when the response ends.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-26 22:48:15 -05:00
chrnx 704622cf65 bench(compare): add compression cases to the A/B harness
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 23s
The A/B harness had no case with compression on, so a change to the
response write path was measured only on its uncompressed branch. Add an
8 KB JSON response uncompressed, identity-negotiated, gzip and br, plus a
small response under the threshold with compression enabled.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-26 13:24:14 -05:00
chrnx 8b67b1a46c perf(http): trim per-request work on the Node path
CI / runtimes (bun) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 32s
Profiling the validate (POST) bench route against 4d1639f showed the
loss since then spread over several small costs on the Node request
path rather than one regression. This removes the ones that do not
change behaviour:

- readBody reads with data/end/error/close listeners instead of
  `for await`, whose async iterator costs a promise and a microtask per
  chunk. It keeps the iterator's semantics: the running total enforces
  the limit, an over-limit body destroys the request as leaving the loop
  did, an error or a close before `end` rejects (the latter with
  ERR_STREAM_PREMATURE_CLOSE), and the declared-length 413 is still a
  rejection rather than a synchronous throw. A single chunk is returned
  without Buffer.concat.
- writeResult is no longer async. A buffered response without
  compression is written synchronously and returns nothing to await;
  only a stream or a compressed body returns a promise, which serve
  awaits, so a failure still reaches failSafe. The compression request
  object is not built when compression is off.
- declaresOverLimit compares the number first and runs its /^\d+$/
  shape test only when the length is over the limit.

The `serve().catch(failSafe)` wrapper stays: it is the #108 guarantee,
and handle() is asynchronous, so there is no synchronous path to skip.

Local A/B against 74faa55 (5 s x 4 rounds, macOS, indicative only):
validate (POST) +4.6%. test/read-body.test.ts pins readBody's
semantics: joining, empty body, 413 with destroy, declared-length 413,
stream error and premature close.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-26 08:02:03 -05:00
chrnx 74faa55f41 Merge pull request 'fix(build): let the npm ESM build load on workerd (#93)' (#173) from fix/edge-esm-no-create-require into develop
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 30s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 23s
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 32s
2026-10-25 03:54:14 +00:00
chrnx b7a852ac92 fix(build): let the npm ESM build load on workerd (#93)
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (bun) (pull_request) Successful in 19s
tsup.config.ts gives every ESM output a banner that calls
createRequire(import.meta.url) at module scope, so the lazy
require('ws') / require('busboy') resolve. On workerd import.meta.url
is not a file URL: createRequire throws during module evaluation and
the worker fails to start. dist/edge.mjs, and the chunk it shares with
the other entry points, could therefore not be loaded from npm at all.
test/edge/run.ts bundles src/, which has no banner, so it never saw it.

The banner now wraps the call in a try and leaves `require` undefined
when it throws. esbuild's __require shim and src/node-require.ts
already handle an undefined require: the latter falls back to
process.getBuiltinModule, and its callers report a missing module in
their own terms. The static node:module import is kept: edge already
requires nodejs_compat, which provides it, and dropping it for
getBuiltinModule would lose Node 22.0-22.2, which lack that API.
Building edge separately was ruled out because it would duplicate
module state (MARK_EDGE) between @green-tea/core and its /edge entry.

test/edge/dist.ts bundles a worker that imports dist/index.mjs and
dist/edge.mjs, as wrangler does with the installed package, and serves
a request on Miniflare. It fails with the old banner and passes now.
npm run test:edge builds before running it, so CI's edge job covers it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:52:07 -05:00
chrnx dd3a74afcd Merge pull request 'fix(transformers)!: answer 204 when a handler returns undefined (GitHub #38)' (#172) from fix/undefined-return-204 into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 32s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 32s
2026-10-25 03:51:58 +00:00
chrnx 40702aef2a fix(transformers)!: answer 204 when a handler returns undefined (GitHub #38)
CI / runtimes (edge) (pull_request) Successful in 21s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / build (pull_request) Successful in 29s
JsonTransformer passed the handler's value to JSON.stringify, which
returns undefined for undefined, while TransformerFn promises a string
body. The Node server wrote that as an empty 200 with content-type
application/json; the fetch adapter's toBodyInit read `body.buffer` on
it and threw, so Deno, Bun and the edge answered 500 for a handler with
no `return`.

JsonTransformer now returns status 204 and an empty body (no headers)
for undefined. outcomeToResponse already sends a null body for 204 and
the Node server ends with the empty string, so all four runtimes give
the same answer. null is a JSON value and still renders as 200 `null`.
Routes with their own @Transformer are unchanged.

BREAKING CHANGE: a handler with no return value now answers 204 instead
of an empty 200 on Node (and instead of 500 elsewhere). Return a value
to keep a 200.

test/undefined-return.test.ts covers app.fetch and the Node server
(both fail without the fix) and pins null to 200.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:49:46 -05:00
chrnx 3fc43eb7ad Merge pull request 'fix(params): match @header names without case (GitHub #37)' (#171) from fix/header-decorator-case into develop
CI / runtimes (deno) (push) Successful in 34s
CI / runtimes (edge) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (bun) (push) Failing after 12s
2026-10-25 03:49:42 +00:00
chrnx bc04330a27 fix(params): match @header names without case (GitHub #37)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
Node's IncomingHttpHeaders and the fetch adapter's headersToRecord
both store request header names lower-cased, but resolveOne looked a
@header/@headers key up exactly as the decorator wrote it. Any name
with a capital letter, such as @header('Content-Type'), therefore
reached the handler as undefined.

resolveOne now lower-cases the key for the headers source before the
lookup. A picked bag (@headers([...])) keeps the names as written, so a
handler reads back the key it asked for; @headers() with no argument
still returns the whole lower-cased bag.

test/params.test.ts covers the single and picked forms on resolveArgs;
test/header-case.test.ts sends a request over app.fetch and the Node
server. All three fail without the fix.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:36:18 -05:00
chrnx cf5df70c62 Merge pull request 'fix(multipart): accept exactly maxParts parts (#118)' (#170) from fix/multipart-max-parts-boundary into develop
CI / runtimes (bun) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 33s
CI / build (push) Successful in 30s
2026-10-25 03:36:02 +00:00
chrnx 5536093894 fix(multipart): accept exactly maxParts parts (#118)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 30s
CI / dco (pull_request) Successful in 5s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / runtimes (bun) (pull_request) Successful in 20s
busboy emits `partsLimit` once its part count reaches `limits.parts`,
not when it passes it, and parseMultipart treats that event as a
malformed body. With `maxParts: N` a body of exactly N parts was
therefore rejected with 400 and only N-1 were accepted.

parseMultipart now passes `maxParts + 1` to busboy, the same one-unit
headroom it already gives `fieldSize`. N parts are accepted, N+1 are
rejected. Route-level and server-level maxParts share this path, as do
the Node server and app.fetch.

test/multipart.test.ts adds the exact-N case on parseMultipart;
test/multipart-http.test.ts sends exactly N parts at route and server
level. All three new assertions fail without the fix.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:21:10 -05:00
chrnx 87b6e7a4b0 Merge pull request 'fix(multipart): bound a text field by the body limit, not busboy's 1 MiB (GitHub #39)' (#165) from fix/multipart-field-size into develop
CI / runtimes (edge) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 33s
CI / build (push) Successful in 29s
2026-10-25 00:48:17 +00:00
chrnx 235e483bfb fix(multipart): bound a text field by the body limit, not busboy's 1 MiB (GitHub #39)
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 5s
parseMultipart created busboy with `limits: { parts }` only, so
busboy's `fieldSize` default of 1 MiB applied whatever maxBodyBytes
allowed. busboy cuts a field at that size and only sets
`valueTruncated`, which nothing read: with the body limit raised, a
1,100,000-character field reached the handler as 1,048,576 characters.

acquireBody now passes the route's resolved body limit down as
`maxFieldBytes`, and parseMultipart gives it to busboy as `fieldSize`.
busboy flags a field once it reaches `fieldSize`, so it gets one byte
of headroom; otherwise a field of exactly the limit would count as
cut. A field that busboy still reports as truncated rejects with
HttpError 413, which parseRequestBody already renders with that
status, matching how an over-limit body fails. Node and app.fetch
(Deno, Bun, edge) share this path.

test/multipart-http.test.ts sends a 1,100,000-character field to a
route with maxBodyBytes 2,000,000 over both app.fetch and the Node
server. test/multipart.test.ts checks the 413 and the exact-limit
boundary on parseMultipart directly.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 19:29:31 -05:00
chrnx e7f08052f4 Merge pull request 'fix(graph)!: fail boot when a node needs the token it provides (GitHub #43)' (#163) from fix/graph-self-dependency into develop
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 32s
CI / runtimes (bun) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 19s
CI / build (push) Successful in 29s
2026-10-24 23:58:26 +00:00
chrnx 0ba15b7862 fix(graph): report a self-dependency as the cycle it is (GitHub #43)
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / dco (pull_request) Successful in 4s
A node that needs the token it provides is a cycle of one, so say so in
the same words as every other cycle (`cycle detected: a -> a`), and name
the token and the fix:

  cycle detected: auth -> auth (it needs 'user', which only it provides).
  Remove 'user' from its needs, or move the work that produces 'user'
  into a step it needs.

"missing dependency … it provides it itself" pointed the reader at a
missing producer, when the producer is there and the problem is the
loop.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:42:23 -05:00
chrnx b005d6a44a fix(graph)!: fail boot when a node needs the token it provides (GitHub #43)
topoSort validated each need with producedBy.has(key), and the visit
skipped a dependency whose producer was the node itself. So a step with
needs: ['user'] and provides: ['user'], and nothing else providing user,
passed the graph check and booted. At request time it read a value
nobody had written, where every other missing dependency fails at boot.

The check now treats a node's own token as missing unless it is seeded.
The issue also allowed "provided by another node", but since CARD-18
(GitHub #35) a token has exactly one producer, so a second node that
provides it fails boot on its own; the self-producer is the only
producer there can be. A seeded token (req, params) still satisfies the
need, because the step reads the seed from the context before its
output is merged over it. The visit keeps skipping the node itself for
that case, so it is not reported as a cycle.

overrides do not exempt the node. They replace a runner after
finalizeGraph has run topoSort, and change no needs, so the graph check
sees the same node either way.

BREAKING CHANGE: an app with a node that needs a token only it
  provides now fails createApp with "missing dependency: <token> needed
  by <node> — it provides '<token>' itself". Remove the token from the
  node's needs, or move the work that produces it into a separate
  provider or step.
Refs: GitHub #43

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:42:22 -05:00
chrnx 08d3dd061b Merge pull request 'fix(container): cache the in-flight promise of an app-scoped binding (GitHub #46)' (#169) from fix/provider-inflight-cache into develop
CI / runtimes (bun) (push) Successful in 25s
CI / build (push) Successful in 29s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 33s
2026-10-24 23:42:18 +00:00
chrnx 510e9c4863 fix(container): cache the in-flight promise of an app-scoped binding (GitHub #46)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (bun) (pull_request) Successful in 20s
Container.resolve marked an app-scoped binding resolved only after its
factory settled. Two resolutions that started before then both found
nothing cached and both ran the factory, so one token could open two
pools.

The binding now caches the promise as soon as the factory starts, and
every resolution returns that promise. Retry semantics are unchanged:
before, a rejected factory set nothing and the next resolution ran it
again. Now a rejection clears the cached promise, so the next
resolution still retries, and only the callers already waiting on the
failed attempt share its rejection. The factory runs inside an async
wrapper so a synchronous throw takes the same path.

createApp was not exposed to this in practice. bootProvider runs each
provider's runner once, inside the memoized boot, and registers the
finished value as a constant factory, and Container is not exported.
The fix makes the container's own guarantee hold instead of relying on
that.

Refs: GitHub #46
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:31:40 -05:00
chrnx ebb828a495 Merge pull request 'fix(metadata): keep a subclass's decorators off its base class (GitHub #44)' (#168) from fix/param-metadata-inheritance into develop
CI / runtimes (deno) (push) Successful in 33s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 19s
2026-10-24 23:31:35 +00:00
chrnx dae052f400 fix(metadata): keep a subclass's decorators off its base class (GitHub #44)
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 20s
record in params.ts read the argument map with Reflect.getMetadata,
which walks the prototype chain, then pushed into the list it got back
and defined that same object on the subclass. On a subclass with no
metadata of its own, that object was the base class's, so a @query on
Child.list also showed up in getArgs(Base, 'list').

routeDecorator in metadata.ts had the same pattern with the routes
array, so a @Get on a subclass was also served by the base controller.
It is the same bug in the same shape, so it is fixed here too.

Both now write a copy onto the decorated class: a shallow copy of the
map and a new list for the method in params.ts, a new array in
metadata.ts. getMetadata returns the class's own metadata once it has
some, so later decorators on that class copy its own data, not the
base's. A subclass still starts from what it inherits, as before.

The other decorators in metadata.ts (@Provider, @Step, @Route,
@Module, @Transformer, @Html) define a fresh value per class or per
method and never mutate what they read, so they are unaffected.

Refs: GitHub #44
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:27:35 -05:00
chrnx 32bd4f6e4a Merge pull request 'fix(http): end an idle stream as soon as the client leaves (GitHub #40)' (#167) from fix/stream-cancel-on-disconnect into develop
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 33s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 19s
CI / build (push) Successful in 29s
2026-10-24 23:27:30 +00:00
chrnx 1daa4f3cd1 fix(http): end an idle stream as soon as the client leaves (GitHub #40)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 41s
Both stream adapters waited for the source's pending next() after the
client had disconnected. A source idle between events, such as an SSE
feed with nothing to send, may never settle that next(), so on Node
pipeStream never reached its finally: stream:close did not fire and the
closer stayed registered, which graceful shutdown then still treated as
a live stream. Through app.fetch, the ReadableStream's cancel awaited
return(), which an async generator only runs once its pending next()
settles, so cancelling the body did not settle either, with or without
compression wrapping it.

Each pull is now raced against the disconnect: the response's close
event on Node, and the stream's cancel on the fetch path. The source's
return() is called without being waited on, through a small
releaseIterator helper that also guards a return() that throws
synchronously, which on Node escaped from the close listener as an
uncaught exception. The WebSocket abort listener already released its
iterator this way and now uses the same helper.

The new cases in stream-lifecycle-parity drive both adapters, with and
without compression, against an async generator, a return() that never
settles and a return() that throws. All twelve need the fix except the
uncompressed fetch case with a generator, which already passed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:23:29 -05:00
chrnx 1a24d4e1b6 Merge pull request 'fix(shutdown): treat a graceful close that throws synchronously as a rejection' (#166) from fix/close-deadline-sync-throw into develop
CI / runtimes (bun) (push) Successful in 21s
CI / build (push) Successful in 16m36s
CI / runtimes (edge) (push) Successful in 21s
CI / runtimes (deno) (push) Successful in 33s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
2026-10-24 23:23:24 +00:00
chrnx 51fa7c1a88 fix(shutdown): treat a graceful close that throws synchronously as a rejection
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 29s
CI / dco (pull_request) Successful in 5s
closeWithDeadline called graceful() directly inside the Promise
executor. A graceful path that threw before returning its promise
escaped the executor, so the close() that serveDeno and serveBun
return rejected on the spot. The deadline timer had already been armed
and nothing cleared it, so it later fired anyway: it logged a timeout
and forced a server whose close() had already given up.

graceful() now runs inside Promise.resolve().then(), so a synchronous
throw becomes a rejection and takes the same path one already took: the
shutdown ends, close() resolves, and the timer is cleared.

GitHub #47.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:20:56 -05:00
chrnx c7558ccbeb Merge pull request 'fix(lifecycle): make a concurrent close() wait for the teardown in flight' (#164) from fix/concurrent-close into develop
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (edge) (push) Successful in 18s
CI / runtimes (deno) (push) Successful in 33s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / build (push) Successful in 29s
2026-10-24 23:20:52 +00:00
chrnx 212d2fa5c4 fix(lifecycle): make a concurrent close() wait for the teardown in flight
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 32s
CI / runtimes (edge) (pull_request) Successful in 41s
TeardownRegistry.run set a `drained` flag and returned at once to any
later caller. That kept teardown from running twice, but a second
close() made while the first was still awaiting its callbacks resolved
straight away. A signal handler and a test hook closing together could
then move on with a database the first call had not closed yet. This
reached every close path: app.close() with or without a listen()ed
server, and serveDeno/serveBun, which hand over to app.close().

The registry now keeps the promise of the teardown it started and
returns it to every caller, so the callbacks still run once and each
caller resolves only after they finish, within its own runTeardown
budget. The drain window and closeApp needed no change: the health
drain already shares one window, and a second server.close() waits for
the same 'close' event. close() after a failed listen() still has no
server and only runs teardown.

GitHub #45.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:18:23 -05:00
chrnx d90e7ca2b0 Merge pull request 'fix(http): choose the body parser by the media type (GitHub #36)' (#162) from fix/content-type-media-type into develop
CI / runtimes (bun) (push) Successful in 20s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 35s
CI / build (push) Successful in 30s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-24 23:18:19 +00:00
chrnx 79925595b5 fix(http): parse every +json media type as JSON (GitHub #36)
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
Exact matching left `application/json-patch+json` arriving as text,
where the old substring check had parsed it, and still left the other
`+json` types (`application/problem+json`, `application/vnd.api+json`)
as text, as they always were. `+json` is the structured-syntax suffix
for JSON (RFC 6839), so any media type ending in it is parsed as JSON.
`application/jsonx` and parameters that only mention JSON still are not.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:15:50 -05:00
chrnx e303cb3a4b fix(http): choose the body parser by the media type (GitHub #36)
parseRequestBody picked JSON, urlencoded or multipart with
contentType.includes() on the raw header. That is case-sensitive, so a
valid `Application/JSON` reached the handler as a string, and it
matches anywhere in the header, so a parameter could choose the
parser: `text/plain; x=application/json` was parsed as JSON.

The media type is now taken from the part before any `;`, trimmed and
lowercased (RFC 9110 §8.3.1), and compared exactly. The boundary is
still read from the full header.

A type that merely contains one of the three no longer selects its
parser. `application/json-patch+json` used to be parsed as JSON and
now arrives as text, as other `+json` types always have. CHANGELOG
says so.

test/http.test.ts sends both cases from the issue, plus their
urlencoded equivalents, through the Node server.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:15:50 -05:00
chrnx 6fc6e9e3c5 Merge pull request 'fix(app): an empty mountpoint mounts at the root again (GitHub #31)' (#161) from fix/mountpoint-empty-string into develop
CI / build (push) Successful in 28s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 33s
CI / runtimes (bun) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-24 23:15:45 +00:00
chrnx 7c2454fe43 fix(app): an empty mountpoint mounts at the root again (GitHub #31)
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 29s
CI / dco (pull_request) Successful in 4s
GitHub #32 (merged from contrib) made `createApp` fail with a message
naming the module when its `@Module` metadata has no `mountpoint`,
instead of a TypeError from `joinPath`. The check tested falsiness, so
it also refused `mountpoint: ''`, which the type allows and which has
always mounted at the root (`joinPath('', '/hi')` is `/hi`).

Test for `typeof … !== 'string'` instead: a missing or non-string
mountpoint still fails with the new message, and `''` boots as before.
The CHANGELOG entry for #31 that #32 did not add is included.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 15:52:50 -05:00
chrnx 9f6f916063 Merge pull request 'Merge contrib: validate module mountpoints at runtime (GitHub #32)' (#160) from contrib/gh-pr-32 into develop
CI / runtimes (deno) (push) Successful in 33s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / build (push) Successful in 29s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (edge) (push) Successful in 18s
2026-10-24 20:51:52 +00:00
chrnx dc88fdef10 Merge pull request #32 from otrumb/fix/module-mountpoint-error
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 30s
fix(app): validate module mountpoints at runtime
2026-10-24 15:49:32 -05:00
chrnx 1e2d55f158 Merge pull request 'docs(changelog): say how to migrate off the two new boot failures (CARD-22)' (#159) from docs/changelog-migration-notes into develop
CI / runtimes (deno) (push) Successful in 33s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 29s
2026-10-24 20:15:30 +00:00
chrnx f494fc283d docs(changelog): say how to migrate off the two new boot failures (CARD-22)
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 32s
Two Breaking entries in [Unreleased] described a new boot failure
without the step that fixes it. Found in the second pre-freeze review.

- #127, constrained route params that tie: make the constraints
  disjoint, keep one route and branch in the handler, or give one its
  own static segment. A plain param reported unreachable never served a
  request, so delete it or narrow the constraint that shadows it. For a
  WebSocket pair, declare the constrained route first.
- #126, reserved `/__mesh__/control`: move the route to another path.
  Nothing replaces the reserved one, which never reached a route on
  Deno, Bun or the edge.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:50:05 -05:00
chrnx 9de0027ddc Merge pull request 'feat: name every type the public signatures use, before the freeze (CARD-22, D19)' (#158) from feat/d19-public-surface into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 5s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 33s
2026-10-24 19:50:01 +00:00
chrnx 92d54dcc45 feat: name every type the public signatures use, before the freeze (CARD-22, D19)
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 32s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 19s
D19 as amended 2026-10-24: nothing that shipped in 26.9.0-beta.2 is
removed. Every symbol D19 had listed for removal or review is in that
release, so this change only adds exports and marks scope.

- Export `AppOptions`, `ExplainNode`, `WsRequest` and `WsSocket`. Each
  appears in a public signature (`createApp`, `Explain.chain`,
  `app.upgrade`) but could not be imported. `AppOptions` is the former
  inline options type of `createApp`, moved verbatim into an interface.
- Add `RequestHeaders`. `Headers` shadows the Fetch global wherever it
  is imported, so it stays only as a `@deprecated` alias of the same type.
- Mark the mesh exports and `MeshConfig` `@experimental`. They stay
  exported and unchanged, but sit outside the freeze, like the
  `experimental: true` flag the mesh already needs.
- The seven review candidates (`withConsoleFallback`, `UNMATCHED_ROUTE`,
  `HTTP_ERROR`, `VALIDATION_ERROR`, `TransportMismatchError`,
  `isAsyncIterable`, `buildOpenApi`) stay as they are.

CHANGELOG: `### Added` for the types, `### Changed` for the mesh tag, and
a new `### Deprecated` for `Headers`. No `### Breaking`.

test/types/public-surface.test.ts fails to compile if any of the new
names stops being exported. `deno publish --dry-run` passes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:48:26 -05:00
chrnx b1392db7af Merge pull request 'fix(mesh): cap what an unauthenticated control peer can send on Node (#120)' (#157) from fix/mesh-preauth-wire-cap into develop
CI / build (push) Successful in 28s
CI / runtimes (edge) (push) Successful in 19s
CI / runtimes (deno) (push) Successful in 32s
CI / runtimes (bun) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
2026-10-24 19:45:31 +00:00
chrnx 411c7ef3f5 fix(mesh): cap what an unauthenticated control peer can send on Node (#120)
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 33s
Before a peer's hello is accepted, `boundInbound` refuses any frame over
64 KiB, but only once it has the whole frame. On Node, the control
channel's `WebSocketServer` takes the authenticated bound as its
`maxPayload` (about 7 MB at the defaults, so an RPC body fits), and
`maxPayload` is fixed per server. So `ws` assembled a frame up to that
size for a peer that had not yet authenticated. Found in the second
pre-freeze review. The existing pre-auth tests use a fake socket and
never reached `ws`'s own limit.

The Node adapter now counts the raw socket bytes from the upgrade until
the hello is accepted (`boundInbound` gains an `onWiden` hook for that
moment). Past a hello's worth (64 KiB + 1 KiB), it sends close 1009, as
every runtime does for an oversized frame, pauses the socket so `ws`
reads nothing more, and ends it. The counter is installed in the
`handleUpgrade` callback, after `ws` attaches its own `data` listener,
so no chunk is lost.

Bun and Deno have no per-socket limit for this. The CHANGELOG #120 entry
now says so, and says to limit frame size at the proxy if untrusted
peers can reach a Bun or Deno teapot's control path.

Test: a raw client announces a 5 MB frame before its hello and sends
200 KiB of it. The teapot answers with a 1009 close frame and closes the
connection. Without the fix it waits for the rest of the frame.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:36:15 -05:00
chrnx 19d6db7064 Merge pull request 'fix(mesh): queue RPC sends per socket so one drain releases one frame (#41)' (#156) from fix/mesh-rpc-send-order into develop
CI / runtimes (edge) (push) Successful in 18s
CI / runtimes (deno) (push) Successful in 32s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 19s
CI / build (push) Successful in 29s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-24 19:32:21 +00:00
chrnx 1ae4c6f865 fix(mesh): queue RPC sends per socket so one drain releases one frame (#41)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
#152 made each mesh RPC send wait for `drained()`, but each one waited on
its own. A drain on a backed-up socket releases every waiter at once
(`nodeSocket` keeps them in one list), so they all sent and the buffer
overshot the 1 MiB mark by one frame per concurrent RPC: bounded, but not
what #152 claims. Found in the second pre-freeze review.

`sendWhenDrained` (ws-core, internal) chains sends per socket, and each
one waits for `drained()` when its turn comes. The buffer then peaks at
the mark plus one frame, however many RPCs wait, and frames go out in
call order. The teapot's `reply` and the link's `sendRpc` both use it.
The frame is built at send time, so a call that timed out while queued
sends nothing, and nothing is sent after the close.

Tests: a burst of five 100-byte frames behind a backed-up socket sends
one frame per drain, in order, with the buffer at most one frame. It
fails when each sender waits on its own. Also: a withdrawn frame is
skipped, and a frame queued at close is dropped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:26:49 -05:00
chrnx 8333a46497 Merge pull request 'test(mesh): keep T2's refused body inside the socket buffer (#120)' (#155) from fix/test-flakes into develop
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (deno) (push) Successful in 33s
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 19s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
2026-10-24 19:19:46 +00:00
chrnx 2fc7bab78a test(mesh): keep T2's refused body inside the socket buffer (#120)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 29s
T2 sent a 1,000,001-byte body against the 1 MB default. The teacup answers
413 with `connection: close` while the client is still uploading, so the
client sometimes saw EPIPE instead of the 413: about 1 run in 10, on
develop too. That is the transport racing the answer, not a different
answer.

Run it against a 1,000-byte limit, the way the edge suite already does.
CARD-24's T2 asks only for "body > maxBodyBytes". 0 failures in 30 runs,
against 2 in 20 before.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:17:18 -05:00
chrnx 439f37d68f Merge pull request 'fix(app): listen() rejects when the port is taken (#138)' (#154) from fix/listen-bind-error into develop
CI / runtimes (edge) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 33s
CI / dco (push) Has been skipped
2026-10-24 19:17:15 +00:00
chrnx bca6fd09eb fix(app): listen() rejects when the port is taken (#138)
CI / runtimes (deno) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
`listen()` awaited `server.listen(port, cb)` without an `error` listener.
A bind failure (EADDRINUSE, EACCES) never calls the callback, so the
promise hung and the error went unhandled. That is the 30 s timeout #138
saw on CI: owner.test.ts reserved a port with `freePort()` (listen on 0,
close, reuse the number), another process on the shared runner took it,
and the teapot's `listen` hung instead of failing.

- core: `bind()` rejects on the `error` event. On failure `server` goes
  back to undefined, so `close()` resolves and `listen()` can retry.
- owner.test.ts: lifetime A listens on port 0 directly, since its teapot
  is up before the teacup needs the port. Lifetime B has to boot its
  teacup against a port nobody holds yet, so it keeps `freePort()` and
  reruns on a fresh port on EADDRINUSE, up to three times.

Tests: listen on a taken port rejects with EADDRINUSE, then the same app
listens on 0 and serves; close() after a failed listen resolves. Both
hung without the fix.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:13:39 -05:00
chrnx 1611ec0bfe Merge pull request 'docs(changelog): static revalidation is a breaking change (CARD-15, D12)' (#153) from docs/changelog-1c-breaking into develop
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 19s
CI / runtimes (deno) (push) Successful in 33s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
2026-10-24 19:13:23 +00:00
chrnx b23b4e4161 docs(changelog): static revalidation is a breaking change (CARD-15, D12)
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 33s
Every static file now goes out with `Cache-Control: no-cache`, where
before it sent no Cache-Control at all. A browser or proxy that reused
static files for a lifetime guessed from `Last-Modified` now revalidates
each one, and keeping the old behaviour needs a config change (`static:
{ cacheControl }`). That is a breaking change, so the entry moves from
`### Changed` to `### Breaking`, word for word.

D12 had filed it under `### Changed`. CARD-22's gate table already said
a breaking entry was due if the default turned on, and it did. The
pre-freeze review flagged the mismatch.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:10:55 -05:00
chrnx 4e02cdc351 Merge pull request 'fix(mesh): RPC frames wait for the send buffer too (CARD-26, #41)' (#152) from fix/mesh-rpc-backpressure into develop
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 32s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 5s
2026-10-24 19:10:52 +00:00
chrnx 07d9b7441c fix(mesh): RPC frames wait for the send buffer too (CARD-26, #41)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 34s
CI / runtimes (bun) (pull_request) Successful in 19s
CARD-26 made the WebSocket route pump await `drained()` before each pull,
but mesh RPC traffic sends outside that pump, so it never waited:

- teapot: `handleRpc` runs concurrently per rpc-req, so a teacup that
  keeps sending requests and stops reading grows the teapot's buffer by
  one response each.
- link: `sendRpc` sent each rpc-req at once, whatever the buffer held.

Both now wait for `drained()` before sending. The teapot drops a response
whose socket closed while waiting. The link starts its timeout before
waiting, so a teapot that stops reading still answers 504, and a call
that settles while waiting (timeout or close) is never sent late.

Found in the pre-freeze integrated review.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:08:35 -05:00
chrnx bb3d759f3a Merge pull request 'fix(http): a handler-set ETag array is still the handler's (CARD-15)' (#151) from fix/etag-array-header into develop
CI / runtimes (edge) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 19s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 32s
2026-10-24 19:08:27 +00:00
chrnx d1abc4951a Merge pull request 'chore: clear the dependency advisories blocking CI' (#150) from chore/npm-audit-2026-10-24 into develop
CI / runtimes (edge) (push) Successful in 19s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 32s
CI / runtimes (bun) (push) Successful in 20s
CI / dco (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 6s
2026-10-24 19:06:54 +00:00
chrnx 0017093626 chore: mirror the new overrides in deno.lock
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 33s
deno.lock records package.json's overrides, so the runtimes (deno) job's
publish dry-run found it out of date after the bump and aborted.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 13:59:25 -05:00
chrnx 3efe049bb5 fix(http): a handler-set ETag array is still the handler's (CARD-15)
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 20s
With `etag: true`, `tagged()` only recognised a handler ETag given as a
string. Given as an array, it compared If-None-Match against the body's
computed tag while sending the handler's array, so a client revalidating
with the tag it was sent got a 200 instead of a 304, and two ETag values
went on the wire.

ETag is single-valued, so the last value of an array wins, as a repeated
`setHeader` would. It is sent alone and drives the comparison.

Found in the pre-freeze integrated review.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 13:55:06 -05:00
chrnx 74dbbe0b1a chore: clear the dependency advisories blocking CI
CI / runtimes (deno) (pull_request) Failing after 33s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 29s
`npm audit --audit-level=moderate` fails on develop: six advisories, all
in devDependencies, none in what ships.

- body-parser (high) and fast-uri (moderate): a plain `npm audit fix`.
- undici (high): the existing override pinned 7.29.1, now inside the
  advisory range. Move it to 7.30.1. `--force` wanted a miniflare
  downgrade instead.
- multer (high): reached through @nestjs/platform-express, the bench's
  Nest comparison. 2.5.0 carries the fix. `--force` wanted a Nest
  downgrade, so add an override like the others.

Verified: audit reports 0 vulnerabilities; lint, typecheck, `npm test`
(1149), test:edge (exercises miniflare on the new undici), test:bun,
test:deno and build all pass.

test/mesh/large-body.test.ts T2 fails about 1 run in 10 with EPIPE. That
rate is the same with and without this change (2/20 each), and Node's
fetch uses its bundled undici, not this one. Tracked separately.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 13:53:51 -05:00
chrnx cdef95ffcb Merge pull request 'fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)' (#147) from feature/fprd-001c-ws-backpressure into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 19s
CI / runtimes (deno) (push) Successful in 32s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 20s
2026-10-23 06:22:18 +00:00
chrnx a9a4f6c6ef fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (bun) (pull_request) Successful in 19s
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 01:20:11 -05:00
chrnx 567b5e134f Merge pull request 'fix(mesh): bound the control channel by maxBodyBytes and its own queue, not the user ws limits (CARD-24, #120, #148)' (#142) from feature/fprd-001c-ws-mesh-body into develop
CI / runtimes (edge) (push) Successful in 19s
CI / runtimes (deno) (push) Successful in 25s
CI / runtimes (bun) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 28s
CI / dco (push) Has been skipped
2026-10-23 06:20:06 +00:00
chrnx 8f73779a21 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 18s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 19s
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 01:16:43 -05:00
chrnx e98d5d33eb 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 01:16:43 -05:00
chrnx cad81223e5 fix(mesh): give the control channel its own inbound queue bound (#148)
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 01:16:43 -05:00
chrnx 713122d53a fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
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 01:16:43 -05:00
chrnx bfa4c1464a Merge pull request 'feat(http): response compression with gzip and br (CARD-16, #112)' (#149) from feature/fprd-001c-compression into develop
CI / runtimes (deno) (push) Successful in 22s
CI / build (push) Successful in 28s
CI / runtimes (edge) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 18s
2026-10-23 06:15:05 +00:00
chrnx 3296189093 feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (deno) (pull_request) Successful in 23s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 17s
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:12:48 -05:00
chrnx c22c37e0b3 Merge pull request 'feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)' (#144) from feature/fprd-001c-etag into develop
CI / runtimes (deno) (push) Successful in 21s
CI / build (push) Successful in 28s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 5s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
2026-10-23 06:11:40 +00:00
chrnx d32fc9f8d7 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / build (pull_request) Successful in 27s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 4s
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
  Last-Modified and Cache-Control from the stat the resolver already did.
  A matching If-None-Match, or If-Modified-Since when If-None-Match is
  absent, answers 304 before the file is read. StaticHit now carries the
  stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
  no-cache so browsers revalidate rather than reuse a file for a lifetime
  guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
  to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
  plus its length, computed before HEAD blanks the body. A handler-set
  etag is kept and only compared. Weak comparison, lists split outside
  quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
  dropped, so NotModified matches the ETag path on every adapter.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:09:54 -05:00
chrnx 50010da88d Merge pull request 'feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)' (#140) from feature/fprd-001c-cookies into develop
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 15s
2026-10-23 06:09:50 +00:00
chrnx 7f9a0eef0f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 20s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00
chrnx 037e695a31 Merge pull request 'feat(mesh): remote routes follow teapot membership (CARD-19, #124)' (#146) from feature/fprd-001c-mesh-membership into develop
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 28s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
2026-10-23 06:08:09 +00:00
chrnx 9ea1365b66 test(router-parity): a late teapot is served after it connects for CARD-19 (owner approval required)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 4s
owner-mesh-lifetime.json froze phase B2 (teapot absent at boot, then up)
at 404 for GET and POST /api/remote/ping. The table was built once at
boot, so a late teapot was never spliced in. CARD-19 (#124, D15) changes
that. B2 now answers GET 200 {"from":"teapot"} and POST 405 with
Allow: GET, HEAD, OPTIONS, the same as A1.

Only those two entries change. A1, A2 and B1 are identical.

The fixture's teacup goes from reconnect: false to reconnect with a fast
backoff (20-60ms). Under D15, reconnect: false makes a dropped teapot
"gone" (404), and an absent one is not retried. The card's phases
describe the reconnecting teacup: A2 stays 503 and B2 becomes 200. B2
now waits for the mesh:routes event before probing. The fixture comment
and the corpus README line describing "built once at boot" are updated.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:40 -05:00
chrnx 6bbd78fc8e feat(mesh): remote routes follow teapot membership (CARD-19, #124)
The teacup built its route table once at boot. A teapot that started
late was never served, and one that was gone for good stayed advertised.
Implement D15 (accepted 2026-10-18):

- A teapot that missed bootTimeoutMs is retried in the background with
  the reconnect backoff (not with reconnect: false). On connect its
  routes join the remote table. Its steps do not, because the graph
  was validated at boot without them.
- While a link is reconnecting, its routes stay and answer 503, now
  with retry-after (seconds until the next attempt).
- A link that gives up for good (dropped with reconnect: false, or a
  permanent refusal while reconnecting) has its routes removed: 404,
  and Allow drops its methods. A refused reconnect no longer retries
  forever.
- A returning manifest replaces the teapot's routes. missingFromManifest
  now checks steps only, so a dropped route is removed instead of
  refusing the reconnect.
- A late route that conflicts with another teapot's is refused and
  logged. The table keeps serving. At boot the same conflict still
  fails boot.
- Each change emits mesh:routes with { url, added, removed }.
- The reserved-path check from CARD-21/CARD-17 (#141, #145) runs in
  the table for every remote route: at boot a route on /__mesh__/control
  (or /__live__ and /__ready__ with health on) fails boot as before. A
  late or returning one is refused and logged, and the teapot's other
  routes are served.

Mechanics: the remote table publishes a new array per change
(copy-on-write). app.fetch and listen() share one table through a
getter, and buildFetch/createHttpServer read it once per request, so a
request sees the old table or the new one, never a mix. The router
reuses local trees when the local entries are identical, so a
membership change rebuilds only the remote trees. Dev routes now sit
before remote ones in the table to keep the local positions stable.

Tests cover T1-T8 on Node (test/mesh/membership.test.ts), plus the
local-tree build counter and late reserved-path routes, and T1/T2 on
Deno and Bun.

The frozen owner-mesh-lifetime.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:39 -05:00
chrnx c9e76fde2d Merge pull request 'fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)' (#137) from feature/fprd-001c-mesh-remote-head into develop
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 21s
2026-10-23 06:04:35 +00:00
chrnx ae9e5529e8 test(router-parity): HEAD on a remote GET answers 200 for CARD-20 (owner approval required)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 20s
owner-mesh-allow.json froze HEAD /api/x at 404 on both adapters: the
teacup forwarded HEAD to the teapot, which has no HEAD plan for the
route. CARD-20 (#125, D16) fixes that, so HEAD now answers 200 with the
GET's headers and an empty body, like a local route.

Only those two entries change (fetch and node), status 404 -> 200.
Headers and the empty body are identical. The fixture comment in
owner.test.ts that described the old behaviour is updated to match.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 5783212377 fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)
The teacup's router resolves HEAD to a remote buffered GET through the
implicit-HEAD fallback, and OPTIONS advertises HEAD. But the remote
route handler forwarded req.method, so the teapot got a HEAD envelope,
found no HEAD plan in resolveRoute, and answered 404.

Forward a HEAD that matched a remote GET as GET. dispatch already drops
the body for HEAD, so the client gets the GET's status and headers and
no body, the same as a local route. An explicit remote HEAD route is
matched first and is still forwarded as HEAD.

The fix is teacup-side (D16, accepted 2026-10-22): the teapot and the
wire protocol are unchanged, so a new teacup works against an older
teapot during a rolling deploy.

Tests cover app.fetch and the Node listener (200 + GET headers + empty
body, OPTIONS, explicit HEAD precedence, 404/500 kept with no body, the
teapot handler called once as GET) and Deno and Bun.

The frozen owner-mesh-allow.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 1da6bf2f99 Merge pull request 'feat(http): liveness and readiness probes with a drain window (CARD-17, #115)' (#145) from feature/fprd-001c-health into develop
CI / runtimes (deno) (push) Successful in 20s
CI / dco (push) Has been skipped
CI / build (push) Successful in 27s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 17s
Promote → GitHub / push-github (push) Successful in 5s
2026-10-23 05:58:56 +00:00
chrnx f0530b15bb feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
CI / runtimes (deno) (pull_request) Successful in 21s
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 27s
CI / runtimes (bun) (pull_request) Successful in 16s
createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.

Probes are answered by the adapters, ahead of the request gate and of
handle(): Node in serve() (src/http/server.ts), the Fetch path in
app.fetch before it awaits the boot. Otherwise ready could never say
booting. Being ahead of the gate means maxConcurrentRequests never sheds
a probe (D14). Being ahead of handle() means no step, provider, plugin or
onError runs, and no lifecycle event is emitted, so logRequests and
metrics never see a probe. Security headers still apply, plus
cache-control: no-store. Other methods get 405 with Allow: GET, HEAD.

A probe through app.fetch before any boot starts the boot without
awaiting it. On the edge, or under a bare Deno.serve(app.fetch), nothing
else may boot the app, and an orchestrator that waits for ready before
sending traffic would wait forever.

health: { drainDelayMs } (D14) marks the app draining and keeps the
listener open for that long before connections drain. Without it, Node
closes idle keep-alive sockets at once, and a probe sees a reset rather
than the 503. The window is spent out of the close budget. serveDeno and
serveBun start the same window, through a symbol-keyed hook on the app,
before server.shutdown() / server.stop(false). workerd has no close(),
so it never reports draining.

While health is on, /__live__ and /__ready__ join the reserved-path
boot check that CARD-21 introduced, for local and mesh-spliced routes.
Invalid health values throw at createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:57:10 -05:00
chrnx 09251496c0 Merge pull request 'feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126)' (#141) from feature/fprd-001c-mesh-reserved-path into develop
CI / dco (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 26s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 20s
2026-10-23 05:57:05 +00:00
chrnx 9977d14605 test(router-parity): reserved mesh path refused on Node for CARD-21 (owner approval required)
CI / build (pull_request) Successful in 27s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
Golden update for ws-node-upgrade.json, needs owner approval (CARD-08
rule). The WS parity fixture declared @Ws('/__mesh__/control') to
capture the old adapter split: the Node listener served it (101, the
route's frame, close 1005), app.upgrade refused it (1008). Under D17
that route fails createApp, so the fixture drops it and keeps the path
in UPGRADE_PATHS. The Node row now matches the app.upgrade row: 101, no
frame, close 1008 with the shared reason.

ws-app-upgrade.json is unchanged: app.upgrade already refused the path
before matching, so removing the route does not change its answer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:53:55 -05:00
chrnx 2c00cc3407 feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126)
The Node upgrade listener only intercepted /__mesh__/control when a mesh
control channel was configured; otherwise a user @Ws route there was
served. app.upgrade (Deno, Bun, edge) always checked the path first and
closed 1008. The same app therefore worked on Node and was refused
everywhere else.

D17 makes the path reserved in every app, mesh or not:

- createApp fails when a @Ws, @Stream or HTTP route claims the path,
  naming the declaration. A literal pattern is checked by equality, a
  parameterised one (/__mesh__/:x, /__mesh__/:rest*) by matching the
  reserved path against it. Patterns whose first segment is not the
  literal __mesh__ (/:org/:repo, /:rest*) still boot: the adapters
  answer the path before route matching, so those routes never see it.
- A route exported by a teapot is checked during the teacup splice.
- The Node listener, with no control channel, accepts the upgrade and
  closes 1008 with the reason app.upgrade gives. The reason is now one
  shared constant.

The check lives in src/http/reserved-paths.ts so CARD-17 can add
/__live__ and /__ready__ to the same list.

BREAKING CHANGE: an app that declares a route at /__mesh__/control, or a
pattern under /__mesh__/ that matches it, now fails createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:53:55 -05:00
chrnx 444910b6f0 Merge pull request 'feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)' (#143) from feature/fprd-001c-one-producer-per-token into develop
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 14s
2026-10-23 05:51:52 +00:00
chrnx 56f953f0bb feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 14s
topoSort, topoLevels and subgraphFor built their token -> node map with
producedBy.set(key, node), so the last node registered for a token won.
Plugin nodes are registered after module nodes, which let a plugin's
scope.add({ name: 'shadow', provides: ['user'] }) silently replace the
app's own @Provider({ provides: 'user' }) for every route that needed
it. setRunner only rejects duplicate names, and scope.add is the one
path where a name and its tokens differ.

D9 settles it graph-wide: topoSort now throws when a token already has
a producer, naming both nodes and their origins (module:..., plugin,
mesh:<url>, builtin). One check on the whole node set covers every
current and future registration path. It also protects the built-ins
(logger, rooms, events) by rule rather than by registration order.
topoSort runs at finalize, after the mesh splice, so remote steps are
checked too. topoLevels and subgraphFor only ever see nodes topoSort
has already validated, so they keep their plain maps.

overrides replace the runner of an existing token and add no node, so
they are unaffected. Steps that provide nothing (plugin observers) are
not producers. The official plugins (jwt, metrics, rate-limit) pass
their suites against this build.

BREAKING CHANGE: an app whose graph has two nodes providing one token,
  e.g. a plugin scope node providing a token a module or built-in
  already provides, now fails createApp instead of letting the later
  node win.
Refs: GitHub #35

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:50:26 -05:00
chrnx a9e0555516 Merge pull request 'feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)' (#139) from feature/fprd-001c-edge-cf-connecting-ip into develop
CI / build (push) Successful in 27s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
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 05:49:45 +00:00
chrnx 88cbe41f72 feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / runtimes (bun) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 19s
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket
upgrade, so any client that sent the header chose its own address, and
it never read the header for HTTP, so IP-keyed plugins saw '' there.
D21 settles both: the header counts only under trustProxy, on both
paths, with no new option.

The adapter cannot make that call, because trustProxy is an app option.
So edgeHandler records the header against the object it hands the app
(the Request for HTTP, the WsRequest for an upgrade) in an internal
registry next to the Deno/Bun peer one, and app.fetch and app.upgrade
both consult it through one helper, trustedProxyClient(), which returns
'' unless trustProxy is on. Under trustProxy it takes precedence over
x-forwarded-for, since Cloudflare sets it itself and XFF can carry
client-supplied hops.

Nothing else records into the registry, so the Node, Deno and Bun
adapters, and a bare app.fetch or app.upgrade, ignore the header as
before.

BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from
  cf-connecting-ip unless the app sets trustProxy: true; without it,
  ctx.ip is ''.
Refs: #119

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:47:58 -05:00
chrnx 89ac955072 Merge pull request 'fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)' (#136) from feature/fprd-001c-query-string-question-marks into develop
CI / runtimes (edge) (push) Successful in 13s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 27s
2026-10-23 05:47:53 +00:00
chrnx 8bf54ec168 fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
CI / dco (pull_request) Successful in 4s
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
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).

Path extraction already split on the first `?` and is unchanged.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:02:42 -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 / runtimes (deno) (push) Successful in 20s
CI / build (push) Successful in 27s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (edge) (push) Successful in 14s
2026-10-23 04:55:05 +00:00
chrnxandClaude Opus 5.5 e112819f64 chore(deps): patch vite, vitest and fastify dev-dependency advisories
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
`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 / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
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 / build (pull_request) Successful in 27s
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 20s
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 / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 15s
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 / build (pull_request) Successful in 53s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 37s
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 / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 20s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 26s
2026-10-14 02:22:28 +00:00
chrnx 84e6f0752e docs(readme): describe radix route lookup
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (bun) (pull_request) Successful in 16s
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 / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 27s
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 / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 15s
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 / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 25s
CI / dco (pull_request) Successful in 5s
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 / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 19s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
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 / runtimes (bun) (push) Successful in 15s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 19s
2026-10-12 20:10:44 +00:00
chrnx 1b30f15c02 perf(router): reset the walk stack only when a lookup throws
CI / runtimes (edge) (pull_request) Successful in 14s
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
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 / runtimes (bun) (push) Successful in 15s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
CI / build (push) Successful in 25s
2026-10-12 18:54:45 +00:00
chrnx a2b71e2472 fix(router): drop pending walk frames when a segment fails to decode
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 15s
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 / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (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 / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (edge) (pull_request) Successful in 14s
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 / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 15s
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 (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 25s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 20s
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 (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
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 / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 35s
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 / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 21s
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 / 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
CI / dco (push) Has been skipped
CI / build (push) Successful in 26s
2026-10-10 21:41:42 +00:00
chrnx 77a99e83ce chore(deps): vitest 4
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 19s
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 / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 29s
CI / dco (pull_request) Successful in 5s
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 / runtimes (bun) (push) Successful in 15s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 21s
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 (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 19s
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 / 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
CI / dco (pull_request) Successful in 4s
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 / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / dco (pull_request) Successful in 4s
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 / build (push) Successful in 30s
CI / runtimes (bun) (push) Successful in 14s
CI / dco (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
2026-09-23 17:04:26 +00:00
chrnx 9761b40eb5 docs(agents): stop publishing the address of the private forge
CI / build (pull_request) Successful in 31s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 14s
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 / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 19s
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 / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 15s
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
Ngoc Trung aaef6cf5b7 fix(app): validate module mountpoints at runtime
Signed-off-by: Ngoc Trung <mr.trung.dhbk@gmail.com>
2026-09-23 10:30:02 +07:00
chrnx a16be6a832 Merge pull request 'chore(release): cut 26.9.0-beta.2' (#99) from chore/cut-26.9.0-beta.2 into develop
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (push) Successful in 14s
Stage → Verdaccio / publish-stg (push) Successful in 27s
CI / runtimes (bun) (pull_request) Successful in 16s
Promote → GitHub / push-github (push) Successful in 5s
CI / build (push) Successful in 32s
CI / runtimes (deno) (push) Successful in 18s
Release → npmjs / publish-prod (push) Has been skipped
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 14s
CI / dco (pull_request) Successful in 5s
2026-09-23 01:50:39 +00:00
chrnx b0a9f3bfc9 chore(release): cut 26.9.0-beta.2
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / dco (pull_request) Successful in 7s
CI / runtimes (deno) (pull_request) Successful in 20s
Dated 2026-09-22, the day the tag goes up, rather than the day the version was
decided — package.json has said 26.9.0-beta.2 since the staging bump on the
17th, and that is the difference the heading records. A version number is a
plan; a changelog heading is a receipt.

Last commit before the tag, which is the order AGENTS.md asks for and the one
the beta.1 slip taught: everything merged, the release gate measured, the
suites green on all four runtimes, and only then the date. Held here rather
than written with the bump, so nothing accumulated underneath a heading that
claimed to have shipped it.

The section covers what landed since beta.1: the plugin contract, app.boot(),
async serveDeno/serveBun, errors recognised by brand, and the mesh moving to
steps-and-routes-only exports. `release.yml` reads this section by version to
build the GitHub release notes, and does so after npm and JSR have published,
so the heading has to exist before the tag rather than after it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:41:19 -05:00
chrnx 9a8677d5c2 fix(bench): date the run in project time, and let the harness typecheck again
Two things the release run surfaced, neither of them visible from CI.

`npm run typecheck:bench` has been failing since serveDeno and serveBun became
async: the bench servers gained a top-level await, which `module: commonjs`
rejects outright, and bench/tsconfig.json inherited commonjs from the root
config it extends. The servers are ES modules run by tsx, Deno and Bun and
never by the CommonJS build, so the config was describing the wrong thing even
before the await arrived. CI runs `typecheck`, not `typecheck:bench`, which is
why a break in the harness waited for someone to run it by hand.

The date came from the runner's clock through toISOString, which is UTC. The
table was measured on the evening of the 22nd over ssh against a box keeping
UTC and dated itself the 23rd, a day ahead of the commit and of the changelog
entry it sits beside. It now reads project time.

tsx transpiles with this tsconfig too, so the module change was verified by
running the smoke pass again on that box: all six frameworks, the secure run
and all three runtimes still boot, and the regenerated header reads 2026-09-22.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:37:45 -05:00
chrnx 8c95ae8bfb docs(bench): regenerate the cross-framework tables on a box that was not busy
Measured on an otherwise idle Ryzen 3700X over ssh, with the same Node, Deno
and Bun versions the laptop runs, after two attempts here were thrown away.
The absolute numbers drop to roughly a third — a 2019 desktop part against an
M4 Max — and that is the trade: a slower box whose numbers mean something
beats a faster one whose numbers track what else was on screen.

The shape reproduced across both machines, which is the result worth having.
green-tea is behind Fastify on hello, param and pipeline, ahead of it on
validate, and ~2.8x ahead of Express, on the M4 and on the Ryzen alike. The
size of the gap did not reproduce (2-8% there, 7-15% here), so the README now
says the direction and points at the table for the number, rather than
quoting a percentage that is really a fact about somebody's hardware.

CV lands between 0.1% and 1.3% across every row, against 4-6% on the
contended runs.

Fixes a sentence added an hour ago claiming the ordering inside the fast group
moves between runs by more than the gap between its members. It does not — it
held on both boxes — and the claim happened to be the one that flattered us.
Cross-framework tables and the runtime table are regenerated; the hand-written
section below the marker, including the release gate, is untouched.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:20:57 -05:00
chrnx daf0fed8ab docs(agents): delete a branch when its work lands, on both sides
The cleanup that prompted this removed 36 branches from Gitea and 29 locally,
all but one already in develop and some of them three months old. Nothing had
gone wrong — each was simply merged and left, and the deletes were never part
of anyone's definition of done.

The cost lands on whoever cuts the next release, who cannot tell a branch
holding unmerged work from one that shipped in July without checking each in
turn. Writing the rule here rather than leaving it to habit is the point: the
humans and the agents working in this repository read the same file, so the
same definition of done applies to both.

CLAUDE.md is not touched on purpose — it points here precisely so the two
cannot drift.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 14:15:54 -05:00
chrnx c5a8361c14 docs(bench): record the 26.9.0-beta.2 release gate, and drop a claim it never supported
The breaking changes in this release — `Plugin` as `{ name, mount }`, async
`serveDeno`/`serveBun`, a teapot that cannot export a provider, an `HttpError`
recognised by brand — are boot-time and error-path work, so the question was
whether any of it reached the per-request path. Ten cases against
`v26.9.0-beta.1`, both trees on one box in one sitting with the order
alternating: nine overlap and say nothing, which is the answer.

The tenth is the part worth keeping. `param, 50 routes` came out +4.3% with
separated ranges, in our favour, and had no mechanism — the matcher work that
could produce it would have to show at 200 routes, where the same run said
+0.1%. Seven rounds put it at +0.5% and overlapping. It was chance, and it is
recorded as chance, because a flagged row means measure again in either
direction.

The README has claimed since 7 July that green-tea beat every other framework
in 3 of 4 scenarios. The table it links to stopped saying that at some point
over the following two months — a ranking written into prose once is a claim
nobody re-measures, and this one outlived the NestJS rows, the parity controls
and the runtime-neutral boundary the file itself documents the cost of. It is
replaced by the shape of the result, which is stable, and a pointer to the
table for the numbers, which are not.

The cross-framework tables are deliberately left at their 2026-09-02 date.
Two attempts to regenerate them produced runs where a framework's delta
tracked its position in the run order and a browser held ~60% of the machine;
publishing those would have read as green-tea overtaking Fastify, which is the
most flattering available reading of a broken measurement. Absolute numbers
need a quiet box.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 14:14:02 -05:00
chrnx a57223cef9 Merge pull request 'feat(runtime)!: serveDeno and serveBun boot before they bind' (#98) from feature/serve-adapters-boot into develop
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 19s
2026-09-20 16:55:47 +00:00
chrnx 9634ec73e8 feat(runtime)!: serveDeno and serveBun boot before they bind
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 6s
CI / runtimes (deno) (pull_request) Successful in 20s
Both were synchronous and left the boot to the first request, with the fix
documented as something the caller should remember: `await app.boot()` before
`Deno.serve` / `Bun.serve`. That made the correct use of a core helper depend
on reading a README, in a framework whose whole argument is that order should
not be something you have to get right.

The failure it leaves is the bad kind. `app.fetch` boots lazily and the boot
memo keeps the *rejection*, so a missing signing key does not fail the deploy:
the port binds, every request is answered 500 by the runtime, and none of them
reach `onError`. Anything that health-checks by asking whether the process is
listening sees a healthy server.

`listen()` has always awaited `bootApp()` before binding its socket, with a
comment saying it exists so Node and Deno/Bun serve an identical graph. They
did not. Now the three helpers agree, and the two adapters return promises.

`edgeHandler` is deliberately unchanged: on workerd there is no startup outside
a request, so there is no earlier moment to move the failure to.

Both new tests were confirmed to fail with the gate commented out — without it
`serveBun` resolves instead of rejecting, and serveDeno binds a port that 500s.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 12:38:50 -05:00
chrnx cbeab73626 Merge pull request 'chore(release): 26.9.0-beta.2 to staging' (#97) from release/26.9.0-beta.2 into develop
CI / build (push) Successful in 30s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
2026-09-18 03:53:29 +00:00
chrnx 58ba18f9f8 chore: ignore per-developer agent directories
CI / build (pull_request) Successful in 32s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
Stage → Verdaccio / publish-stg (push) Successful in 28s
.claude/ and .serena/ hold local settings and tool locks, one directory per
assistant, and both turned up as untracked noise in every status. Nothing in
either is shared configuration — .serena/ ships its own .gitignore, and the
only .claude/ file with a stable name is settings.local.json.

Blanket-ignored rather than enumerated, with a comment naming the one case that
would need revisiting: a repository-wide .claude/settings.json is a real
convention, and committing one later takes a negation line here. No such file
exists today, so this does not pre-build a rule for it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 22:40:03 -05:00
chrnx a30c2cecb3 chore(release): 26.9.0-beta.2 to staging
The plugins repository builds against Plugin { name, mount } and app.boot(),
which only develop has. Staging the version publishes it to Verdaccio under
stg and nowhere else; the npm and JSR cut stays a separate decision.

The bump also moves the exported VERSION, which was two releases behind and had
no business being. Its comment claimed it was "replaced at publish time" and
nothing ever did that — not tsup, not stage.yml, not release.yml, which only
reads the version out of package.json. VERSION is what a consumer quotes in a
bug report, so a stale one sends someone to the changelog of a release they are
not running.

Pinning it to package.json is what keeps this from being a fix with a shelf
life: the next bump that forgets it now fails the build. smoke.test.ts was
never going to catch it, because it asserts the CalVer shape and a stale
version matches that perfectly.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 22:39:49 -05:00
chrnx 1364d54ab4 Merge pull request 'feat(plugin)!: a plugin is a named object, and app.boot() is public' (#96) from feature/plugin-contract into develop
CI / runtimes (deno) (push) Successful in 18s
CI / build (push) Successful in 31s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (edge) (push) Successful in 14s
2026-09-17 03:47:20 +00:00
chrnx 7a01ca3068 docs: record the plugin contract change and app.boot()
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 6s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 16m38s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:45 -05:00
chrnx e0da6cee16 test(runtimes): build plugins as named objects on Deno and Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:25 -05:00
chrnx b3152aac45 test: build plugins as named objects
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:15 -05:00
chrnx 3fc761ce16 feat(app): expose boot() so providers can fail before serving
Only listen() booted before accepting traffic. Deno, Bun and edge all boot on the
first request, and the memo keeps the rejection, so a bad key answered 500 for the
life of the process while the app looked healthy.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:26:28 -05:00
chrnx 80f3f532f2 feat(plugin)!: a plugin is a named object, not a function
BREAKING CHANGE: `Plugin` is now `{ name, mount(api) }`. `fn.name` was the only
source for the name that plugin:mounted reports, and it is empty for a returned
arrow, "plugin" for a const, and whatever a minifier decides. A failed mount now
names the plugin and keeps the original error as its cause, and two plugins with
the same name fail createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:26:13 -05:00
chrnx e83d62cc1a feat(signals): recognise HTTP errors by brand, not by instanceof
A plugin published as its own package cannot import HttpError without depending on
core's version, and under CalVer no dependency range survives next month's beta. A
Symbol.for brand crosses copies, so a plugin throws a 429 core renders, while
importing nothing but types.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:25:50 -05:00
chrnx 73a4a9f6cd Merge pull request 'Mirror develop to GitHub contrib' (#95) from ci/mirror-develop-to-contrib into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 21s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 30s
CI / runtimes (edge) (push) Successful in 12s
2026-09-12 21:36:14 +00:00
chrnx 25f4144a38 ci(promote): mirror develop to GitHub contrib
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 5s
CI / runtimes (edge) (pull_request) Successful in 13s
Outside contributors target GitHub `contrib`, which tracked released
`main` and was reset after every release. Between releases they were
working against code the current develop no longer had — a PR touching
an area that changed on develop was obsolete the day it opened, and only
the maintainer could see why.

`contrib` now mirrors `develop`: promote.yml runs on develop pushes too
and pushes to `contrib`, not forced. The refusal is the guard — it fires
exactly when `contrib` holds external merges not yet carried into
develop, and the job says so instead of forcing over them. `main`
keeps its one meaning: released code.

Gitea's `contrib` is gone; it was only ever a copy waiting to be
forgotten. AGENTS.md and CONTRIBUTING.md describe the new flow, drop
the post-release reset, and note that a develop conflict is now the
contributor's to resolve because they can see it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 16:34:55 -05:00
chrnx 6717b15ee9 Merge pull request 'A teapot exports steps and routes, not providers' (#94) from feat/mesh-steps-only into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 31s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
2026-09-12 20:42:04 +00:00
chrnx 0ce81b08f3 test(mesh): cover the teapot dying with an RPC still in flight
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
The three failure tests kill the teapot between requests, so the link is
already down when the next one arrives and `rpc` fails before it sends
anything. Nothing covered the case that can actually hang: the request is
parked on a promise waiting for an `rpc-res` frame that is never coming.

`endSession` already handles it -- `rejectAllPending` fails what was
waiting with a 503 -- but that line was untested. Stubbing it out leaves
all three existing tests green while these two hang until the per-RPC
timeout (30s by default) and then answer 504, so the regression this
guards against is a request that stalls for half a minute and then
reports the wrong cause.

Asserts 503 specifically rather than "not 200", since a 504 would mean
the timeout caught it instead of the disconnect.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 249fc00f80 fix(mesh): name the teapot in the boot log a later 404 points back to
A route the absent teapot would have exported 404s, and that is the right
status: nothing was ever registered for a manifest that never arrived, so
there is no path to serve. But a bare 404 is indistinguishable from a typo
in the path, and the boot log is the only place the two are told apart.

It could not tell them apart either. The give-up warning relied on the
error's own message to identify the teapot, which holds for a refusal --
`mesh handshake failed: <url>` -- but not for an unreachable one, where the
error is a socket error that may carry no url at all. So the url is passed
in now, and every line of the boot-connect story names it: the retries, the
refusal, and the give-up. The give-up line also says no manifest was ever
exchanged, which is the fact that explains the 404.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 6e050197b6 test(mesh): drop the buildRemote case its neighbour already subsumes
'turns every manifest step into a lazy remote node' built the same thing as
the test directly below it and asserted less about it: one step token instead
of two, no assertion on what the RPC was called with. Two tests covering one
behaviour, one of them strictly weaker.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 8ef7c3ee14 fix(mesh): validate the manifest's route entries, not just its steps
decode is the mesh's trust boundary, and the steps array gained a per-element
check on this branch while the routes array beside it kept only its
Array.isArray. A peer sending `{ method: 5, pattern: {} }` got past decode and
died in compilePattern as a boot TypeError — it failed closed, so nothing was
exposed, but the error blamed green-tea for what was a malformed frame from
the other side. Both fields reach compilePattern, so both are checked.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx e69f604053 docs(mesh): record the scopes->steps rename as an exception to the bump rule
The bump rule in protocol.ts says renaming a field earns a protocol bump, and
this branch renamed the manifest's `scopes` to `steps` at v1 without one. The
argument for that lived only in the CHANGELOG, so the rule as written read as
simply broken to anyone who found it from the code.

The exception is now stated where the rule is, with the three conditions it
rests on: mesh is alpha, every app using it is gated behind `experimental:
true`, and both peers ship out of this repo, so no deployed pair can be split
across the rename. It retires with the first mesh release that drops
`experimental`.

Two other stale pointers go with it. The bootTimeoutMs JSDoc said `0` restores
"the old behaviour of a single attempt", which now reads as restoring a boot
that failed — it is only the attempt count, and the way to make a teapot's
absence fatal is a local `@needs` on one of its tokens. And the reconnect
plan's step 4 still pointed at invalidateRemoteBindings, which this branch
deleted; it gets a dated note in the same shape as the degrade plan's D6.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 727987286b refactor(graph): the missing-dependency note is a string, not a callback
topoSort, finalizeGraph, assertNeedsSatisfiable and finalize all threaded a
`(key: string) => string`, and no caller ever read `key` — the one producer,
in prepareGraph, is `() => ...`. The note names which teapots did not connect,
which does not vary by token, so the parameter was machinery for a
customization nothing asked for.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx bff8778112 refactor(mesh): @Provider's options no longer advertise export
The framework's public type offered an option whose only behaviour is to
throw at boot. Removing the field from the options type means a TypeScript
caller gets a compile error at the decorator, where the mistake is, instead
of a boot error a deploy away.

The runtime throw in collectProviders stays as the JavaScript backstop, so
ProviderMeta keeps the field and the decorator still records it through a
cast — a JS caller reaches the error naming the provider and its replacement
rather than having the option silently ignored.

The `as any` in the boot-throw test is now genuinely load-bearing, since no
TypeScript caller can write that decorator at all, and says so.

test/metadata.test.ts asserted the flag was stored for a provider. That half
described the option working, which is the message being removed, and the
boot throw it fed is already covered end to end in test/mesh/failure.test.ts.
The default is a different claim and stays: collectProviders throws on
anything truthy, so every plain provider recording `false` is what keeps
ordinary apps booting.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 1bcaa463f2 fix(mesh): a rejected first connect no longer leaks a retry supervisor
openSession's abort listener runs onEnd -> endSession -> scheduleRetry on
every socket abort, including the ones where the connect promise rejected.
A rejected connect means no caller ever received the Link, so nothing can
close it and closeLinks never sees it — connectUntilDeadline pushes to
meshLinks only on success. Every boot attempt against an unreachable teapot
therefore left a live supervisor behind, reconnecting forever on a handle
nobody holds.

Before this branch the boot then threw and the process died with them. Now
the teacup starts without that teapot, so they outlive the boot: close() the
teacup, bring the teapot up afterwards, and three mesh:connect events fire
for a URL contributing nothing to the graph, each holding an open socket.

The initial openSession now marks the link closed and clears the pending
timer before rethrowing. connectUntilDeadline is already the retry loop above
this; a second one underneath it was never wanted. Reconnection for a link
that did connect is untouched — that path runs through endSession on a
session that dropped after the Link escaped, and the rejection handler here
fires only on the first connect.

The regression test asserts both sides: no mesh:connect on the teacup, and
none on the teapot either, so a socket that opens without being adopted still
fails it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx f5d4d0cd74 docs(mesh): an absent teapot 404s, it does not 503
A teapot that never connected sent no manifest, so spliceRemoteScopes
registers nothing for it — no step runner, no route. Its routes therefore
take the ordinary unmatched path and 404, and a local node that needs one of
its tokens still fails the boot naming it. The 503 belongs to a teapot that
connected and later died, where the link and its exports exist and the
dead-link guard answers.

The previous commit said 503 for the absent case in five places, including
the warning an operator reads during a deploy. All five now tell the same
story, and the bootTimeoutMs JSDoc — stale in the other direction, still
claiming an absent teapot fails the boot — with them. The connectUntilDeadline
JSDoc also had a paragraph saying it still throws, contradicted three
paragraphs later; that one is gone.

No behaviour changed. Serving 503 for an absent teapot's tokens means knowing
what it would have exported, which is the expects list in the degrade plan and
is deliberately not built.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 03132b2048 docs(mesh): steps and routes are what a teapot exports
The CHANGELOG gains an [Unreleased] section — no version heading, no date —
covering the three mesh changes on this branch and why each one follows from
the first: a remote export is a step now, so it holds nothing between requests,
so an absent teapot costs a 503 rather than a boot.

The README says it in the Honest scope section, where the mesh caveats already
live: what can be exported, what happens if you export a provider anyway, and
why a missing token still fails the boot when an unreachable teapot no longer
does.

Two stale bits go with it. The JSDoc over assertNeedsSatisfiable still quoted
the old unconditional message; the Deno and Bun fixtures still said a teapot
exports its scopes. And the degrade plan's D6 planned to reuse a seam this
branch deleted — a dated note says so, and why a degraded step never needed it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 9f5792c1c5 test(mesh): steps-only exports across Deno, Bun and the edge
Deno and Bun mesh fixtures still exported a @Provider, which now throws
at boot. Convert each to a @Step (provide() -> run(), move the class
from providers: [] to steps: []) so the fixtures build a graph the
current mesh actually allows.

test/edge/_worker.mjs is a gitignored esbuild bundle rebuilt by
test/edge/run.ts on every test:edge run, so no source change was needed
there once the fixtures matched. All four suites pass: vitest (Node),
deno test, bun test, and the workerd/miniflare edge run, plus
typecheck.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 4e8aacb6b7 fix(mesh): name the absent teapot in the route-level missing-need error too
assertNeedsSatisfiable is a separate check from topoSort, so it didn't
get the note threaded into finalizeGraph -- a handler-level @needs
against an absent teapot's token read as a typo or a forgotten
export: true, which is worse than the pre-task behavior (the boot used
to throw naming the teapot). Thread missingNote through and soften
"local or mesh" to "local or connected mesh" when it's set, so the
message doesn't claim a search that never happened.

Also tightens two test assertions that only passed because "mesh"
happened to appear inside the unrelated "(local or mesh)" wording, and
removes adopt()'s now-fully-unused attempt parameter in mesh/link.ts
instead of leaving it underscored.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 3b680480ab feat(mesh): an unreachable teapot no longer stops the teacup from booting
Blocking existed for app-scope exports, which have to resolve at boot
because there is no later. Steps and proxied routes are all later. The
grace budget stays -- a co-deploy still waits -- but exhausting it now
warns instead of throwing. A missing token still fails the boot, and the
error now names the teapots that were away.

Also drops connectLink's onReconnect hook and the reconnected flag that
fed it: its only caller was removed by an earlier commit on this branch,
and it is not part of the public API (not re-exported, not documented).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 414b188792 fix(mesh): reject a manifest step that is not a string
decode is the mesh's trust boundary, reached before the handshake
authenticates the peer. The manifest row checked that steps was an array
but not what was in it, so {"steps":[123]} decoded cleanly and 123 would
have become a graph node name in buildRemote.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 6e66b05a41 refactor(mesh): drop the remote app-scope binding and its rebind seam
A remote provider was registered app-scope, resolved once, and cached for
the process lifetime; invalidateRemoteBindings existed only to un-cache it
on reconnect. With providers gone from the manifest, both go, and a remote
step needs nothing on reconnect because it holds nothing between requests.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 55890442fe refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one
value and told a reader nothing. No protocol bump: mesh is alpha, both
peers ship from this repo, and the number should mean incompatibility
between deployed versions.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx f6c05a0929 feat(mesh)!: refuse to export a provider
A provider's value is the object it builds, which cannot cross a JSON wire.
What did cross became an app-scope binding the teacup resolved once at boot
and served from a cache the teapot no longer stood behind. A step is the
shape that travels; the error says so.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 419ba092d4 docs(plans): a mesh that exports steps, not providers
Plan for dropping @Provider export from the mesh: the manifest carries step
names, an unreachable teapot stops blocking the boot, and the app-scope
binding that cached a remote value for the process lifetime goes away.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:23 -05:00
chrnx 85b6c703bb Merge pull request 'A tag stages before it can publish' (#91) from ci/tag-staging-and-promotion into develop
CI / runtimes (deno) (push) Successful in 22s
CI / runtimes (edge) (push) Successful in 12s
Stage → Verdaccio / publish-stg (push) Successful in 25s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (push) Has been skipped
Release → npmjs / publish-prod (push) Has been skipped
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 11s
Promote → GitHub / push-github (push) Successful in 8s
CI / build (push) Successful in 29s
CI / runtimes (bun) (push) Successful in 16s
Reviewed-on: #91
2026-09-04 13:23:20 +00:00
chrnx dfe71102ca docs(changelog): date the section for the day the tag actually ships
CI / runtimes (deno) (pull_request) Successful in 22s
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 14s
The heading was written for 2026-09-02, the day the cut was planned, then dated 2026-09-03
when it was closed. Neither day shipped anything, and the workflow split that has to land
before the tag moved it once more.

AGENTS.md is explicit that a dated heading is a receipt rather than a plan, and that this
exact drift already happened once on beta.1 — a section claiming a release that did not
exist, with a day of further work accumulating underneath it. Correcting the date is
cheaper than being the second instance of the thing the guidance warns about.

Today is the day the tag is created, so the receipt says today.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-04 08:10:25 -05:00
chrnx cd4a9f65f6 ci(release): stage a tag on Gitea before it can reach production
A `v*` tag did two things at once: `promote.yml` mirrored it to GitHub, and GitHub's
`release.yml` published it to npm and JSR. Creating the tag *was* the release, so the only
place to catch a bad one was a registry where npm gives 72 hours to unpublish and JSR gives
nothing — a version number spent on a mistake is spent for good.

The tag now means something different on each forge. On Gitea it triggers `stage.yml`,
which runs the real publish path — same `prepublishOnly` gate, same tarball, same commit —
against the internal Verdaccio, where a version can be overwritten. On GitHub it still
publishes for real. Nothing carries the tag between them; that push is a decision made
after reading the staging run.

`--tags` comes off the branch push in the same change, and it is the part that mattered
most. Removing the tag trigger alone would have left any tag in the runner's clone riding
along with the next promotion of `main` — a production publish as a side effect of a
merge, which is the exact failure the split is meant to prevent.

The refusal to stage a stable version is left as it is, with a note. It will first bite at
the release most worth staging, and the fix there is a suffixed staging version rather than
dropping a guard that keeps a stable number from mutating under an internal consumer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-04 08:10:17 -05:00
chrnx aa15862f3b Merge pull request 'Cut 26.9.0-beta.1' (#89) from chore/close-changelog-26.9.0-beta.1 into develop
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / build (pull_request) Successful in 29s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / runtimes (deno) (push) Successful in 20s
CI / dco (pull_request) Successful in 7s
CI / runtimes (deno) (pull_request) Successful in 20s
Reviewed-on: #89
2026-09-04 12:33:44 +00:00
chrnx 0c099c7266 chore(release): cut 26.9.0-beta.1
CI / build (pull_request) Successful in 13m16s
CI / runtimes (deno) (pull_request) Successful in 1m54s
CI / runtimes (bun) (pull_request) Successful in 53s
CI / runtimes (edge) (pull_request) Successful in 29s
CI / dco (pull_request) Successful in 6s
`[Unreleased]` has been the heading since tier 3 closed, which was correct while entries
were still arriving. They stopped: the matcher entry was the last one, and everything the
section describes is merged and green. Holding the heading past that point only makes the
file describe work as unreleased that is about to ship.

`deno.json` moves in the same commit because `test/package-metadata.test.ts` pins the two
together — bumping `package.json` alone ships one version to npm and a different one to
JSR, and JSR versions are immutable. The release workflow reads the changelog section by
version, so a tag pushed against an `[Unreleased]` heading fails after the publishes have
already run.

Dated 2026-09-03, the day the cut happens, rather than the day it was planned for.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-03 23:55:47 -05:00
chrnx c472d4c0de Merge pull request 'changelog: record the matcher change' (#88) from docs/changelog-matcher into develop
CI / build (push) Successful in 28s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 23s
2026-09-02 03:11:47 +00:00
chrnx f18aa9a42a docs(changelog): record the matcher change, which landed after the tier was written
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 29s
`[Unreleased]` was written when tier 3 closed and the route-ranking work came after it, so
a user-facing improvement with a measured number had no entry. That is the omission the
benchmark notes published in the same release are about — something measured that never
reached the file where anyone would read it — and cutting the beta without it would have
been a poor way to make the point.

Placed in Changed beside concurrent provider boot. Both are savings that appear only once
something grows, and reading them together says what neither says alone: what this release
improved is what happens when an application gets bigger.

The entry leads with what does not change, because "route ranking now happens somewhere
else" is the sort of sentence that makes a reader check whether their routes still resolve
the way they did. Equal specificity still keeps registration order; the ordering carries it
through a stable sort instead of through a scan.

The numbers are given per route-table size rather than as one figure. A single percentage
would be wrong at both ends — nothing at six routes, +14.9% at two hundred — and the shape
is the honest form of the claim.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 22:10:20 -05:00
chrnx 7ccb55d07a Merge pull request 'Route ranking at build time, and a benchmark that can measure a release' (#87) from perf/matcher-and-benchmarks into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 31s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
2026-09-02 03:07:37 +00:00
chrnx e61771077c docs(bench): refresh the tables and record what moved between releases
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 31s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 19s
The tables were measured on 2026-07-07 at `fe1831a`, two releases ago. Re-measured at
`8c5855c` with the runtime matrix included, every row under 1.2% CV.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 15:48:01 -05:00
chrnx e7b1c462e6 Merge pull request 'Tier 3 for the beta: what the graph earns you, and an event stream you can build on' (#82) from beta/tier-3 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 17s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 17:01:52 +00:00
chrnx a84960a46a docs(changelog): record the tier-3 work in Unreleased
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
Concurrent provider boot, `sse()` and the `id:` it writes, and the stream events that
three of the four runtimes never emitted.

#83 and #84 share one entry. They are two defects but one symptom — the stream events
were not usable — and a reader looking for "can I build a stream gauge on this" is served
better by one entry than by two bullets that both open with `stream:`.

The boot entry carries its two consequences rather than only its number, because "616ms
becomes 210ms" is not the part that can surprise someone: a required provider's
independent siblings now start, and `boot:provider:start` stops alternating with `:ok`.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:59:40 -05:00
chrnx 86a0d9c91b fix(observability): correlate stream events with the request that opened them
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
`src/http/core.ts` documented the design as "`stream:open`/`stream:close` already describe
the connection, and now carry the same `requestId`". They carried `{ name }` and nothing
else, on all three emitters, and `Bus.emit` forwards a payload verbatim — so there was
nowhere else it could have been arriving from. The comment described an intent that was
never carried out.

The split it describes is right: a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so ending the request span at the
handler's return keeps hour-long SSE connections out of the same latency distribution as
2ms replies. But the split only works if the two can be **joined**, and `requestId` is the
join key — it is what `EventPayload` defines itself as. Without it an exporter could not
say which request opened the connection still holding a slot, and `traceId`, carried
verbatim so an exporter can hand it to OTLP, never reached the longest-lived thing the
server does.

`route` comes along for a second reason. The contract this beta settled says label on
`route`, never on `name` — and `route` was absent from precisely the events a stream gauge
is built from, leaving a correct consumer with nothing to label. On a stream event `name`
is always the route pattern rather than the concrete path, so the two are the same value
here; both are emitted because the rule a consumer follows is written against `route`.

A WebSocket upgrade correlates itself. It is an HTTP request with headers like any other,
so `runWsConnection` derives its own correlation and adopts a gateway's `x-request-id`
rather than opening a second identity for a connection that already has one. Deriving it
in the one place a ws connection is set up is what keeps it one identity per connection
instead of one per emitter, and it also carries `transport: 'ws'`, which nothing on that
path previously distinguished.

Verified non-vacuous: reverting `src/` fails exactly the six new correlation assertions
across the three emitters and leaves the thirteen lifecycle ones green.

Closes #84

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:57:39 -05:00
chrnx 7d39aebfab fix(stream): report a stream's lifecycle on every adapter, not only Node
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 28s
`pipeStream` emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame.
`asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and
`app.fetch()` on Node — emitted nothing and called `controller.error(err)`.

Both halves of that were silent. A consumer counting `stream:error` saw zero on three of
the four runtimes while the streams were failing normally, and the client got a truncated
body with no explanation, which from the outside is indistinguishable from a clean end of
stream. The observability guide documents these three events without qualification; on
three runtimes they did not exist.

The error path now frames rather than breaks. Enqueue `encodeError`'s frame, then close
cleanly — the Node behaviour, and the better one: an SSE consumer that received an `error`
event knows what happened, where a transport-level failure looks exactly like the
connection dropping. `controller.error` is kept for an encoder with no error frame to
offer, because then breaking the stream is the only signal left.

`stream:close` is latched. A `cancel` can land after the body already ended, and the three
exits — done, error, cancel — must not each emit their own.

The test drives both adapters from one route table rather than asserting them in separate
blocks, since a table that describes one and then the other is how the two drifted in the
first place. Verified non-vacuous: reverting `src/http/web.ts` fails all four fetch rows
and leaves the three Node ones green, which is the split that says the test is measuring
the adapter and not the framework.

The `sse()` injection test from the previous commit went back to `app.fetch`. It had been
written against `listen()` only because the fetch path swallowed the error — that was a
workaround for this bug, and it is no longer needed.

Closes #83

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:52:42 -05:00
chrnx 7b3fe57590 feat(sse): emit id:, so an EventSource reconnect has something to resume from
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 5s
`sseEncoder` wrote one field. With no `id:` on the wire the browser had nothing to put in
`Last-Event-ID`, so every automatic reconnect rebuilt the route's iterable from its start
and lost the gap in silence — a healthy-looking stream that had simply skipped events.

Half of this already worked and it was worth checking before designing anything: the
request envelope has always carried every header, so a handler could already read
`@header('last-event-id')`. It just always arrived empty, because we never gave the
browser an id to send.

`sse(data, { id, event, retry })` tags a stream item; `sseEncoder` writes the fields ahead
of `data:`. An app that never calls it sees byte-identical output. `event:` and `retry:`
come along because the envelope carries them for free and neither was reachable before.

**green-tea stores nothing.** No buffer, no retention window, no replay. The framework
carries the marker in both directions and the handler decides what the gap means, because
only the source knows: a paged log re-reads from an offset, a live sensor has no past
worth delivering. Framework-managed replay would need a stream identity that survives a
disconnect — which does not exist, since every request builds a fresh iterable — plus a
retention policy no default can get right and an in-process buffer that breaks the moment
there are two instances. This commit is also the prerequisite for any of that: whatever
replay might land later keys on these ids.

An id with a newline is rejected, not stripped. An id is exactly the value most likely to
be derived from a request — a cursor, a page token — and the SSE format is line-based, so
one newline lets a caller append arbitrary fields to somebody else's stream. Stripping
would resume from the wrong place invisibly, which is the failure this whole feature
exists to close, so it throws where the stream can report it.

`ndjsonEncoder` unwraps the payload and drops the fields: a `negotiate` route yields the
same items to both encoders, and NDJSON has no frame to carry them and no resumption
protocol to use them.

Verified non-vacuous: reverting just the two `encode` functions fails the six framing and
round-trip assertions and leaves the validation ones passing, which is the right split.

Closes #46

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:47:14 -05:00
chrnx ccd329d12b perf(boot): run independent providers concurrently
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
`bootProviders` was a `for...of` with an `await` inside, so three providers that share
nothing took the sum of their latencies rather than the longest one. Measured on the
issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after.

The graph already knew. `topoSort` proves which nodes cannot constrain each other and
then throws that away by returning a flat list; `topoLevels` groups the sorted list back
into dependency levels in one forward pass, and boot runs a level with `Promise.all`.
Nothing else about the ordering changes: level N is fully registered and warmed before
level N+1 starts, which is the same guarantee the sequential walk gave.

This is the second thing users get for declaring `needs`/`provides` instead of ordering
`app.use` calls by hand. Pruning was the first. An Express app cannot parallelize its
middleware because nothing declares what is independent — we have that declaration and
were not spending it.

Three things had to survive the change, and each has a test:

- **Teardown stays deterministic.** Registration follows level order, not completion
  order, so the registry running in reverse still gives dependants teardown before their
  dependencies. Following whichever provider settled first would have turned that from a
  guarantee into luck.
- **A failed sibling does not strand the level.** `bootProvider` returns an outcome
  instead of rejecting, and successful teardowns are registered before any failure is
  raised — so a boot aborted by a required provider still leaves whatever its siblings
  opened closeable. Previously they had not started at all; now they may be in flight.
- **A provider that threw gets no teardown**, unchanged: it never provided anything, and
  `dispose()` on a half-constructed one is how a teardown finds a null connection.

Behaviour visible to a bus consumer: `boot:provider:start` no longer strictly alternates
with `:ok`. A level emits its starts together, then its results. That is the truth about
what is happening rather than a change in what is reported.

Verified non-vacuous: reverting `src/` fails the overlap assertion and all five
`topoLevels` cases, and puts the benchmark back at 616ms.

Closes #71

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:32:17 -05:00
chrnx b75158eddc Merge pull request 'Tier 2 for the beta: the lifecycle stream gets a contract, plus a P0 found on the way' (#81) from beta/tier-2 into develop
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 21s
2026-09-01 16:11:13 +00:00
chrnx 0adab69466 docs(changelog): record the tier-2 work in Unreleased
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 14s
The event stream's contract, the read-only `events` token, the reserved framework names,
the unmatched-route label, the budget bookkeeping, and the `onError` crash.

Grouped by what a reader is looking for rather than one bullet per commit: the three
observability issues describe one contract and read better as one entry plus the two
fields it needed.

The reserved names get their own paragraph saying plainly that they **can fail an app
that boots today**, because a changelog that buries a breaking change under a feature
heading is how someone finds it from a stack trace instead.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:08:47 -05:00
chrnx 1c4f3fb8cb perf(http): skip the request-budget bookkeeping when no budget is set
Every request registered a `close` listener and set an acquire flag, including in the
apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true`
unconditionally when the limit is unset and `release()` early-returns for the same reason,
so both the closure and the EventEmitter registration were pure overhead: a per-request
cost, on the hot path, for a feature that is off.

The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the
gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not
counting" alike, which is exactly why a caller reading only the result pays either way.

With a budget configured nothing changes: the listener is what releases a slot when a
client disconnects mid-handler, and it comes back. The guard is about the unset case, not
about dropping the feature, and the test asserts both halves so a fix for one cannot
quietly become a regression in the other.

Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts.

Closes #74.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:01:52 -05:00
chrnx 1e76921d49 feat(di): a read-only events token, and framework names nobody can take
Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:57:47 -05:00
chrnx c00f714aa8 feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.

The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.

The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.

`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.

Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.

Closes #65.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:37:41 -05:00
chrnx 5294e62a5a fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.

This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.

It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.

All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.

Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.

`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.

Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.

Closes #80.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:35:03 -05:00
chrnx 3930804fb3 feat(bus): give request:failed a status, and write down the three-event overlap
One request that throws emits three events, and nothing said which of them to count. The
obvious first implementation counts the failure twice — once from `request:failed` and
once from the `request:end` that follows it, under whatever status it invents for the one
that had none. `route:unmatched` overlaps the same way, so a 404 is two events and one
outcome. Both mistakes are silent: the metrics simply lie.

The division of labour is now stated on `EventPayload`, where a consumer reads it:
`request:end` is terminal, universal and carries the status the client received, so it is
the request counter; `request:failed` means *handler code threw*, which no status can
express on its own since a rendered 422 is also a throw; `route:unmatched` means no route
ran. The last two are additional, not alternatives.

`request:failed` also carries a `status` now, so an error counter can break down by
status without joining back through `requestId` for something the emitter already had.

Getting it required moving the emission after the render rather than before, and the two
reasons are worth keeping: `onError` may turn any throw into any status, so deriving one
from the error would be a guess a custom renderer makes wrong — and the emission sits in
`finally`, so a renderer that *throws* cannot swallow the event. That case is the only one
where the event has no status, and the field's doc says so rather than leaving a reader to
find out.

Closes #64.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:26:00 -05:00
chrnx 5d8363d225 feat(bus): guarantee that every request:end has a request:start
`request:start` had one emitter and `request:end` had three, so the pairing every
consumer would reasonably assume held by accident rather than by promise. The
`maxConcurrentRequests` merge added the first terminal path that breaks it: a shed
request emits `request:end` and nothing before it, because it never reaches `handle()`.

Both shed paths now emit the pair, through one shared `emitShedPair` rather than two
copies — the guarantee lives in one place, and the two adapters already had a duplicate
of this block between them.

## Why the pair rather than documenting `request:end` as standalone

Both were defensible and the alternative was seriously considered. It loses on one
concrete case: the obvious in-flight gauge.

    bus.on('request:start', () => inFlight++);
    bus.on('request:end',   () => inFlight--);

Without the guarantee that drifts negative the moment a server sheds — under load, which
is exactly when an operator is reading it, and it fails by producing a plausible wrong
number rather than an error. Documenting "do not do that" asks every consumer to read
the warning; guaranteeing the pair makes the obvious code correct.

Emitting a `start` for a shed request is not a fabrication, which was the objection worth
answering: the request *did* arrive. The gate refused it before the router, and
`request:start` says a request arrived, not that it routed.

The cost of the guarantee is that it binds every future emitter, and that is real. It is
paid down by `test/lifecycle-pairing.test.ts`, which enumerates every response shape —
200, 404, 500, 413, 204 preflight, and 503 on both adapters — and asserts the pair and
the shared `requestId`. The constraint is now something CI enforces rather than something
a contributor has to remember. Verified non-vacuous: dropping the `request:start`
emission fails the two shed rows and nothing else.

Also writes down, next to `LifecycleEvent` where a consumer reads it, the half of this
that is not new: `request:end` is terminal and universal and is the one to count;
`request:failed` and `route:unmatched` describe the same request and are additional.

Closes #73.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:21:34 -05:00
chrnx 0f2f62d8c1 Merge pull request 'docs(changelog): record the unreleased work, without cutting a version' (#79) from chore/changelog-unreleased into develop
CI / runtimes (bun) (push) Successful in 17s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 20s
2026-09-01 14:59:27 +00:00
chrnx 4c9e606cfb docs(changelog): record the unreleased work, without cutting a version
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 11s
Everything on `develop` since `26.8.0-beta.1` that a user would notice: the request
budget and the connection-drop warning from the contribution merge, `handleSignals`,
the extension-point type exports, the single header resolution, and the two crashes
(the CORS predicate, and the JSR package's missing `require`).

The heading stays `[Unreleased]`. The version bump and the dated section belong to the
cut, not to the work.

Left out on purpose: the two `ci(release)` commits. They change how the workflow spends
a dist-tag and whether it publishes release notes — real, and invisible to anyone
reading this file to find out what changed in the package they installed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:47:57 -05:00
chrnx f08956bea8 Merge pull request 'Tier 1 for 26.9.0-beta.1: the four that block the cut' (#78) from beta/tier-1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 14:44:41 +00:00
chrnx b8b3548f15 perf(cors): resolve the request's headers once, not two or three times
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.

`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.

Measured against the built `dist/`, same script that produced the numbers in the issue:

    GET with Origin      2x -> 1x
    OPTIONS preflight    3x -> 1x
    buildFetch, Origin   2x -> 1x
    GET without Origin   0x -> 0x   (never reached the predicate; unchanged)

The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.

Closes #77.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:27:32 -05:00
chrnx 855e044d2a fix(types): export the extension-point types, not just the extension points
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
`Transformer` was exported and `TransformerFn` was not, so a custom transformer could
be attached but not typed. The workaround is to borrow the type off a value —
`const text: typeof JsonTransformer = ...` — which works and reads like a trick,
because it is one. `ErrorRenderer` and `StreamEncoder`, the two neighbouring extension
points, were both already exported; this one was an oversight rather than a decision.

Checking the rest of the barrel for the same shape turned up four more. A plugin split
into named functions rather than one inline arrow cannot annotate what it receives:
`Plugin` types the arrow, and `PluginApi`, `ScopeApi` and `ScopeNode` — the chain
reached through `api.scope.add`, which is how a plugin contributes to the graph — were
all unreachable. So was `Hooks`, which makes `createApp({ hooks })` typeable only
inline, and `TeardownFn`, the shape every one of those three doors takes.

Types only. Nothing at runtime moves, and no existing export changes.

Covered by a type test that fails to compile if any of them leaves the barrel again,
including the two that were already there — the failure mode this fixes is a barrel
edit nobody notices until a user writes the annotation.

Closes #66.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:15:35 -05:00
chrnx e5d5fb801a feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 14s
The README promised shutdown was *"an extension point, not a SIGTERM handler you
write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the
*content* of teardown, but nothing called `close()`, so every application still wrote
the handler — and wrote it three times, because the spelling is per runtime. Forget it
and the container is SIGKILLed after its grace period, every `dispose()` the registry
so carefully ordered never runs, and nothing reports it.

`createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit.

Off by default, and that is the design rather than caution: a library that installs
process-wide handlers behind your back is worse than one that installs none, because
when the process exits is the application's call. Both halves are now supported and
documented — keep the handler, or hand it over. What is not optional either way is
that *something* calls `close()`, and the README now says so instead of implying the
framework already had it covered.

Declared once on `createApp`, wired per runtime by whichever boot call runs:
`listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their*
server to `app.handleSignals`, which returns a close that also unregisters. On Deno
that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener`
holds the process open, so an app that closed itself would otherwise hang.

Unregistering first also means a *second* signal falls through to the platform default
and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a
teardown that is stuck, and swallowing it for the length of a 10s budget would read as
a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there.

Tested against real processes, because a handler whose job is to exit its own process
cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal
escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`,
which is the API that actually differs. Bun shares Node's `process` path.

Closes #70.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:09:56 -05:00
chrnx 4896ee86d2 fix(jsr): resolve require from source, not from tsup's banner
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 6s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 16s
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.

The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.

Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.

Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.

Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.

Closes #69.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:50:42 -05:00
chrnx bb0b01cf26 fix(cors): deny the origin when the origins predicate throws
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 14s
`CorsOptions.origins` accepts a predicate, and it runs on the request path above the
region where errors convert to a response. A predicate that threw became a rejected
promise nobody awaited, and Node's default for that is to exit — so one cross-origin
GET took the process down, with `onError` never reaching it.

The trigger is a browser: `originAllowed` only runs when an `Origin` header is present,
so the crash is reachable by any cross-origin client and by no test that forgets the
header, which is how it survived a green suite.

Guard the call at `originAllowed`, the single point all four call sites funnel through
(the Node handler, `computeInjected` on both adapters, and the preflight path). A
predicate that throws denies the origin: a lookup that failed has not said yes, and a
broken allowlist must never widen into an open one. The failure is reported through the
app logger rather than swallowed — `HttpOptions` already carries one.

The published behaviour changes for a throwing predicate only. Every other origin shape
is untouched, and the security headers still land on the response.

Amends one test from the `maxConcurrentRequests` contribution, which asserted the old
crash as its baseline while proving the gate does not leak a slot. It still proves that,
against a transient failure that is now answered rather than fatal.

Closes #72.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:39:11 -05:00
chrnx d93037e2a0 Merge pull request 'Merge contrib: cap concurrent requests, from an outside contributor' (#75) from contrib into develop
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 14s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 18s
CI / build (push) Successful in 30s
2026-09-01 13:29:40 +00:00
hgshreyas ff94e55496 feat: cap concurrent requests across runtimes
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 11s
CI / build (pull_request) Successful in 29s
CI / dco (pull_request) Successful in 6s
CI / build (push) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 16s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-31 08:53:14 -05:00
hgshreyas 82e1678dea fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-30 12:55:20 -05:00
chrnx 4b04421ddd Merge pull request 'ci(release): publish the release notes, not just the tag' (#62) from ci/github-releases into develop
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 25s
Promote → GitHub / push-github (push) Failing after 6s
CI / dco (push) Has been skipped
CI / runtimes (edge) (pull_request) Successful in 12s
CI / build (push) Successful in 25s
CI / dco (pull_request) Successful in 3s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 15s
2026-08-19 19:32:14 +00:00
chrnx 0fad12688d ci(release): publish the release notes, not just the tag
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 12s
The repository had two tags and no releases, so the only way to find out what
a version changed was to open CHANGELOG.md and scroll to the right heading.
The release page is where people who do not read changelogs look, and a
repository with tags and no releases reads as abandoned.

Notes come from CHANGELOG.md rather than from the commit range. The section
was written for humans and already exists by the time a tag is cut; generated
notes would restate merge subjects nobody chose. `scripts/changelog-section.mjs`
extracts one version's section and makes its relative links absolute against
the tag — a release body resolves them against the release page, not the
repository, so `./BENCHMARKS.md` would have 404'd.

That script is a parser writing text that cannot be corrected quietly once it
is published, so its boundaries are pinned by a test rather than checked by
eye at release time. Both of the bugs it caught while being written are in
there: a section swallowing the `[label]: url` block that follows the oldest
version, and a relative link surviving into a body.

The step is idempotent like the publishes before it, so a re-run finishes what
is left instead of stopping here, and `--verify-tag` keeps it from inventing a
tag — it attaches to the one that triggered the run and cannot move it. A
prerelease is marked as one, which is what keeps the "Latest" badge off a beta.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:31:05 -05:00
chrnx ead71dc1b1 Merge pull request 'ci(release): spend the publish's one dist-tag on latest while there is no stable' (#60) from ci/publish-under-latest into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / build (push) Successful in 24s
CI / runtimes (edge) (push) Successful in 12s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (bun) (pull_request) Successful in 14s
Promote → GitHub / push-github (push) Failing after 6s
2026-08-19 19:18:20 +00:00
chrnx 19fcc18899 ci(release): spend the publish's one dist-tag on latest while there is no stable
CI / runtimes (edge) (pull_request) Successful in 12s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
`npm dist-tag` cannot use Trusted Publishing. The OIDC exchange lives inside
`publish.js` and nowhere else, so the token it returns is publish-scoped: the
step added in the previous commit got `E401` on v26.8.0-beta.1, after both
registries had already taken the version.

That leaves one npm write per release, and it has to go where it counts.
While no stable exists, `latest` and `beta` mean the same thing — there is
nothing else to install — so `latest` takes the publish, because that is what
a bare `npm install @green-tea/core` resolves to and an untouched `latest`
hands the default install an older build than the one just released. The
channel tag is moved by hand; the step prints the command and AGENTS.md says
when it applies.

This is temporary by construction. Once a stable version exists it owns
`latest`, a beta published afterwards must not drag it backwards, and the
publish goes back to setting the channel tag directly — with nothing left to
move by hand.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:17:12 -05:00
chrnx 7f9e6b19d6 Merge pull request 'ci(release): keep latest on the newest beta, and make a re-run finishable' (#58) from ci/release-dist-tags into develop
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
Release → npmjs / publish-prod (push) Has been skipped
CI / runtimes (edge) (pull_request) Successful in 12s
CI / build (push) Successful in 25s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (edge) (push) Successful in 12s
2026-08-19 19:11:16 +00:00
chrnx 7be26fda5c ci(release): keep latest on the newest beta, and make a re-run finishable
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
While there is no stable release, a bare `npm install @green-tea/core` should
get the same thing `@beta` gets — that is what the docs promise. Since
`1a313c2` a prerelease publishes under its channel tag only, so the next
release would have left `latest` behind on 26.8.0-beta.0: an older build for
anyone who installs without asking for a channel.

`npm publish` sets one tag, and `npm dist-tag` cannot use Trusted Publishing —
the OIDC exchange lives inside `publish.js` and nowhere else. Rather than keep
a long-lived npm token in a secret for one command, the step runs the same
exchange itself: request the Actions id-token, trade it for a short-lived
package-scoped token, move the tag. Both values are masked.

The rule is bounded on purpose. Once a stable version exists it owns `latest`
permanently, and a beta published afterwards must not drag it backwards; the
lookup that decides this is read into a variable first, so a failed request
fails the step instead of passing for "no stable exists".

Both publishes also become skip-if-present. That is not belt-and-braces: the
new step runs after them and can fail, so a re-run has to be able to finish
the remaining work instead of dying on a version npm would reject anyway. The
JSR guard asks api.jsr.io rather than jsr.io/meta.json, which is 404 for a
package with no versions yet — the state this package is actually in.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:10:00 -05:00
chrnx e540752f1e Merge pull request 'chore(release): close the changelog at 26.8.0-beta.1' (#56) from chore/close-changelog-26.8.0-beta.1 into develop
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (deno) (push) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / dco (push) Has been skipped
CI / build (pull_request) Successful in 24s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 24s
CI / runtimes (edge) (push) Successful in 12s
2026-08-19 19:02:33 +00:00
chrnx e86051382d chore(release): close the changelog at 26.8.0-beta.1
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
Everything in `[Unreleased]` ships under this tag, so the section gets its
date one step before the tag exists — the order AGENTS.md now prescribes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:01:14 -05:00
chrnx b8cb684a6b docs: close the changelog at the tag, not when the version is decided
The changelog said [26.8.0-beta.1] - 2026-08-17 with a date, above work that
has never been tagged and is on no registry — npm still ends at beta.0 and
neither forge has the tag. A day of further work then landed underneath it as
[Unreleased], so the file asserted both that beta.1 shipped and that its
contents had not.

Folds that section back into [Unreleased], where all of it actually belongs,
and writes the rule in AGENTS.md so the next version is closed one step before
its tag rather than the day it is decided.

A version number is a plan; a changelog heading is a receipt.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:00:55 -05:00
chrnx 2c838c8753 Merge pull request 'fix(mesh): refuse to export a value the wire cannot carry' (#54) from feat/mesh-transport-guard into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 24s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (bun) (push) Successful in 14s
CI / build (pull_request) Successful in 24s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 4s
2026-08-18 18:39:32 +00:00
chrnx cd4f47486f Merge pull request 'feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one' (#53) from feat/mesh-boot-retry into develop
CI / runtimes (bun) (push) Successful in 22s
CI / runtimes (edge) (push) Successful in 12s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 18s
CI / dco (push) Has been skipped
2026-08-18 18:18:23 +00:00
chrnx ffb5139cae Merge pull request 'feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do' (#48) from feat/mesh-envelope into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (edge) (push) Successful in 12s
2026-08-18 18:00:58 +00:00
chrnx 46342a0aa2 fix(mesh): refuse to export a value the wire cannot carry, instead of delivering an empty object
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 25s
Exporting a provider whose value was a connection pool produced HTTP 200 and
 on the other side. JSON keeps the shape and discards everything else, so
what arrived was an object that passed every truthiness check and had no
methods — and the failure surfaced as `db.query is not a function` at a call
site arbitrarily far from the export that caused it. Nothing warned, at either
end, at any point.

The teapot now checks before sending, which is the only place the evidence
still exists: past encode() a pool and an empty object are the same bytes.

An allowlist rather than a denylist. Date is refused too — it would arrive as
a string rather than the declared type, which is the same silent difference
wearing a smaller costume. Bounded by a scan budget so a large legitimate
payload is never turned into an error by the cost of checking it.

The constraint this makes visible was never written down anywhere: a mesh
export carries data, never behaviour. Export what the handle produces rather
than the handle. That limit is what makes an 'executable provider' (#50) the
missing shape rather than a nicety.

442 vitest / 12 Deno / 7 Bun / edge / JSR dry run. All 5 new tests verified to
fail against the old code.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 12:35:48 -05:00
chrnx 1975a7c03f feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one
CI / runtimes (bun) (pull_request) Successful in 16m11s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
A teapot that is thirty seconds behind and a teapot that does not exist look
identical for the first thirty seconds, and only one of them should stop a
deploy. bootTimeoutMs is that grace: retries with backoff until it passes.

It still fails after that, deliberately. A provider the graph depends on is
not optional, and booting without it would only move the failure to the first
request, where it is a caller's 503 rather than the deploy's error.

The full battery caught what the first cut got wrong: a bad secret was being
retried. That is not a transient failure — it is the teapot's decision, and it
will be the same decision in thirty seconds, so retrying only spends the
deploy's patience to arrive at the identical error. Refusals now fail at once.

Telling them apart without threading close codes through the neutral socket
contract of four runtimes: a peer that accepted the connection and then hung
up before answering rejected us on purpose; one that never accepted it may
simply not be listening yet. That is exactly the distinction needed here.

Retries are logged and emitted as mesh:boot:retry, kept separate from
mesh:disconnect — that one is a link that was up and went away, this one never
came up, and a deploy watching for trouble wants to tell those apart.

437 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 11:28:44 -05:00
chrnx f2cb411eac feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (bun) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 24s
The observability release gave every request an id and lost it at the process
boundary — in the one place a distributed trace is the entire point. The RPC
envelope now carries requestId, traceId and url, and the teapot adopts them
instead of opening its own investigation.

Both fields are optional on the wire, so the protocol version does not move.
That decision needed a rule rather than a judgement call, so the rule is now
written beside the constant: bump when an old peer would misparse or misbehave
silently, not when work happened. Bumping per change would make the number
mean the opposite of what it is for.

Three things found while in here:

- mesh:rpc:error emitted the per-link counter where every other emitter puts a
  name, so the two sides of one failure could not be matched up.
- The teapot had no handshake deadline, so an unauthenticated peer could hold
  a socket by saying nothing, and no frame size cap, so it could make the
  process JSON.parse up to whatever the socket layer allowed — 100 MiB with
  the ws defaults, before authenticating.
- The remote-route envelope was cast from the internal request object, putting
  ip and protocol on the wire as fields the protocol never declared.

The cleartext warning is a warning and not a refusal on purpose: a private
network already doing mutual TLS is legitimate, and green-tea cannot tell it
apart from an exposed one.

4 of the 8 new tests verified to fail against the old code; the rest are the
negative cases, which should pass both before and after. The Deno test drives
the teapot's frame loop with a raw client, because server-side close codes are
where these runtimes have already differed once.

431 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 11:15:54 -05:00
chrnx 1ccbf6cadf Merge pull request 'fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits' (#47) from feat/mesh-reconnect into develop
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
2026-08-18 16:04:54 +00:00
chrnx 6ffbad9825 fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 12s
A dropped link stayed dead for the life of the process. Every RPC answered
503 until the teacup restarted, so deploying a teapot forced a restart of
every teacup depending on it and boot order became load-bearing — a worse
operational property than any gap the docs actually listed.

The Link now outlives any single socket, because the graph captured its rpc
closure at boot and a reconnect that produced a new Link would leave the graph
pointing at the dead one. Backoff doubles from 500ms to 30s with full jitter,
so teacups that went down together do not return in lockstep.

A returning teapot whose manifest no longer exports what the graph was
validated against is refused, not adopted: that graph is already serving, and
a token cannot be validated away after the fact. The link keeps retrying,
since a partial deploy may still restore it, and logs once per distinct
manifest rather than once per attempt. Refusal ships as a named policy
(onManifestChange: 'refuse') so hot reconciliation can arrive later as an
addition rather than as a change of what the default means — these are
separate processes on separate deploy cadences.

close() is terminal. closeLinks runs on shutdown, and a link that reconnected
after the application hung up would leave a process that cannot exit.

Also closes the documented gap where an app-scope export outlived its teapot
with a stale value: a successful reconnect re-registers those bindings, so the
next resolve re-runs the RPC. That invalidation is a named function rather
than inline, because it is the seam a future 'reconcile' reuses.

Tested on all three runtimes rather than on Node alone — Node's ws package,
Deno's global WebSocket and Bun's server-level socket handler are three
implementations, and swapping a socket under a live graph is where they stop
agreeing. 7 of the 9 new Node tests were verified to fail against the old
code; the 2 that pass are the ones that should, since the old code never
reconnected at all.

Mesh stays alpha.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 10:53:24 -05:00
chrnx 6672185ba2 Merge pull request 'fix(shutdown): arm the teardown timer before the callback that clears it' (#44) from fix/teardown-timer-ordering into develop
CI / runtimes (deno) (pull_request) Successful in 16s
CI / runtimes (bun) (push) Successful in 13s
CI / build (pull_request) Successful in 23s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 17s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / build (push) Successful in 27s
CI / runtimes (edge) (push) Successful in 12s
2026-08-18 14:18:47 +00:00
chrnx 198e62944f fix(shutdown): arm the teardown timer before the callback that clears it
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (bun) (pull_request) Successful in 14s
`runTeardown` declared `finish` above the `timer` it clears, so the
reference held only because every caller — the timer's own callback and
`teardown.run().then()` — happens to be asynchronous. That is correct by
timing rather than by construction, which is what #20 asked to remove from
this file; `closeApp` twenty lines below already arms its timer first and
carries a comment explaining why that direction is the safe one.

Reversing the order here leaves both shutdown paths resting the same forward
reference on the same guarantee: setTimeout cannot invoke its callback
synchronously. No behaviour changes.

Closes #20

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 09:16:27 -05:00
chrnx 7d04b2d736 Merge pull request 'chore: back-merge main so promotions can go back to fast-forward-only' (#42) from chore/backmerge-main into develop
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 12s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 23s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 24s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 16s
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 13s
2026-08-17 23:22:22 +00:00
chrnx 51608b0631 chore: back-merge main so promotions can go back to fast-forward-only
CI / build (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / dco (pull_request) Successful in 5s
PR #40 promoted develop to main with a merge commit, which left an empty
merge commit living only on main. It carries no content — its diff against
its own develop parent is empty — but it keeps main out of develop's
ancestry, so the next fast-forward-only promotion cannot run at all.

This merge is a no-op by content and exists only to put that commit back
into develop's history. With it, develop -> main is a fast-forward again,
which is what AGENTS.md requires: no commit is ever born on main.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 18:20:47 -05:00
chrnx bbcc90eb4d Merge pull request 'feat: the trust release — observability, shutdown teardown, routing correctness and the docs split' (#41) from feature/trust-release into develop
CI / runtimes (deno) (push) Successful in 16s
CI / dco (push) Has been skipped
CI / build (push) Successful in 23s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 13s
2026-08-17 23:17:11 +00:00
chrnx 9b5347aa75 fix(observability): correlate requests on Node 18, where there is no global crypto
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 28s
CI / build (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 17s
`engines` promises `>=18`. The global `crypto` arrived unflagged in Node 19.
Between those two facts, `correlateRequest` compiled cleanly against an ambient
`declare const crypto` and then threw `ReferenceError: crypto is not defined` on
the first request of every Node 18 process — which is to say the observability
work made the framework unusable on its own stated floor.

Nothing local could see it. Every developer machine here runs 20 or 22, and
Deno, Bun and workerd all expose the global. CI's Node 18 job caught it on the
promotion pull request, which is the entire reason that job is pinned to the
floor rather than to the current release.

The global stays the primary path, because it is why this file does not simply
import node:crypto: it is the runtime-neutral core, and node:crypto is not
available to all four runtimes. The fallback is reached only where the global is
absent, so workerd never evaluates the require, and the ESM build has a real one
from the createRequire banner already in tsup.config.ts. Verified in both built
formats rather than assumed — esbuild rewrites it to require("crypto"), which is
the same module.

test/node-floor.test.ts stubs the global away to reproduce the floor's condition
on any Node, and was confirmed to fail against the previous code. The bug was
invisible where it was written; this makes it visible there.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 18:11:50 -05:00
chrnx 0218508a96 docs(readme): lead with what the framework owns, not with what it is not
CI / build (pull_request) Failing after 3m33s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 11s
Follows the website copy strategy, translated from marketing register into the
one this file is read in. The strategy's own summary of the change applies
here too: stop selling simplicity because the framework is small, start
selling simplicity because the framework carries the infrastructure.

The hero led with "not a mutable bag threaded through positional middleware".
Middleware ordering was the origin problem, not the whole of what this does,
and a reader who has never hit that pain learns only what green-tea is
against. It now says what it is for: declare what a step needs and produces,
and the framework derives the order, validates the wiring before traffic, and
runs only the slice a route requires.

Added "Who does the work?", the section the strategy ranks first and the file
never had. It is a table of which side of the import each infrastructure
decision lives on, ending with business rules on yours — and it is where the
single runtime dependency now sits, as evidence rather than as a headline. The
number was never the point: fewer moving parts to understand, upgrade,
coordinate and debug is. A framework owning less does not delete that work, it
moves it into your application.

"Batteries included — still one dependency" did both of the things the
strategy says to demote in one heading. It is now "What the foundation already
carries", which is the same list making the ownership argument instead of a
bloat-adjacent one.

Accuracy guardrails re-checked after editing rather than assumed: compile-time
guarantees stay scoped to the typed flow core with decorator wiring
boot-validated, mesh stays alpha, no zero-dependency claim, no benchmark
leadership, no anti-Web-Standards framing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 13:21:44 -05:00
chrnx 41c1f4308b chore(release): cut 26.8.0-beta.1
package.json and deno.json both still said 26.8.0-beta.0, which npm already
has. Publishing would have been rejected there and — the expensive half — JSR
versions are immutable, so a wrong one can never be replaced.

The changelog section is closed at today rather than left under Unreleased,
because what it now contains is the whole of this release: the observability
contract, shutdown teardown, the dot-segment behaviour change, and the two
fixes on the fetch and shutdown paths.

The documentation repository is tagged 26.8.0-beta.1 alongside, and that
number means the same thing there: not a version of the site, but the core
release its pages describe. Cutting the two together is what makes the version
a claim that the release is documented rather than only shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 13:05:27 -05:00
chrnx bb75cabeea docs(changelog): record the release's largest feature, which was missing entirely
Unreleased carried two entries for the 81 commits since v26.8.0-beta.0, and
the observability contract was not one of them — the feature four independent
reviews named as the project's biggest gap, and the reason issue #10 existed,
had no changelog presence in any version. Someone deciding whether to upgrade
would have read the release as a shutdown fix.

Also added, in the order a reader needs them rather than the order they landed:

Changed: `.` and `..` in a request path now resolve instead of 404ing. This is
a behaviour change and belongs under Changed rather than buried in Fixed — it
is Node-only, it ends a divergence where the same bytes reached different
routes per runtime, and it is worth telling anyone whose proxy matches on the
literal path that the proxy and the application no longer agree.

Fixed: the BodyInit narrowing on the app.fetch path, which is the path Deno,
Bun and the edge all use, and the shutdown timer ordering that left a
ReferenceError waiting for whoever touched it next.

Found by diffing the public surface at the tag against HEAD rather than
rereading the file. `createApp` gained five options and the package eleven
exports since the beta; the entries above are what had no home.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:50:37 -05:00
chrnx bead3c1569 docs: make the docs rule followable by the people it addresses
Two problems with the rule added earlier today, both found by asking what it
means for the beta rather than whether to automate it.

green-tea is public and green-tea-docs was private, so CONTRIBUTING.md — read
by external contributors — pointed them at a repository that answered 404 and
asked them to change a page they could not see. The repository is now public,
which is what makes the rule possible at all; nothing in it was ever private,
since the history came from this repository's own website/ directory.

And "in the same pull request" cannot be done: a pull request does not span
two repositories. It is a companion pull request, linked to the first, and
both documents now say so.

Added the escape hatch the rule was missing. A contributor who does not want
to write the docs change can say so and a maintainer writes it — what this
line exists to prevent is an API change nobody mentions, not an unwritten
page, and a rule with no honest way out gets ignored rather than followed.

Neither the automation decision nor the accepted risk changes. The link check
stays rejected on the measurement recorded in the trust-release plan.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:38:09 -05:00
chrnx 0414aff665 docs(plans): reject the docs link check, and record what measuring it showed
It was recommended in this plan as the automated guard worth building. Building
enough of it to decide argued the other way, and the reasoning is worth keeping
so the next person does not spend the afternoon rediscovering it.

The narrow version is clean and useless: all 24 symbols the pages import from
@green-tea/core exist among the package's 101 exports, so it finds nothing —
and it structurally could not have caught #18, the one incident there is.
That was close() gaining an option the docs never mentioned. Imports are the
part that does not drift.

Widening it to options and methods produced 17 findings and all 17 were false.
A regex cannot separate a nested tls: { key, cert } from a top-level option, or
prose describing Express's app.use() from a green-tea call. A check that cries
wolf 17 times out of 17 is worse than none, because people learn to skip it.

Type-checking the code blocks would catch the real class, and costs the
documentation repository a dependency on the framework plus examples that must
compile — buying the guarantee back by spending the independence the split was
for. The accepted risk stands, now chosen rather than defaulted to.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:32:01 -05:00
chrnx 21765c2a47 docs: put the docs-drift warning where nobody can miss it
The rule was already in both READMEs, and in both it was a subordinate clause
at the end of something else — a trailing "because nothing fails when the two
disagree" here, a closing section titled "The seam this repository opens"
there. Written, and easy to read past.

Both are now a callout: what breaks, that nothing tells you, and what to do
instead. The docs repository's moves to the top, above how to run it, because
someone opening that repository is usually about to edit a page.

Deliberately not in the marketing site. That risk belongs to whoever changes
the API, not to whoever is deciding whether to try the framework.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:17:30 -05:00
chrnx cd6e2f073f docs: put the docs-drift rule where a contributor reads it
Task 4.4's obligation was to state the risk the docs split opens, and the
first pass met it in the two places that publish rather than the two that
govern: both READMEs. The core README's copy sits in "Docs & development", a
section a user reads and a contributor about to rename a decorator does not.

AGENTS.md and CONTRIBUTING.md both already carried "New public API needs a
note in README.md". Both were written before the split and neither was
updated for it, so the two documents actually read mid-change said nothing
about the new repository — the rule existed everywhere except where it applies.

Both now name green-tea-docs and carry the reason, because a rule without one
is the first thing dropped when a change is nearly finished. #18 is that
reason, and it happened while the two still lived in the same repository.

Neither automated option was built, and the plan now records which is worth
building and why: a link check against the published package targets #18's
real failure mode — a page naming a decorator, a createApp option or a method
that no longer exists — and needs only the identifiers in the pages' code
blocks compared against the package's exports. It catches lies rather than
staleness. A docs job triggered from core releases is weaker: it fires after
the API has already shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:11:29 -05:00
chrnx 38b73cebce docs(readme): say which parts are settled and which still move
The last thing a reader needs before betting on a beta, and the one thing
Honest scope did not answer: it admits what is missing, not what is likely to
change under them.

Present state only. No dates, no delivery commitment, and deliberately not a
roadmap — this is one person's spare-time work, and a schedule it cannot keep
would cost more trust than the schedule earns. The API freeze stays declared
under **next**, untouched, and gets planned near the RC.

Every tier is read off the history rather than asserted. The graph is settled
because graph.ts and container.ts have not been touched since the beta
hardening on 7 July, and because the changes to metadata.ts since then only
add decorators (@Head, @Options, @Html) rather than redefine the ones that
were there. The plugin API is listed as moving because it moved this week.
The pipeline context is listed because 4081106 made it one object mutated in
place, which changed what a step that captured it observes — a real semantic
change, not a perf note, and worth a reader knowing.

Two claims the trust-release plan proposed are not made. It grouped decorator
syntax with the volatile things; the volatility there is TC39's, not ours, and
README already explains it. And it listed the CLI, which ships from its own
repository on its own version line, so nothing here can honestly speak for it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:56:50 -05:00
chrnx 62d0b7aa3a test: execute the circuit-breaker recipe the docs publish
The recipe closing #13 lives in the documentation repository, which imports
nothing from here — so nothing fails when the page and the framework drift
apart. That is the seam Phase 4 opened, and a worked example that quietly
stops working is the worst version of it: it is the page a reader trusts most,
because it looks like code that ran.

This executes the three claims the page rests on rather than asserting them in
prose. That breaker state survives across requests, which is the entire reason
the recipe uses a provider and not a step. That the window re-opens after it
elapses. And that a failed trial in half-open re-opens immediately instead of
making a recovering upstream earn the full threshold again.

Beyond the file list Phase 5 asked for, which named only the guide page. Kept
because it is small and it turns Task 4.4's written rule into something that
fails, for one page at least.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:44:49 -05:00
chrnx 24feca481c feat: shutdown teardown for plugins, providers and applications
Closing a connection meant writing process.on('SIGTERM') by hand: closeApp
drained the server and mesh links and knew nothing about the graph, and the
Bus had no shutdown event at all, so a plugin could not even observe that the
app was going away.

Implements docs/plans/2026-08-17-shutdown-teardown-design.md, D1-D8.

Three doors into one registry, with one order and one failure policy — a
@Provider may declare dispose(), a plugin may call api.onShutdown(fn), and an
application that wants neither passes createApp({ hooks: [{ onShutdown }] }).
Shipping only the plugin half would have frozen the public API around the less
common case: the thing that holds a database connection is a provider.

Callbacks take no arguments. Whatever needs closing is already in the closure
that registered it, so nothing crosses a scope and the registry needs no
container, app reference or transport. That is what keeps this a registry
rather than a second event bus — Bus.on is synchronous and emit swallows
failures on purpose, and a teardown needs the opposite of both.

Provider dispose() is registered as the provider boots rather than as it is
collected, so reverse-registration is reverse-topological order for free: a
cache that needs db closes before the db it is holding, with no second sort to
keep in step. It registers inside the try, so a provider that failed to boot is
never disposed — nothing it might close was ever opened.

Teardown runs after the drain, because an in-flight request may still be using
what a teardown is about to close, and inside the same timeoutMs, because that
number is a promise about when close() returns. teardownTimeoutMs reserves a
slice of that budget rather than extending it, and is rejected at boot rather
than clamped.

Node, Deno and Bun reach it through the close() each runtime actually uses.
app.close() returns at its no-server guard everywhere but Node, so the Deno and
Bun adapters chain it after their own drain — and app.close() now runs teardown
on that path too, since an app served through app.fetch still booted providers
that opened things. The registry drains once, so both entry points are safe.

Edge gets a doc comment and nothing else. workerd has no shutdown to intercept;
a best-effort call on an event that does not exist would be worse than saying so.

Recorded in mountPlugin's comment while widening it: "isolation is structural"
is a guarantee about the registration surface, not about the request context. A
plugin's step already receives the live context and can overwrite keys in it.
Pre-existing, unrelated, and now written where the next reader will look.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:37:31 -05:00
chrnx bfe8b66127 ci: run the JSR gate on every push, not only on a release tag
release.yml has always run `deno publish --dry-run` before publishing to
either registry, and keeps doing so — that copy is the last thing standing
between a tag and a JSR version number that can never be replaced.

It runs too late to be feedback, though. A slow type in the public API or a
Deno type error lands on main in silence and surfaces while cutting a
release, which is the same "least time to judge a fix" the audit steps are
already ordered to avoid. The workflow made that argument for advisories and
not for the registry that type-checks us.

This matters more in the next few commits than it did in the last hundred:
Task 2.5 adds Hooks, TeardownFn and PluginApi.onShutdown, and exported types
are exactly what the slow-types check polices.

It is a second compiler over the same source rather than a packaging
formality. `npm run typecheck` is tsc with this repo's config; this is Deno's
checker with Deno's lib, and it is what found the BodyInit hole on the fetch
path that tsc accepted. JSR serves src/ directly, so what it rejects is what
a JSR consumer would have received.

Measured at 0.68s against 2.0s for the whole vitest suite, so it goes in the
runtimes job's Deno leg, which already installs Deno.

test:all covers the same ground locally. npm test stays Node-only on purpose
— it is the loop you run constantly, and booting three more runtimes into it
would tax every run to catch what CI already catches on every push. Verified
end to end: 393 vitest, 9 Deno, 5 Bun, edge, and the dry run, in 6.1s.

It passes --allow-dirty and CI does not, deliberately: locally you are
checking work in progress, and in CI a checkout that is not clean is worth
failing on.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:21:43 -05:00
chrnx 78b5034936 docs(plans): drop 4.5.3 — the decorator warning is already documented, and the reason given for it was wrong
Two corrections to the phase added an hour ago.

The task asked for documentation that exists. README.md:233 "Why legacy
decorators" and concepts/the-graph.md:43 in the docs repository both already
carry the argument, and carry it better: parameter decorators are
deliberately absent from the TC39 Stage 3 proposal, so a handler taking
`@param('id') id: string` is only expressible with legacy decorators, and
Stage 3 means the replacement is not finalized either. Writing a third,
shorter version of that in Honest scope would have made it worse.

The task also justified itself with a claim that is false. It said the
framework depends on emitDecoratorMetadata. It does not:
`grep -rn 'design:type\|design:paramtypes' src/` returns nothing. The flag is
set in tsconfig.json and deno.json, but no design:* reflection is read
anywhere in src/ — argument positions are recorded explicitly. Both documents
already state this, which is how the error surfaced.

What survives is a note rather than a task, because the warning arrives in CI
together with the new gate and would otherwise read as something the gate
found.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:19:41 -05:00
chrnx a5c1fda886 docs(plans): add Phase 4.5 — move the JSR gate off the tag
Task 2.5 adds public API, and exported types are what JSR's slow-types check
polices. Writing that surface with no JSR gate on pull requests means finding
out at release time whether the shape is publishable, so the phase is
numbered as an insertion and says it runs first.

The first reading of this was wrong and the correction is the useful part:
release.yml already runs `deno publish --dry-run`, before either registry
ships, and a dry run passes today with the slow-types check included. The gap
is not a missing gate, it is when it runs — only on a version tag, so a
Deno-typecheck break or a slow type lands on main in silence and surfaces
while cutting a release. That is the moment release.yml's own npm-audit
comment identifies as having the least time to judge a fix; the workflow
makes that argument for advisories and not for JSR.

Measured rather than assumed: the dry run takes 0.68s against 2.0s for the
whole vitest suite, so it goes in the runtimes job's Deno leg, which already
installs Deno, and needs no more thought than that.

npm test stays Node-only. The runtimes job already covers Deno, Bun and edge
on every push, so they are not unguarded — what is missing is one command a
contributor can run before pushing, which is test:all.

Also recorded: every dry run warns that experimentalDecorators is deprecated
and may be removed. Nothing to fix, no workaround worth inventing early, but
it is a dependency on a deprecated compiler option in a runtime we publish
to, and it belongs in Honest scope rather than in a warning nobody reads.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:44:43 -05:00
chrnx e778f62902 docs(plans): settle D8 as a reservation, and plan the implementation
D8 was the one decision left open: the teardown shares close()'s budget and
may never exceed timeoutMs, but whether lowering teardownTimeoutMs reserves
its slice or merely caps it was never stated.

It reserves. A cap only bounds how long teardown may run and does nothing
about the case the decision exists for — a drain that spends the whole
budget leaves teardown zero milliseconds and the connection stays open.
Reserving is what makes the option a guarantee rather than a ceiling on
something that may never get to run.

The plan orders the work so nothing is observable until close() is wired in
Task 4, and puts the Deno/Bun parity at Task 5 rather than last, because it
is the task most likely to surface something the design did not foresee and
finding that out early is worth more than a tidy sequence.

Two notes carried into it for whoever executes it. Provider dispose() is
registered as the provider boots rather than as it is collected, so the
reverse-topological order D5 asks for falls out of the registry's reverse
registration rule instead of needing a second sort. And the Deno and Bun
suites are not part of npm test, so that task cannot be called done on the
strength of vitest passing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:40:32 -05:00
chrnx 9f72604cbb docs(plans): design the shutdown teardown surface, before any code
Task 2.5 has been open since it was raised while deciding #15, deliberately:
it needs public API, and the API freeze is the next milestone.

Three things the design settles that the task description did not anticipate.

Teardown reaches the graph through hooks, PluginApi and a provider dispose(),
but all three are doors into one registry with one order and one failure
policy. Shipping the plugin half now and providers later would freeze two
mechanisms with different semantics around the less common case: the thing
that holds a database connection is a provider, not a plugin. The hooks
framing also means PluginApi's signature never changes, so nothing breaks at
all, which widening it directly would not have achieved.

Callbacks receive nothing. State lives in the closure that registered it, so
no handle crosses a scope and no container, app reference or transport is
needed. That is what makes this a registry rather than an event bus.

It fires from each runtime's real close, not app.close(), which returns at
its no-server guard on everything except Node. Edge cannot participate at all
and that is documented as a capability difference rather than hidden.

Recorded while verifying: "isolation is structural" protects the registration
surface, not the runtime context. A plugin's step can already overwrite
context keys, and a plugin mounting before provideBuiltins can replace the
logger and rooms builtins. Pre-existing and unrelated to teardown, noted so
the finding outlives the conversation that produced it.

D8, the shared timeout budget, is marked open rather than settled: whether
lowering teardownTimeoutMs reserves its slice or merely caps it was not
decided, and the two differ in whether a slow drain can starve teardown of
the time it needs.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:32:23 -05:00
chrnx 101c4fe65a chore: move the documentation site out to its own repository
website/ is now github.com/Expressive-Tea/green-tea-docs, carrying its own
history — 31 commits, extracted with `git subtree split`, not squashed into
an import that pretends the pages appeared all at once.

What this repository gives up is real and worth naming: the site had no
deploy pipeline at all, and CI here was the only thing proving it still
built. That is why the new repository got a build gate and a tagged release
before this deletion landed, rather than after.

Removed with it: the three website steps in ci.yml (including the second
setup-node that re-pinned 22.12 purely for the docs build — the core job
stays on 18, the minimum supported version), the two package.json scripts,
and the .astro/ and website/dist/ ignore rules that now belong over there.

SECURITY.md pointed at `website/` as an out-of-scope path; it now points at
the repository, since the path no longer exists to be out of scope.

The split trades a CI coupling for a drift risk — nothing fails now when
the docs and the API disagree. Both READMEs state the rule that replaces
the build: a change to public API updates the page documenting it. That is
the weakest of the options considered, and it is written down rather than
assumed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:05:04 -05:00
chrnx a4bb3c02d6 refactor(http): resolve each request once, in the core that already routes it
Both adapters routed every request themselves, and then handle() routed it
again from the same inputs — a four-route app walked its table 2.5 times
per request. Neither side was wrong: an adapter must know the route to
decide whether to read a body, and the core must know it to dispatch.

The cause was the shape of the handoff. NeutralRequest carried an
already-parsed body, so producing one was the adapter's problem, and every
policy that depends on the matched route came with it — these four chains
were written out in server.ts and web.ts character for character:

    matched.def.maxBodyBytes   ?? opts?.limits?.maxBodyBytes ?? 1_000_000
    matched.def.bodyDuplicates ?? opts?.bodyDuplicates       ?? 'last'
    matched.def.maxParts       ?? opts?.limits?.maxParts     ?? 1000
    opts?.limits?.maxBodyBytes ?? 1_000_000

A fifth knob, or one changed default, meant editing both or letting the
runtimes quietly disagree about limits.

Handing over the ability to read rather than the result moves the decision
to where the route is already known. What stays in an adapter is what
genuinely differs between runtimes: getting bytes in, putting bytes out.
Enforcement stays with the reader too, because Node aborts an oversized
upload as chunks arrive while a fetch runtime can only measure what
arrayBuffer() already resolved — passing the limit in preserves that.
413/400/501 keep their exact current shape, Node's connection: close
included; it now has the test it never had.

Measured through app.fetch, both versions in one process, interleaved:
40 routes with the match declared last, 3.89 -> 3.58 us (-8.2%). One
route, where there is no second scan to save, is unchanged.

The first cut of this was 13% SLOWER, and the reason is worth recording:
a per-request closure for the reader plus the error-context object it
captured cost 250 ns, and the async frames around a body that did not
exist cost another 215 ns — together more than the duplicate scan the
whole change removes. The reader is now built once per server and takes
the runtime's request as an argument, and a bodiless request touches no
promise on this path at all.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:46:57 -05:00
chrnx 0c9f8a545e fix(router): route dot segments the same way on every runtime
The same bytes on the wire reached different routes depending on where
the app ran. `GET /public/../admin` hit a `/admin` route under Deno, Bun
and workerd, and 404'd under Node — 200 vs 404 for one request.

The fetch-based runtimes resolve dot segments inside the `Request`
constructor, before green-tea is handed anything: `new Request(
'http://x/public/../admin').url` is already `http://x/admin`. Node's raw
target has no such step. Rejecting outright — the stricter policy, and
what this module already does for `//` — is not implementable on three of
the four runtimes, because the raw target is unrecoverable there. So Node
converges on the rule the other three cannot opt out of.

`%2e` is a dot to the URL parser, so the encoded spelling resolves too;
leaving it out would keep it as a way to reach a route the plain spelling
resolves away from.

Cost is gated: paths with no `.` and no `%` pay two indexOf scans
(20.0 -> 21.7 ns for `/hello`), a literal dot pays the regex (35.5 ns),
and only real dot segments pay the split (103.6 ns).

The existing parity suite could not have caught this — its `both()`
helper goes through `fetch()`, which normalizes the URL before it reaches
the wire. The new cases write the request line to a socket by hand.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:35:26 -05:00
chrnx e625d5c881 perf(router): stop the route scan at a match nothing can outrank
matchRoute evaluated every registered route before answering, so `/hello`
cost the same whether it was declared first or last among 32 routes —
1227 ns against 1237 ns. That is ~38 ns of scanning per registered route
on every request, growing with the route table, and the benchmark app has
the smallest table any real service would have.

Specificity ranks a literal segment above every other kind, so a pattern
made only of literals cannot be outranked by anything else matching the
same path, and an equal rank keeps registration order — which is the
route already in hand. Finishing the scan only re-derives it.

The path split moves out of matchCompiled for the same reason: `split` +
`filter` ran once per candidate route on every request, always producing
the same array. Doing it once per request is 63.7% off a 32-route scan
that early exit cannot help at all (a :param match, which must be
compared against the rest of the table).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:35:06 -05:00
chrnx 5fafe97bc5 docs: correct the observability cost, and record why three earlier numbers were wrong
The published figure was -3.9%. It was measured sequentially rather than
interleaved, and the machine drifts 12% across a session as it warms, so run
order was indistinguishable from effect. Two later attempts to correct it were
also wrong: 0.8% had the same flaw, and -6.8% compared 7bd11bf against HEAD,
which differ by observability *and* three performance fixes pulling the other
way, then reported their net as if it were one of them.

Measured properly, alternating round by round between 7bd11bf and 523e318 (the
last commit before those fixes): +7.0% of the framework's own per-request work,
about 0.29us, roughly 2% of a request over a real socket. Ranges do not overlap.

The guide no longer quotes absolute throughput from this laptop. The reference
numbers come from a two-box setup, and single-box loopback figures invite a
comparison that is not valid.

D7's shape survives: the cost is fixed per request, not per step, because
per-step work is skipped when nothing subscribes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:03:07 -05:00
chrnx 8d8ef7ed09 perf(http): look injected header keys up directly instead of rebuilding a Set
mergeInjectedHeaders rebuilt a lowercased Set of the injected header keys on
every response: an array from Object.keys, a mapped array from toLowerCase, and
a Set from that. Three allocations to answer a question the object already
answers.

The lowercasing was the redundant part. Every key `injected` can hold is written
as a lowercase literal in src/security.ts — buildSecurityHeaders and resolveCors
are its only sources — so the mapped array was a copy of the keys it started
with.

hasOwnProperty rather than `in`: a handler may legitimately send a header named
constructor or toString, and `in` would find those on Object.prototype and drop
them silently.

146.4ns to 55.9ns in isolation; -3.2% end to end over five interleaved rounds,
with all five pairs favouring the change.

Third of three fixes from the same profile, and all three are one pattern:
work done unconditionally for a case that rarely or never applies — validating
encoding that is almost never malformed, parsing a query string that is not
there, lowercasing keys that already were.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:57:37 -05:00
chrnx 0c5decbeae perf(router): skip query parsing when there is no query string
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.

92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.

Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.

Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:55:46 -05:00
chrnx 86dd3fe9b6 perf(router): stop decoding every path segment to throw the result away
normalizeRequestPath ran on every request and validated percent-encoding by
splitting the path and calling decodeURIComponent on each segment, discarding
every result — matching is done on the raw path. Two array allocations and one
decodeURIComponent per segment, per request, to prove that a string nobody
decodes could be decoded.

Measured in isolation: 95.8ns for /hello, 342.7ns for a six-segment route. The
guard costs 15.7ns and 6.7ns for the same two paths.

Same validation. decodeURIComponent throws on the first malformed % sequence
wherever it appears, so one call on the whole string catches what per-segment
calls caught, and %2F inside a segment decodes fine either way. Only the throw
was ever used. The existing tests for malformed encoding and repeated slashes
pass unchanged.

Found by sweeping all 178 commits between fe1831a and the observability work
after the regenerated benchmark showed green-tea down ~20% since July while
raw-http, fastify and nestjs-fastify reproduced their July numbers within 1.4%
on the same run. The sweep put a +11.8% step at 9a61ba8 "complete HEAD and
OPTIONS semantics", which is where this function entered the request path.

Effect: -6.2% in-process request latency, from twelve interleaved measurements
whose ranges do not overlap (OLD 4.253-4.425us, FIX 4.035-4.151us). A first
attempt measured with-then-without and produced the opposite sign, so the
interleaving is load-bearing, not ceremony. Expect roughly 2% over a real
socket, which is below that harness's own noise floor.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:44:35 -05:00
chrnx 523e3184b0 docs(plans): record that the timing model was wrong in shape, not just magnitude
D7 predicted ~0.25% per step and called it invisible. Measured over a real
socket it is -3.9% on JSON hello and -2.1% on a three-step pipeline: the route
with *fewer* steps loses more, which falsifies a per-step model rather than
just its constant. Per-step work is skipped when nothing subscribes, so what
remains is a fixed per-request cost that a shallow route amortises over less.

The decision survived, for a better reason than it was made with: there is
nothing per-step left to make optional.

Also records the two regressions that measurement caught and reasoning did not,
both larger than anything the design anticipated — a second async frame in
handle() at 0.43us per request, and a closure allocated per request inside
correlateRequest at 0.16us. On this path an extra promise costs more than any
amount of bookkeeping.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 15:07:39 -05:00
chrnx 92987d0a24 docs(observability): document the contract, and retire the sentence that denied it
Task 8. README.md led its Honest scope section with "No observability layer,
either." — the single most load-bearing sentence in the CTO assessment, and now
false. It says what exists instead, and keeps being explicit about what does
not: no metrics registry and no OpenTelemetry exporter in core, because core has
one runtime dependency and intends to keep it.

Adds a guide covering the parts that are contracts rather than implementation
details, since those are the ones a reader gets wrong: route labels carry the
pattern and never the concrete path (labelling metrics on raw URLs is how you
take down a metrics backend), request:end fires when the handler returns rather
than when a stream closes, and streams emit lifecycle events only.

The plugins guide was titled "Plugins & observability" and carried a partial
event list that had already drifted. It now covers plugins and points at the
guide for the vocabulary, with the correlation note it was missing.

Includes the measured cost, because a performance claim without a number is
marketing: -3.9% on JSON hello, -2.1% on a three-step pipeline, and the reason
the shallower route loses more.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 15:06:54 -05:00
chrnx e052d5ba8f feat(observability): request-level events, and request logging that reads them
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.

handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.

route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.

logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.

The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.

Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:57:42 -05:00
chrnx df460f01dd feat(observability): an injectable logger, and a lint rule that keeps core off console
Task 4. createApp({ logger }) accepts any Logger; the default writes structured
JSON, or a readable line on a TTY, decided once at construction rather than per
record. It writes through console, which is what lets core have a logging
contract while reflect-metadata stays the only runtime dependency.

Four levels, because four have callers. Core's diagnostics were all warn — every
one of the eight console.warn calls — and request logging adds info and error.
No trace, no fatal: a level nothing emits is a decision handed to the user for
no reason.

Registered rather than declared as a provider. Provider boot failures are
reported while the graph is still resolving and shutdown warnings after it is
gone, so a logger that lives in the graph cannot cover either end. It is also
registered as a builtin provider, so @needs('logger') reaches the same object —
one instance, two access paths — and exposed on App so serveDeno/serveBun report
through the application's logger instead of past it.

The [green-tea] prefix moves out of the prose into a `name` field: an aggregator
filters on a field and cannot filter on a substring of a sentence. Context that
was interpolated into messages is now structured alongside them.

#10 asks that nothing in core call console directly. That is now a lint rule
scoped to src/ rather than a grep somebody has to remember, with src/logger.ts
exempted because being the console sink is its entire job. Verified it fails on
a planted console.log.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:51:33 -05:00
chrnx 7b0a3d4e24 docs(observability): record why randomUUID is the fast option, not the lazy one
Benchmarked the alternatives rather than leaving the question open. Every
supported runtime already batches entropy behind randomUUID, so the intuitive
replacements lose: Math.random() twice into base36 is 3.5x slower at 265ns
because the string work dominates, an unbatched getRandomValues is 472ns, and
a uint32 pool through toString(36) is 114ns.

The only cross-runtime improvement is a hand-rolled entropy pool with a hex
lookup table at 50ns, which saves 26ns — 0.26% of a real 10.19us request. Not
worth owning an entropy pool for. Buffer.toString('hex') matches it but is
Node-only, which this file cannot be.

Table left in the code so the next person does not re-run it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:45:17 -05:00
chrnx dabab1812b perf(observability): hoist a per-request closure out of correlateRequest
The `first` helper was declared inside correlateRequest, so it was allocated on
every request. It captures nothing, so module scope is where it always
belonged.

Measured at 0.16us against a ~4.4us in-process request — 45% of the entire
remaining observability overhead, from one line. Total overhead is now +0.24us
rather than +0.44us, which against the 10.19us of a real socketed request is
~2.4%.

Ablation of what is left, so the next person does not repeat it: randomUUID is
0.16us of the 0.24 and the other 0.08 is the header read, the extra properties
and three hasListeners lookups. Building the correlation literal per request
costs nothing measurable — V8 keeps it on the stack — so do not go optimising
that one.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:42:13 -05:00
chrnx 633ef58032 perf(observability): do not build event payloads for an empty room
The correlation work regressed the in-process hot path from 4.52us to 5.43us
per request, ~20%. The design predicted 0.25% per step and was wrong by more
than an order of magnitude, so recording what the measurement actually said:

  spreading correlation into payloads   ~197ns   <- the cost
  crypto.randomUUID()                   ~170ns in place
  try/catch inside the step loop          ~2.6ns <- not the cost

emit() cannot avoid the first: its argument is already built by the time it is
called. Only the caller can decline to build it, so Bus.hasListeners lets it,
and runSteps hoists the check out of the loop since listeners are registered at
boot. An application subscribing to nothing now pays a branch instead of four
payloads and three clock reads for an audience of nobody.

That recovers half. 4.96us remains against 4.52us — ~10% in process, ~4.5%
against the 10.19us of a real socketed request. Two ways to shave the rest were
measured and both rejected in comments: a lazy requestId is defeated by the
first spread, and a boot-prefix counter is 5x cheaper but trades the standard
identifier shape for ~1.7%. Neither earns its complexity yet.

The remaining cost is the feature, not an accident: correlation only exists if
something carries it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:26:16 -05:00
chrnx 2c47ee8896 feat(observability): correlate and time the lifecycle event stream
Tasks 1-3 of the observability plan. The Bus already had 19 emission points;
what it lacked was any way to tell which request an event belonged to, which
made the whole stream unusable under concurrency.

Every per-request event now carries requestId, traceId, route, method and
transport, and request:step:leave carries durationMs — a field that has been
declared in EventPayload since the beginning with nothing ever writing it.

Identity is derived in the adapters rather than in handle(), because both read
and size-check the body first: a 413 is answered without handle() ever seeing
the request, so generating there would leave exactly the failures an operator
most wants to correlate with nothing to correlate them by. An incoming
x-request-id is adopted rather than replaced, and traceparent is carried
verbatim — core implements no propagation spec.

Timing takes N+1 readings for N steps, since one step's end is the next one's
start. Measured at 25.2ns per step against a ~10.19us request.

request:step:error now names the step that actually failed. It reported
name: 'pipeline' before, discarding the one fact it exists to carry, because it
was emitted from the outer catch where that is all that is known. The outer
catch emits request:failed instead: one marks the span, the other the trace.

route carries the matched pattern and never the concrete path. Labelling a
metric on raw URLs gives unbounded cardinality and takes down the metrics
backend rather than the app, so it is a contract, with a test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:20:44 -05:00
chrnx 7bd11bff27 docs(plans): implementation plan for the observability contract
Eight tasks from the reviewed design, ordered so the correction lands before
anything consumes it — a logger built on uncorrelated events would grow its own
notion of request identity, which is the failure the design exists to prevent.

Two placement details worth having settled in writing. requestId is generated
in the adapters rather than in handle(), because both read and size-check the
body first, so a 413 never reaches handle() — generating there would leave
exactly the failures an operator most wants to correlate without an id. And
step timing takes N+1 timestamps for N steps, since one step's end is the next
one's start; the design measured that against the naive 2N.

Task 7 benchmarks the hot path and says outright that if the measurement
disagrees with D7, the design changes rather than the number being quietly
kept.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:08:11 -05:00
chrnx d324ecfcb4 docs(plans): settle the three open questions in the observability design
D6: a request span ends when the handler returns, and stream events carry its
requestId. Ending it at stream close would mix 2ms buffered requests with
hour-long SSE connections in one latency distribution; connection duration is
already readable from stream:open/close once they can be joined. Same boundary
#21 chose for its concurrency gate — the framework should not disagree with
itself about when a request is over.

D7: per-step timing is always on. Measured rather than argued: performance.now()
at step boundaries costs 25.2ns per step against a 10.19us request, or 0.25% —
below the 0.3% run-to-run CV of the project's own benchmark. A flag would buy
two code paths for something the harness cannot detect. The measurement also
settles Date.now(), which is both slower (28.6ns) and coarser.

D8: request logging is a Bus subscriber, wrapped to fall back to console. One
path, composable as #10 asks, and the wrapper closes the hole that emit()
swallows listener failures by design — the Bus keeps its guarantee without
buying it with silence.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:06:51 -05:00
chrnx 8c3844e577 docs(plans): design the observability contract for #10
The issue says green-tea ships no logging, metrics or tracing contract. The
mechanism is actually already there — Bus has 19 emission points across boot,
pipeline, streams, mesh and plugins, and plugins already subscribe to it. What
is missing is narrower and worse: no event carries request identity, so under
concurrency step events cannot be attributed; durationMs is declared in the
payload and written by nothing; there are no request-level events for step
events to hang from; and a failing step reports as name: 'pipeline'.

That reframes the work. A logger, a metrics exporter and an OpenTelemetry
bridge are not three features, they are three consumers of one corrected event
stream — which is a sharper reason for #10's 'one design, not six' than the
issue had, and it puts most of the work in bus.ts and pipeline.ts rather than
in new files.

Five decisions settled with their reasoning, including why the logger cannot be
an ordinary provider (it must outlive the graph to report the graph failing to
boot) and why route labels carry the pattern rather than the URL (a metrics
consumer labelling on raw paths takes down the backend, not the app).

Three questions left open for review rather than answered alone, the sharpest
being where a request span ends on a streaming route — the same boundary #21
hit, which should be answered once for both.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:27:36 -05:00
chrnx f97ac8098b docs(plans): record the #15 decision and split out shutdown extensibility
The plan asked Task 2.3 to decide between two answers; the decision and what
the runtimes actually allow now sit in it, so the next reader is not re-deriving
either. The Deno constraint in particular was found by measurement and is not
in any issue.

Adds Task 2.5 for the plugin/provider teardown idea, kept out of the #15 work
on purpose: it needs a new await-aware surface on PluginApi, because the
existing Bus is a synchronous observer by design and cannot be made to hold up
a shutdown without losing the guarantee that makes it safe.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:18:06 -05:00
chrnx e4a2047a1e docs: describe the shutdown deadline, and who owns it per runtime
Closes #18. The three places that still described close() without a timeout —
the createapp reference table, the README bullet and the dependency-injection
inline comment — now say that in-flight work gets 10 seconds, then a warning
and a force-close.

Also documents what #18 deliberately deferred, now that #15 has decided it.
runtimes.md gains the per-runtime story: app.close() is Node-only, the servers
serveDeno()/serveBun() return carry the same close({ timeoutMs }), and edge has
nothing to close. Including the row that matters — Node and Bun cut the
remainder after the deadline, Deno returns and lets the process end it — since
a deadline that means two things is worse than one that admits it.

createApp({ shutdownTimeoutMs }) from #19 gets its row in the options table.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:17:19 -05:00
chrnx 586e14da72 feat(runtimes): a bounded close() on the Deno and Bun adapters
Closes #15, taking the second of the two answers it framed: app.close() stays
Node-only, and each transport that owns a handle offers the same close({
timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun
because they serve through app.fetch and never through listen(), and only the
transport can drain what it accepted. The warning there now names the
replacement instead of pointing at this issue.

The runtimes do not agree, and the code says so rather than averaging them:

Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves
between them like Node's closeAllConnections().

Deno cannot. Its two levers are mutually exclusive — aborting the serve signal
while shutdown() is pending throws BadResource from Deno's own listener,
uncaught and fatal under deno test. Measured on 2.9: abort alone is clean,
abort after shutdown is not. So on Deno the deadline bounds how long close()
waits, not when connections die, and both the type and the timeout warning say
that outright. Silently accepting an option that does less is the failure mode
AGENTS.md rules out.

closeWithDeadline is shared so the two cannot drift into different meanings of
the same timeoutMs, and it resolves on its own timer rather than awaiting the
force call — Bun's stop(true) was measured waiting out a handler with a pending
timer, which is exactly the unbounded wait the deadline exists to prevent.

serveDeno now owns the AbortController it serves with, chaining any caller
signal into it so neither party loses control; a test covers that. The Bun
ambient said stop() returns void, which was simply wrong.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:16:24 -05:00
chrnx 085eb9a67d fix(app): arm the shutdown timer before finish(), and make the deadline an app option
Closes #20. finish() called clearTimeout(timer) from above the timer's own
declaration. It worked because server.close(cb) always defers, so the
assignment won the race — correct by timing, and a ReferenceError waiting in
the shutdown path for whoever added a synchronous call site.

The issue proposed hoisting a `let timer`, but prefer-const rejects that and
is right to. Swapping the two blocks fixes it without a suppression and lands
somewhere better: the surviving forward reference is the timer callback
reaching finish(), and setTimeout not firing synchronously is the event loop
rather than a library's current behaviour.

Closes #19. The 10s deadline is now settable via createApp({ shutdownTimeoutMs }),
with the per-call close({ timeoutMs }) still winning. close() is usually
reached from a signal handler, a test helper or a shutdown hook you do not
own, where passing it per call is not available. Nothing changes for anyone
passing neither. The precedence test uses a 30s app-level default, so it can
only pass if the per-call value took priority.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:03:09 -05:00
chrnx 91f349bef7 ci: publish to JSR from the same tag that publishes to npm
The @green-tea scope is claimed and the package is linked to this repository
on jsr.io, so the OIDC id-token the job already holds for npm Trusted
Publishing authenticates JSR too — no new secret.

Ordered around one asymmetry: npm allows an unpublish within 72 hours, JSR
versions are immutable and can never be replaced. So JSR goes last, where a
failure costs a re-run rather than a version number, and a dry run gates both
before either ships — JSR checks slow types and module structure that npm
never looks at, and finding that out mid-release leaves the tag half-shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:59:45 -05:00
chrnx f96c2ad401 test: pin the JSR manifest to package.json
npm and JSR publish from the same tag but read their identity from different
files. Bump package.json alone and that tag ships one version to npm and the
previous one to JSR, with nothing failing — the drift the deno.json manifest
introduced, closed where the other publication-metadata pins already live.

Also pins the entry points to npm's, so a docs example importing
@green-tea/core/bun keeps working whichever registry the reader installed from.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:47:47 -05:00
chrnx a0fd74da34 ci: run the Deno, Bun and workerd suites on every push
package.json has defined test:deno, test:bun and test:edge for a while and CI
ran none of them, so 'runs everywhere' rested on whoever remembered to run
them locally. AGENTS.md even warned that npm test does not cover the other
runtimes without anything closing that gap.

Its own job rather than more steps on build, so a Bun failure reads as a Bun
failure instead of burying the Node lint output — the same reasoning that
places the audit where it is. fail-fast is off because which *other* runtime
broke is the useful half of the answer.

README and AGENTS.md now say the suites gate a merge, since the claim they
back is the headline one.

Refs: .specs/reports/green-tea-next-beta-trust-release.md section 7
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:46:51 -05:00
chrnx 1c5a908fb9 chore(types): name the decorator shapes so JSR sees no slow types
deno publish --dry-run reported 17 slow types across metadata.ts and
params.ts: two factories with inferred return types, and the fifteen exported
decorators built from them. Naming RouteDecorator and ArgDecorator fixes all
seventeen, since annotating each factory resolves its constants with it.

Fixed rather than waived with --allow-slow-types. That flag degrades the
generated declarations and makes type checking 1.5-2x slower for consumers,
which is a strange thing to ship in the framework whose central claim is type
safety. The two names are public API and worth having on their own: a caller
can now give a decorator of either shape a name.

The factories also lost their inline parameter types, which the declared
return type now supplies.

deno.json gains the JSR manifest. Exports mirror npm's four entry points on
purpose — a docs example importing @green-tea/core/bun has to work whichever
registry the reader installed from. Dry run is clean with no flags; claiming
the @green-tea scope on jsr.io is the remaining step.

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:45:47 -05:00
chrnx 30f33b6383 fix(http): narrow buffered bodies to what the runtime's Response accepts
A Node Buffer is a Uint8Array at runtime, but its declared backing store is
ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only
ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This
is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went
unnoticed because every implementation is forgiving about it at runtime.

Re-views rather than copies: this is the buffered-response path, and a copy
per response would cost real throughput on the runtimes that have no other
adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands
back a window into a shared 8 KB pool, and dropping them returns the whole
pool. A direct test covers that; the static-serving one covers the integration.

The type is derived from Response's own constructor because BodyInit is not a
global under lib es2020 plus @types/node, though Response itself is.

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:45:37 -05:00
chrnx 70bb9902dc ci: scope the publish audit gate to what actually ships
AGENTS.md states the rule and ci.yml implements it: npm audit --omit=dev
blocks, everything else reports. stage.yml and release.yml ran a bare
npm audit, so a dev-only advisory could hold a publish.

That drift stopped work twice. The nanoid advisory reached the tree through
tsup -> postcss -> nanoid, a build-tooling path that ships to nobody, and
fixing it was a precondition for a release it could not affect.

The full audit still runs with continue-on-error, so nothing goes unseen.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:38:20 -05:00
chrnx 9c3bc9574b docs(plans): plan the trust release from the four evaluation reports
The reports in .specs/reports/ were written independently and converge on
observability as the gap that matters most. Two things they demand had no
issue filed at all: CI never runs the Deno/Bun/edge suites that package.json
defines, so the multi-runtime claim has no evidence behind it, and explain()
returns each node's needs without ever naming what produced them.

Sequenced so the cheap phases land first and produce the material the
observability design needs. API freeze stays out: README already declares it
under 'next', and freezing a surface that is still missing its observability
contract would freeze the wrong thing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:38:12 -05:00
chrnx 08310ac252 Merge pull request 'release: promote the app.close() timeout and the nanoid bump to main' (#40) from develop into main
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / build (push) Successful in 35s
2026-08-12 19:11:55 +00:00
chrnx 31cafcc3fa Merge pull request 'chore(deps): bump nanoid to 3.3.18' (#39) from chore/nanoid-advisory into develop
CI / dco (push) Has been skipped
CI / dco (pull_request) Successful in 4s
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 33s
2026-08-12 19:10:36 +00:00
chrnx 4aae9c3e71 chore(deps): bump nanoid to 3.3.18 in both lockfiles
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 33s
Clears Dependabot alert 26. The advisory is real but our exposure is not:
nanoid arrives through postcss, under tsup at the root and under astro in
website/, so it never ships. Production dependencies of the package are
reflect-metadata and nothing else, and `npm audit --omit=dev` was already
green. Reaching the bug needs control of the size argument passed to nanoid,
which postcss calls with a fixed length.

Fixing it anyway because the alert costs more to keep explaining than to
close, and an open badge trains us to skim Dependabot. The next advisory
should be the only one sitting there.

Dependabot files it under website/ as runtime scope because website/package.json
lists astro under dependencies and has no devDependencies at all. Moving them
would stop that mislabelling, but that is a separate change.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-12 14:09:22 -05:00
chrnx 2e4712788b Merge pull request 'Merge contrib: app.close() timeout from an outside contributor' (#38) from contrib into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 34s
2026-08-12 19:03:23 +00:00
chrnx 9d95260706 chore(test): nest the close({ timeoutMs }) case inside its describe block
CI / dco (push) Has been skipped
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 34s
CI / build (push) Successful in 35s
The test landed one line below the closing brace of describe('graceful
shutdown'), so it ran at the top level instead of under the block it
belongs to. Placement only; the assertions are untouched.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-12 13:34:07 -05:00
ServeurGoat 3dcf784159 fix: add timeout to app.close()
Signed-off-by: YxnnXriel <yannariel13@gmail.com>
2026-08-12 13:33:10 -05:00
chrnx 7518a5a785 Merge pull request 'release: promote the contributor-facing docs and CI gates to main' (#37) from develop into main
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 34s
CI / dco (push) Has been skipped
2026-08-11 14:48:32 +00:00
chrnx da6099b0e6 Merge pull request 'docs: close the gaps an outside contributor falls into' (#36) from chore/contributor-friction into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 34s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 34s
2026-08-11 14:41:02 +00:00
chrnx f200045fd7 chore: put a project address in the package metadata
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 35s
author had no email and bugs had no address, so the only contact npm could show for a
published package was a GitHub issues URL. bugs.email is a field npm actually reads and
npm bugs surfaces, which makes it the right home for the catch-all.

No security address here on purpose: npm has no field for one, an invented key is read by
nothing, and the standard location is /.well-known/security.txt on the domain root, which
this repo does not serve.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:32:32 -05:00
chrnx 18d441b3ec docs: set real response times and a disclosure window
3/10 days was a placeholder borrowed from policies written for teams with someone on
rotation. This project is one person, so 5/15 with an escalation address, and an explicit
release from embargo if that also goes unanswered. A reporter facing silence should not
have to guess whether they are allowed to publish.

Adds the 90-day window, which was the real omission: the reporter's question is when they
may disclose, and leaving it unstated invites them to assume CERT/CC's 45.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:07:53 -05:00
chrnx 3714f7befc ci: reject commits without a Signed-off-by
CONTRIBUTING said unsigned commits are rejected and nothing enforced it, so the DCO was
caught by hand at review time. That is a full round-trip for a trailer, on top of however
long the fork's first run waits for approval.

Own job, so it reports separately from the code gates and costs nothing on push. Presence
only: whether a trailer that doesn't match the author is acceptable is a reviewer's call,
whether one exists at all is not.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:03:03 -05:00
chrnx ab58c064d5 docs: document local setup and the runtime suites
CONTRIBUTING went from clone straight to 'make the change' and never said npm install.
That mattered more than it looks: prepare wires core.hooksPath to .githooks, and the
pre-commit hook runs lint and complexity:check. An external contributor without it gets
told by CI what the hook would have told them before the commit existed.

The runtime commands were only in AGENTS.md and the README, so an assistant reading the
repo was better briefed than the person sending the pull request.

Checklist and the CI list now match ci.yml, which had grown complexity:check and build
without either following.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:02:56 -05:00
chrnx 6fa40672c6 docs: add a code of conduct and a security policy
Both were absent. The code of conduct is Contributor Covenant 2.1 verbatim, with
enforcement pointed at compliance@, which sits outside the project team so a report
about a maintainer has somewhere to go that isn't that maintainer.

The security policy exists so an exploitable finding has a route that isn't a public
issue. States the scope, the response times we can actually hold to, and that there is
no bounty, rather than leaving someone to find that out after the work.

Issue chooser now surfaces both, plus support@ for questions that are about the
reporter's own app rather than a bug here.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:02:49 -05:00
chrnx 1bb82491bd docs: document the cognitive complexity gate
complexity:check was missing from the list of commands CI runs, so the first
external contributor to trip it hit a failure with no way to have seen it
coming, on a rule the docs never stated.

Says what the number measures and why nesting is what it punishes, so the fix
reads as extracting a helper rather than raising the threshold.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 08:47:57 -05:00
chrnx b08ecb66cc chore: ignore bun.lock
Bun writes it on install but nothing reads it: test:bun runs against the
node_modules npm installed, already pinned by package-lock.json. deno.lock
stays tracked because the Deno tests resolve npm:/jsr: specifiers against
registries, where a lockfile is the only thing making them reproducible.

It reached a pull request once already, at 1278 lines.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 08:47:50 -05:00
chrnx 9bff2a52c9 Merge pull request 'docs: contributions merge into develop, they no longer need rebasing' (#29) from docs/agents-merge-not-rebase into develop
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 34s
Promote → GitHub / push-github (push) Successful in 7s
2026-08-10 13:51:09 +00:00
chrnx 551e79a86c docs: contributions merge into develop, they no longer need rebasing
CI / build (pull_request) Successful in 35s
The rebase existed to keep `main`'s history out of `develop` back when the two
had drifted ten commits apart. Fast-forward-only promotions closed that gap
hours after this file was written, and with `develop` and `main` on the same
commit a merge drags nothing in — so rebasing now only rewrites a
contributor's SHAs and drops `contrib` out of `main`'s ancestry, which is what
forces the force-push at reset time.

Proven on the first contribution through the route: the author's commits are
in `develop` under their original hashes, `main` is still an ancestor, and the
reset ahead is a plain fast-forward.

Hotfixes remain the exception, since they reach `main` without passing through
`develop`, so the rebase guidance stays for that case.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-10 08:50:43 -05:00
chrnx 61bef36d60 Merge pull request 'feat: concurrent connection limits, from the first external contribution' (#28) from contrib into develop
CI / build (push) Successful in 34s
2026-08-10 13:41:08 +00:00
chrnx 024b0a79fd Merge pull request #16 from hgshreyas/feature/max-connections
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 34s
feat: add concurrent connection limits
2026-08-10 08:32:04 -05:00
hgshreyas 8c781c1258 fix: treat non-positive connection limits as unlimited
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-10 16:14:07 +05:30
chrnx 84a2a29ed6 Merge pull request 'docs: make the base-branch reminder visible in the PR template' (#26) from docs/pr-template-base-branch into develop
Promote → GitHub / push-github (push) Successful in 5s
CI / build (pull_request) Successful in 34s
CI / build (push) Successful in 33s
2026-08-09 16:52:18 +00:00
chrnx 9d8e970c85 docs: make the base-branch reminder visible in the PR template
CI / build (pull_request) Successful in 34s
It sat inside an HTML comment, so it vanished the moment the description
rendered. The second external pull request filled in the checklist and still
targeted `main` — the template was read, the one line that mattered was not.

Now it is a visible blockquote the author is asked to delete, and a checklist
item, so choosing the base is an explicit tick rather than something to skim
past on the way to the boxes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-09 11:51:56 -05:00
hgshreyas 9e5e5cffe9 feat: add concurrent connection limits
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-09 17:27:47 +05:30
chrnx beec350fcd Merge pull request 'docs: add AGENTS.md and an AI assistance policy' (#24) from docs/agent-guidance into develop
Promote → GitHub / push-github (push) Successful in 5s
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 34s
Reviewed-on: #24
2026-08-09 05:45:30 +00:00
chrnx 37693246d7 docs: write down the release procedure and where AI assistance stands
CI / build (pull_request) Successful in 34s
Nothing recorded how this repository is actually run, so every rule lived in
one head and had to be rediscovered. AGENTS.md now carries the two-forge
topology, why promotions are fast-forward-only, how to tell a genuinely ahead
branch from pre-rebase duplication, and the runtime and dependency constraints
that reviews keep enforcing by hand. CLAUDE.md points at it rather than
repeating it, so the two cannot drift.

The AI section in CONTRIBUTING is neither a prohibition nor a disclosure rule.
Assistants are welcome and there is nothing to declare. What it asks is that
you read the diff before sending it, because a person reads every line that
lands here and a diff its own author skipped turns their review into
proofreading. The four failure modes listed are the ones this codebase
actually sees — added dependencies, Node-only assumptions, deleted reasoning,
missing tests — and three of the four were live in a real pull request the day
this was written.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-09 00:32:48 -05:00
chrnx 1b8f2f3140 Merge pull request 'docs: document the two-forge flow, add PR and issue templates' (#21) from docs/contribution-flow into develop
CI / build (push) Successful in 33s
CI / build (pull_request) Successful in 34s
Promote → GitHub / push-github (push) Successful in 7s
Reviewed-on: #21
2026-08-08 22:42:10 +00:00
chrnx e820954ea8 Merge branch 'develop' into docs/contribution-flow
CI / build (pull_request) Successful in 34s
2026-08-08 22:41:54 +00:00
chrnx 324ddf0d61 Merge pull request 'ci: gate on what we ship, and run the audit after the code checks' (#20) from chore/ci-audit-gate into develop
CI / build (push) Successful in 34s
Reviewed-on: #20
2026-08-08 22:41:34 +00:00
chrnx f2db461187 docs: tell contributors where their changes go, and add the templates
CI / build (pull_request) Failing after 11s
CONTRIBUTING described GitFlow as though there were one forge. There are two,
and nothing said so: an outside contributor reading it had no way to learn
that GitHub is a mirror of `main` and that pull requests belong on `contrib`.
The first external PR duly went to `main`, which was our omission rather than
theirs.

The templates carry the parts that keep being repeated by hand — sign-off,
the local check commands, and the two failures that a graph framework invites:
an implementation growing an option that its public interface never declares,
and behavior that works on Node while silently doing nothing on Deno and Bun.

Blank issues stay enabled. Scope and placement discussions are most of what
gets filed here and they don't fit a bug form.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:47 -05:00
chrnx 55263f2d97 ci: scope the audit gate to shipped dependencies, and run it last
CI / build (pull_request) Successful in 43s
`npm audit` sat fifth of fifteen steps, so any advisory anywhere in the tree
skipped lint, typecheck, tests and build. A high in a vitest transitive was
enough to hide whether the code itself was correct — and for external
contributors, whose runs need approval before they see anything at all, that
turned a red X into no information.

Severity is the wrong axis: a critical in the test runner reaches nobody,
while a high in `reflect-metadata` reaches everyone. Scope is the right one.
Production dependencies block; build tooling reports and moves on.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:46 -05:00
chrnx 506dedb624 ci: run checks on the contrib branch
External contributions land on `contrib`, and a PR targeting a branch absent
from the trigger list gets no checks at all — leaving contributors without the
feedback that would have caught the failure themselves.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:45 -05:00
chrnx 1030109efa Merge pull request 'release: promote docs and audit fixes to main' (#18) from develop into main
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Failing after 11s
CI / build (pull_request) Failing after 15s
Reviewed-on: #18
2026-08-07 21:58:41 +00:00
chrnx 08d92f5de7 Merge pull request 'docs: problem-first README, declared observability gap, docs analytics' (#16) from docs/observability-scope-and-analytics into develop
CI / build (push) Successful in 33s
CI / build (pull_request) Successful in 33s
Reviewed-on: #16
2026-08-07 19:27:49 +00:00
chrnx 8babcb9554 Merge pull request 'fix(release): unblock npm provenance publication' (#15) from hotfix/npm-release-provenance into main
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 35s
Reviewed-on: #15
2026-08-03 03:48:19 +00:00
chrnx 6dd23ed874 chore(release): reconcile main before npm fix
CI / build (pull_request) Successful in 33s
Merge the current public main history while preserving develop's mutable Verdaccio staging policy for the npm provenance hotfix.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:45:51 -05:00
chrnx 05e59383f1 Merge pull request 'release: promote 26.8.0-beta.0 to main' (#13) from release/26.8.0 into main
CI / build (push) Successful in 35s
Promote → GitHub / push-github (push) Successful in 6s
Reviewed-on: #13
2026-08-03 02:57:35 +00:00
chrnx 97a146a758 Merge branch 'main' into release/26.8.0
Stage → Verdaccio / publish-stg (push) Failing after 21s
CI / build (pull_request) Successful in 33s
2026-08-03 02:57:15 +00:00
chrnx aa3402bd84 ci(release): stage prereleases from release branches
Stage → Verdaccio / publish-stg (push) Successful in 21s
CI / build (pull_request) Successful in 36s
Keep develop free to accept concurrent changes while Verdaccio validates an immutable release candidate. Audit dependencies and reject stable versions before publishing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:43:16 -05:00
chrnx 813a29001b Merge pull request 'release: merge docs refresh to main' (#11) from develop into main
Stage → Verdaccio / publish-stg (push) Successful in 22s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 23s
2026-07-18 21:09:01 +00:00
chrnx 8d923e053c Merge pull request 'release: OIDC publishing + beta dist-tag → main' (#9) from develop into main
Stage → Verdaccio / publish-stg (push) Successful in 22s
CI / build (push) Successful in 24s
Promote → GitHub / push-github (push) Successful in 7s
2026-07-18 20:18:07 +00:00
chrnx 523e302012 Merge pull request 'release: promote stage fix to main' (#7) from develop into main
CI / build (push) Successful in 24s
Stage → Verdaccio / publish-stg (push) Successful in 27s
Promote → GitHub / push-github (push) Successful in 7s
2026-07-18 19:09:16 +00:00
chrnx e068426582 Merge pull request 'release: promote develop → main (staging)' (#5) from develop into main
Stage → Verdaccio / publish-stg (push) Failing after 26s
CI / build (push) Successful in 24s
Promote → GitHub / push-github (push) Successful in 6s
2026-07-18 19:01:48 +00:00
320 changed files with 210091 additions and 11735 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
---
name: Bug report
about: Something behaves differently from what the docs or the types promise
labels: bug
---
## What happened
## What you expected
## Minimal reproduction
The smallest module and route that shows it:
```ts
```
## Environment
- green-tea version:
- Runtime and version: <!-- e.g. Node 22.20 / Deno 2.5 / Bun 1.3 / Cloudflare Workers -->
- OS:
<!--
If it works on one runtime and not another, say which. That difference is
usually the bug rather than a detail of it.
-->
+14
View File
@@ -0,0 +1,14 @@
# Design questions, scope decisions and "should this live in core?" threads don't fit a
# bug form, and they are most of what gets filed here. Keep the blank option available.
blank_issues_enabled: true
contact_links:
- name: Security vulnerability
url: https://github.com/Expressive-Tea/green-tea/security/advisories/new
about: Report it privately instead. Never in a public issue — see SECURITY.md.
- name: Documentation
url: https://green-tea.expressive-tea.io/docs/
about: How to wire a route, a module, a plugin or a runtime adapter.
- name: Help with your own app
url: mailto:support@expressive-tea.io
about: Implementation questions about your code rather than a bug in green-tea.
+17
View File
@@ -0,0 +1,17 @@
> **Base branch:** on GitHub this must target `contrib`, not `main`. You can still change it above, before you submit — and [here is why](https://github.com/Expressive-Tea/green-tea/blob/main/CONTRIBUTING.md#where-to-send-your-changes). Delete this line once the base is right.
## What this changes
<!-- A sentence or two, on the why rather than the what. -->
Closes #
## Checklist
- [ ] The base branch above is `contrib`
- [ ] Commits are signed off (`git commit -s`)
- [ ] `npm run lint`, `npm run format:check`, `npm run typecheck`, `npm test`, `npm run complexity:check` and `npm run build` pass locally
- [ ] The runtime suites this change touches pass locally (`npm run test:deno`, `test:bun`, `test:edge`, or `test:all`), and they are named here
- [ ] New behavior has a test
- [ ] A new public option or method is also declared in `src/app/types.ts`, and noted in `README.md`
- [ ] Behavior is the same on Node, Deno and Bun — or the difference is deliberate, and said out loud here
+88 -11
View File
@@ -1,28 +1,105 @@
name: CI name: CI
on: on:
push: push:
branches: [develop, main] branches: [develop, main, contrib]
pull_request: pull_request:
branches: [develop, main] branches: [develop, main, contrib]
jobs: jobs:
# Separate job so a missing sign-off reports on its own and doesn't hide behind the code
# gates, and so it costs nothing on push. Checks that the trailer is present, not that it
# matches the author — a mismatch is a judgement call for a reviewer, an absent trailer
# is not, and telling a contributor on their first push beats telling them on review.
dco:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Every commit needs a Signed-off-by
env:
RANGE: ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}
run: |
missing=0
for sha in $(git rev-list --no-merges "$RANGE"); do
if ! git show -s --format='%(trailers:key=Signed-off-by,valueonly)' "$sha" | grep -q '[^[:space:]]'; then
echo "::error::no Signed-off-by: $(git show -s --format='%h %s' "$sha")"
missing=1
fi
done
if [ "$missing" = 1 ]; then
echo "We use the DCO instead of a CLA. See CONTRIBUTING.md."
echo "Fix the whole branch with: git rebase --signoff ${{ github.event.pull_request.base.sha }}"
echo "Then: git push --force-with-lease"
exit 1
fi
echo "All commits signed off."
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
- uses: actions/setup-node@v4 - uses: actions/setup-node@v5
with: with:
node-version: '18' node-version: '22'
- run: npm ci - run: npm ci
- run: npm audit
- run: npm run lint - run: npm run lint
- run: npm run format:check - run: npm run format:check
- run: npm run complexity:check - run: npm run complexity:check
- run: npm run typecheck - run: npm run typecheck
- run: npm test - run: npm test
- run: npm run build - run: npm run build
- uses: actions/setup-node@v4 # Supply chain, deliberately after the code gates: an advisory published by a third party
# must never decide whether a contributor gets to see their own lint and typecheck output.
# Only what we ship blocks — with `reflect-metadata` as the sole runtime dependency, a
# production advisory is rare and genuinely reaches users. Build tooling only reports.
- run: npm audit --omit=dev
- run: npm audit
continue-on-error: true
# Runs everywhere is the headline claim, so it gets tested rather than asserted. `npm test` is
# Node only: a change to shared code can pass it and still be broken on Deno or Bun, which is
# exactly why these suites exist separately. Leaving them out of CI meant the claim rested on
# whoever remembered to run them locally.
#
# Its own job, not more steps on `build`, for the reason the audit sits where it does: a Bun
# failure should read as a Bun failure instead of burying the Node lint output.
runtimes:
runs-on: ubuntu-latest
strategy:
# One runtime breaking must not cancel the others — which one else broke is the useful part
# of the answer, and a cancelled job reports as if it had never been asked.
fail-fast: false
matrix:
runtime: [deno, bun, edge]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with: with:
node-version: '22.12' node-version: '22'
- run: npm ci --prefix website # All three need the dependency tree: the edge suite drives workerd from a Node process, and
- run: npm audit --prefix website # Deno and Bun resolve `reflect-metadata` out of node_modules like any other import.
- run: npm run docs:build - run: npm ci
- if: matrix.runtime == 'deno'
uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@v2
- run: npm run test:${{ matrix.runtime }}
# JSR's gate, moved off the release tag. `release.yml` runs this too and keeps doing so —
# that copy protects an immutable JSR version and is the last thing standing between a tag
# and a version number that can never be replaced. This copy exists because that one runs
# too late to be useful as feedback: a slow type or a Deno type error would otherwise land
# on `main` in silence and surface while cutting a release, which is the same "least time
# to judge a fix" the audit steps above are ordered to avoid.
#
# It is a second compiler over the same source, not a formality. `npm run typecheck` is tsc
# with this repo's tsconfig; this is Deno's checker with Deno's lib, and it is what found
# the `BodyInit` hole on the fetch path that tsc accepted. JSR serves `src/` directly, so
# anything it rejects is something a JSR consumer would have received.
#
# 0.68s against 2.0s for the whole vitest suite. No `--allow-dirty`: a checkout is clean,
# and if it somehow is not, that is worth failing on.
- if: matrix.runtime == 'deno'
run: deno publish --dry-run
+34 -14
View File
@@ -1,30 +1,50 @@
name: Promote → GitHub name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub # Promotion. Runs on GITEA ONLY. Mirrors two branches to the public GitHub repo and nothing else:
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's #
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers # main → GitHub main the production mirror
# its release workflow (production publish). # develop → GitHub contrib what outside contributors fork from and target
#
# Feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
# would expose every branch).
#
# Neither push is forced. For `contrib` that is the guard, not a limitation: the push is refused
# exactly when `contrib` holds external merges that have not been carried into `develop` yet
# (AGENTS.md, "External contributions"). Carry them and the next develop push fast-forwards.
#
# Tags are deliberately NOT mirrored. The same `v*` tag means two different things on the two
# forges: on Gitea it stages to Verdaccio (`stage.yml`), on GitHub it publishes to npm and
# JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
# decision a person takes after reading the staging run, not a side effect of creating it:
#
# git push gh v<version>
#
# `--tags` is left off the branch push for the same reason. It used to ride along here, which
# meant any tag sitting in the runner's clone could reach production as a side effect of
# promoting `main` — a publish nobody chose, of a commit nobody was looking at.
on: on:
push: push:
branches: [main] branches: [main, develop]
tags: ['v*']
jobs: jobs:
push-github: push-github:
if: ${{ github.server_url != 'https://github.com' }} if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
with: with:
fetch-depth: 0 # full history + tags for a clean push fetch-depth: 0 # full history for a clean push
- name: Push main + tags to GitHub - name: Push to GitHub
env: env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }} GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: | run: |
case "$GITHUB_REF_NAME" in
main) target=main ;;
develop) target=contrib ;;
*) echo "::error::promote runs for main and develop only, got '$GITHUB_REF_NAME'"; exit 1 ;;
esac
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git" git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
if [ "${{ github.ref_type }}" = "tag" ]; then if ! git push github "HEAD:refs/heads/${target}"; then
git push github "refs/tags/${{ github.ref_name }}" echo "::error::GitHub ${target} has commits that ${GITHUB_REF_NAME} does not. For contrib that means external merges not yet carried into develop — carry them (AGENTS.md, External contributions); never force this push."
else exit 1
git push github "HEAD:refs/heads/main"
git push github --tags
fi fi
+91 -7
View File
@@ -12,24 +12,108 @@ jobs:
publish-prod: publish-prod:
if: ${{ github.server_url == 'https://github.com' }} if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
PKG: '@green-tea/core'
permissions: permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance) id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read contents: write # create the GitHub release for this tag
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
- uses: actions/setup-node@v4 - uses: actions/setup-node@v5
with: with:
node-version: '22' node-version: '22'
registry-url: 'https://registry.npmjs.org' registry-url: 'https://registry.npmjs.org'
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing - run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
- run: npm ci - run: npm ci
# Same scoped gate as ci.yml: only what we ship blocks a publish. With `reflect-metadata`
# as the sole runtime dependency, a blocking advisory here is rare and genuinely reaches
# users; a build-tooling one never does. The full audit still reports.
- run: npm audit --omit=dev
- run: npm audit - run: npm audit
continue-on-error: true
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first. # `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token. # No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest` # A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
# never points at a beta; a stable version publishes under `latest`. # never points at a beta; a stable version publishes under `latest`.
- name: Publish - uses: denoland/setup-deno@v2
with:
deno-version: v2.x
# Gate both registries before either one ships. JSR checks things npm never looks at — slow
# types, module analysis — and learning about them after npm has published leaves the tag
# half-shipped. Seconds, against a failure mode with no clean recovery.
- run: deno publish --dry-run
# A publish sets exactly one dist-tag, and it is the only npm write this workflow can make:
# Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token
# it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag
# the publish gets has to be the one that matters most.
#
# While no stable release exists, `latest` and the channel tag mean the same thing — there is
# nothing else to install — and `latest` takes it, because that is what a bare
# `npm install @green-tea/core` resolves to. Leaving it behind on an older beta would hand the
# default install an older build than the one just released. The channel tag is then moved by
# hand; the step prints the command. Once a stable version exists it owns `latest` for good,
# a later beta must not drag it backwards, and the channel tag becomes the automatic one again.
- name: Publish to npmjs
run: | run: |
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')") VERSION=$(node -p "require('./package.json').version")
echo "dist-tag: $TAG" CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
npm publish --access public --tag "$TAG" # Read the list into a variable so a failed lookup fails the step, rather than passing for
# "no stable exists" and pointing `latest` at a prerelease that should not have it.
VERSIONS=$(npm view "$PKG" versions --json)
if [ "$CHANNEL" != latest ] \
&& ! node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
TAG=latest
else
TAG=$CHANNEL
fi
echo "$VERSION under dist-tag: $TAG"
# Skip rather than fail when the version is already up, so a re-run after a later failure
# can finish the remaining work instead of dying on a duplicate npm rejects anyway.
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
echo "npm already has $VERSION"
else
npm publish --access public --tag "$TAG"
fi
if [ "$TAG" != "$CHANNEL" ]; then
echo "::notice::Move the channel tag by hand: npm dist-tag add $PKG@$VERSION $CHANNEL"
fi
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
# failure *after* it would cost a version number permanently. Version and entry points come
# from deno.json, which `test/package-metadata.test.ts` pins to package.json — JSR has no
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
# id-token npm just used; the package is linked to this repository on jsr.io.
- name: Publish to JSR
run: |
VERSION=$(node -p "require('./package.json').version")
PKG=${PKG#@}
# 404 until the version exists, and also for a package with no versions at all — which is
# what this one was until v26.8.0-beta.1 — so the guard must not read a 404 as an error.
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
echo "JSR already has $VERSION"
else
deno publish
fi
# The release page is where people who do not read a changelog find out what changed, and a
# repository with tags and no releases reads as abandoned. Notes come from CHANGELOG.md rather
# than from the commit range: the section was written for humans and already exists by the time
# a tag is cut, and generated notes would restate merge subjects nobody chose.
#
# Idempotent like the publishes above, so a re-run after a later failure does not stop here.
# `--verify-tag` refuses to invent a tag: the release attaches to the one that triggered this
# run and can never move it. A prerelease is marked as such, which is what keeps GitHub's
# "Latest" badge off a beta.
- name: Create the GitHub release
env:
GH_TOKEN: ${{ github.token }}
run: |
VERSION=$(node -p "require('./package.json').version")
TAG=${GITHUB_REF_NAME}
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "release $TAG already exists"; exit 0
fi
node scripts/changelog-section.mjs "$VERSION" "$TAG" > /tmp/notes.md
case "$VERSION" in *-*) PRE=--prerelease ;; *) PRE= ;; esac
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" \
--notes-file /tmp/notes.md --verify-tag $PRE
+20 -4
View File
@@ -1,24 +1,35 @@
name: Stage → Verdaccio name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release # Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag. # internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag.
# Staging versions are intentionally mutable: an existing prerelease is removed before # Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version. # publishing the updated release candidate under the same version.
#
# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path —
# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we
# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm
# allows 72 hours to unpublish and JSR allows nothing at all.
on: on:
push: push:
branches: ['release/**'] branches: ['release/**']
tags: ['v*']
jobs: jobs:
publish-stg: publish-stg:
if: ${{ github.server_url != 'https://github.com' }} if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
- uses: actions/setup-node@v4 - uses: actions/setup-node@v5
with: with:
node-version: '22' node-version: '22'
- run: npm ci - run: npm ci
# Same scoped gate as ci.yml: only what we ship blocks a publish. A `tsup` advisory
# reaches nobody, and holding a release candidate for one is how staging stalls on work
# that has nothing to do with the package. The full audit still reports.
- run: npm audit --omit=dev
- run: npm audit - run: npm audit
continue-on-error: true
- name: Validate release candidate - name: Validate release candidate
run: npm run prepublishOnly run: npm run prepublishOnly
- name: Publish prerelease to Verdaccio - name: Publish prerelease to Verdaccio
@@ -27,6 +38,11 @@ jobs:
run: | run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version") VER=$(node -p "require('./package.json').version")
# Staging overwrites the version it publishes, and a stable number that changes
# under an internal consumer is worse than no staging at all. This will need
# revisiting at the first stable release, which is exactly the one most worth
# staging: the answer is probably to stage it under a suffixed version rather
# than to drop the guard.
case "$VER" in case "$VER" in
*-*) ;; *-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;; *) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
+17 -3
View File
@@ -1,6 +1,13 @@
# Local specs & plans — not committed # Local specs & plans — not committed
.specs/ .specs/
# Per-developer agent state: local settings and tool locks, one directory per assistant. Nothing
# here is shared configuration — `.serena/` even ships its own .gitignore. A repository-wide
# `.claude/settings.json` is a real convention and would need a `!` line here to be committable;
# none exists today, so this stays a blanket ignore rather than a rule for a file nobody wrote.
.claude/
.serena/
# Node # Node
node_modules/ node_modules/
dist/ dist/
@@ -11,9 +18,16 @@ coverage/
.env .env
.env.* .env.*
# Astro (docs site)
.astro/
website/dist/
# Edge (Miniflare) test bundle artifact # Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs test/edge/_worker.mjs
test/edge/_parity-worker.mjs
test/edge/_compression-worker.mjs
test/edge/_dist-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.
# deno.lock IS tracked, and that asymmetry is deliberate — the Deno tests import `npm:` and
# `jsr:` specifiers that Deno resolves against registries, so only a lockfile makes them
# reproducible. Bun resolves the same package.json npm does.
bun.lock
+156
View File
@@ -0,0 +1,156 @@
# AGENTS.md
Guidance for AI coding assistants working in this repository. Claude Code, Codex, Cursor and anything else that reads this file.
If you are an assistant: a person reads every line of what you produce before it lands, and the person submitting it signs off on it. Make that reading worth their time — leave the reasoning visible, don't quietly widen the scope you were asked for, and say what you were unsure about instead of smoothing over it. The "Working with AI assistance" section of `CONTRIBUTING.md` applies to your output.
## What this is
`@green-tea/core` — a type-safe HTTP framework where the API is a dependency graph rather than a middleware chain. You declare what each step needs and provides; the framework computes execution order, fails at boot if something is missing, and can print the whole pipeline. Runs on Node, Deno, Bun and the edge from one codebase.
**Hard constraint: one runtime dependency.** `reflect-metadata`, and nothing else. `busboy` and `ws` are peer dependencies. Anything that would add a third belongs in a plugin, not in core.
## Commands
```bash
npm run lint # eslint
npm run format:check # prettier, src/**/*.ts only
npm run typecheck # must be clean; includes the compile-time-guarantee type test
npm test # vitest
npm run build # tsup
npm run complexity:check
npm run test:deno # the other runtimes are NOT covered by `npm test`
npm run test:bun
npm run test:edge
```
Run the first four before proposing anything as finished. The runtime suites stay separate commands on purpose — a change to shared code that passes `npm test` may still be broken on Deno or Bun — but they are no longer optional: CI runs all three on every push and each one gates a merge. Run them yourself for anything touching `src/http/`, the adapters, or `src/mesh/`, rather than finding out from CI.
## Two forges
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and `develop` automatically — `develop` under the name `contrib` — and release tags only by hand.
```
feature/* → develop → main → [promote.yml] → GitHub main
│ │
└─[promote.yml]┼──→ GitHub contrib ← external PRs
↑ │ │
└── carried back by hand ─┘ (a PR into develop)
│
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
└─── GitHub (pushed by hand): [release.yml] → npm + JSR
```
- **Gitea `develop`** — active development.
- **Gitea `main`** — staging. Merging here publishes nothing. A `v*` tag here publishes to the internal Verdaccio, never to a public registry.
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
- **GitHub `contrib`** — mirror of `develop`, pushed by `promote.yml` on every develop merge, and where outside contributions land. GitHub only: there is no Gitea `contrib`.
`develop` and `main` on Gitea have direct push disabled with an empty whitelist, so nobody can push to them, admins included. Advance them by opening a PR and merging it.
## Procedure
**Promotions are fast-forward-only.** `develop → main` merges with Gitea's fast-forward-only style, so `main` becomes an exact copy of `develop` and no commit is ever born on `main`. This is not a preference: merge-style promotions created seven of the ten commits of drift that had to be cleaned up in August 2026, because each one lived on `main` and never travelled back. Release boundaries are marked by `v*` tags, not by promotion commits.
**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
git branch -d <branch> && git push origin --delete <branch>
```
On 2026-09-22 this repository carried 36 branches on Gitea and 29 locally, every one but a single stale docs branch already merged into `develop`, some of them since July. At that size the branch list stops describing the work in flight and becomes something a release has to audit commit by commit — which is both when it costs the most and when nobody has the patience for it. `git branch -r --merged origin/develop` is the check. A branch whose commits were rebased on the way in will not appear there even though its content did land, so confirm that case by content (`git diff <branch> develop -- <file>`) rather than by the flag. Never `develop`, `main`, or a `release/*` that has not shipped yet.
**Diagnosing "this branch is ahead of main".** Usually it is pre-rebase duplication, not unmerged work: the same content under different SHAs, because contributions are rebased on their way into `develop`. Confirm before acting:
```bash
git diff <branch> <main> -- <suspect file> # empty means the content is already in main
```
Merging such a branch to "recover" the commits duplicates the work and drags stale history along.
**External contributions.** They arrive on GitHub `contrib`. Merge the pull request there, fetch GitHub `contrib` into a branch on Gitea, then open a pull request from it into `develop` and merge it. The next develop push mirrors back to `contrib`, and fast-forwards because `develop` now contains everything `contrib` had. Merge rather than rebase: because promotions are fast-forward-only, `develop` and `main` are the same commit, so there is no main-only history for a merge to drag in. Rebasing would rewrite the contributor's SHAs for no gain and leave `contrib` with commits `develop` does not have, so the mirror push is refused until someone forces it. Merging keeps their commits reaching `main` under their own name and hash.
The exception is a `hotfix/*`, which lands on `main` without passing through `develop` and leaves the two out of step. Back-merge before taking a contribution through, or rebase that one and accept the force-push. If you do rebase, take the commit range from the pull request itself and never "everything since main": if a second contributor branched from `contrib` after the first one merged, the broad range sweeps up work that isn't theirs.
**Nothing to reset after a promotion.** `contrib` follows `develop` through the mirror, and there is no Gitea `contrib` to keep in step. The one thing the mirror will not do is push over external merges that were never carried in: that push is refused, the promote job fails, and the fix is to carry them as above — never to force.
A conflict against `develop` is visible to the contributor through `contrib`, so it can be theirs to resolve: ask them to rebase onto the current `contrib`. Only a conflict against a feature branch that has not merged yet is the maintainer's alone, because that code they cannot see.
## Releasing
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
nowhere is worse than no heading at all, because the next reader believes it.
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
two contradictory things — that beta.1 was released, and that everything in it was not.
So the order is: everything merged and promoted → **close the section with the release date** → tag →
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
number feels.
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
A version number is a plan; a changelog heading is a receipt.
**A tag is created twice, on purpose.** Pushing `v*` to Gitea stages that exact commit to
Verdaccio through the real publish path; pushing the same tag to GitHub publishes it to npm and
JSR. Nothing promotes the tag for you — `promote.yml` mirrors `main` and only `main`, so the
second push is a decision made after reading the first run:
```bash
git push origin v<version> # Gitea → Verdaccio, reversible
git push gh v<version> # GitHub → npm + JSR, permanent on JSR
```
The split exists because a mistake caught on Verdaccio costs a re-tag, and the same mistake
caught on JSR costs the version number forever.
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
on `v26.8.0-beta.1`). While there is no stable release the publish spends that one tag on `latest`,
since that is what a bare `npm install @green-tea/core` resolves to, and the workflow prints the
command for the rest:
```bash
npm dist-tag add @green-tea/core@<version> beta
```
Once a stable version exists this stops being a chore: `latest` belongs to the stable release, the
publish gives a beta its channel tag directly, and there is nothing left to move.
## CI
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
**The forges disagree about where workflows come from.** GitHub reads `pull_request` workflows from the base branch, so a workflow fix cannot validate itself and must reach the base before it gates anything. Gitea reads from the head. Likewise, `continue-on-error` steps report as `success` on GitHub, hiding the advisory in the log, but as `failure` with the job still green on Gitea.
GitHub does not run workflows on fork pull requests until a maintainer approves them. A contributor's first push may sit with no checks at all.
## Conventions
- Conventional Commits, focused on the *why*. Every commit signed off (`git commit -s`) — the project uses a DCO, and unsigned commits are rejected. No AI co-authoring attribution.
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
+214 -37
View File
@@ -4,14 +4,14 @@
## Environment ## Environment
- **Date**: 2026-07-07 - **Date**: 2026-09-22
- **Commit**: fe1831a - **Commit**: daf0fed
- **Node**: v22.22.2 - **Node**: v22.22.2
- **OS**: darwin - **OS**: linux
- **CPU**: Apple M4 Max (16 cores) - **CPU**: AMD Ryzen 7 3700X 8-Core Processor (16 cores)
- **RAM**: 69 GB - **RAM**: 67 GB
- **Core-pinned**: no - **Core-pinned**: no
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1 - **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over > **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
> loopback on the same machine, sharing the same cores as the server processes they measured. That > loopback on the same machine, sharing the same cores as the server processes they measured. That
@@ -29,64 +29,74 @@
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 | | raw-http | 41,631 | 2.00 | 3.00 | 4.00 | 0.6% | 41,343–41,974 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 | | nestjs-fastify | 32,419 | 3.00 | 4.00 | 6.00 | 0.5% | 32,103–32,583 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 | | fastify | 32,170 | 3.00 | 3.00 | 5.00 | 1.3% | 31,236–32,356 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 | | green-tea | 29,777 | 3.00 | 6.00 | 7.00 | 0.4% | 29,557–29,873 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 | | express | 10,546 | 8.00 | 13.00 | 18.00 | 0.4% | 10,480–10,625 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 | | nestjs-express | 9,680 | 9.00 | 15.00 | 21.00 | 0.6% | 9,567–9,739 |
### Route param ### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 | | raw-http | 41,756 | 2.00 | 3.00 | 4.00 | 1.1% | 40,953–42,017 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 | | fastify | 31,708 | 3.00 | 4.00 | 5.00 | 0.5% | 31,359–31,847 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 | | nestjs-fastify | 29,880 | 3.00 | 4.00 | 6.00 | 0.3% | 29,745–29,961 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 | | green-tea | 28,706 | 3.00 | 6.00 | 7.00 | 0.6% | 28,562–29,051 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 | | express | 10,376 | 9.00 | 12.00 | 17.00 | 0.4% | 10,364–10,453 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 | | nestjs-express | 9,257 | 10.00 | 15.00 | 21.00 | 0.2% | 9,244–9,285 |
### Pipeline (3 steps) (approximation) ### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 | | raw-http | 39,897 | 2.00 | 3.00 | 5.00 | 0.6% | 39,847–40,441 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 | | fastify | 31,436 | 3.00 | 4.00 | 6.00 | 0.6% | 31,079–31,563 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 | | nestjs-fastify | 29,403 | 3.00 | 4.00 | 6.00 | 0.6% | 29,151–29,689 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 | | green-tea | 26,839 | 3.00 | 6.00 | 8.00 | 0.1% | 26,783–26,872 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 | | express | 10,365 | 9.00 | 12.00 | 18.00 | 1.3% | 10,171–10,542 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 | | nestjs-express | 9,256 | 10.00 | 15.00 | 22.00 | 0.5% | 9,187–9,302 |
### POST JSON + validation ### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- |
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 | | raw-http | 31,783 | 3.00 | 5.00 | 6.00 | 0.4% | 31,517–31,825 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 | | green-tea | 22,005 | 4.00 | 7.00 | 9.00 | 0.7% | 21,736–22,187 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 | | fastify | 20,430 | 4.00 | 8.00 | 9.00 | 0.4% | 20,398–20,601 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 | | nestjs-fastify | 18,597 | 4.00 | 8.00 | 11.00 | 0.2% | 18,540–18,658 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 | | express | 8,440 | 11.00 | 16.00 | 24.00 | 0.3% | 8,408–8,492 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 | | nestjs-express | 7,666 | 12.00 | 18.00 | 26.00 | 0.3% | 7,645–7,703 |
## Step-scaling (green-tea) ## Step-scaling (green-tea)
| Path | Steps | req/s | | Path | Steps | req/s |
| --- | --- | --- | | --- | --- | --- |
| /steps/0 | 0 | 92,282 | | /steps/0 | 0 | 29,196 |
| /steps/3 | 3 | 81,530 | | /steps/3 | 3 | 26,564 |
| /steps/5 | 5 | 71,994 | | /steps/5 | 5 | 25,314 |
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box. Each additional pipeline step costs roughly 776 req/s (-13.3% over 5 steps), on this box.
## green-tea across runtimes
| Scenario | node | deno | bun |
| --- | --- | --- | --- |
| JSON hello (overhead) | 30,379 | 51,888 | 46,300 |
| Route param | 29,204 | 51,786 | 42,788 |
| Pipeline (3 steps) | 27,208 | 50,692 | 39,644 |
| POST JSON + validation | 22,609 | 35,743 | 31,960 |
Same application, same built bundle, same box — only the runtime differs. Read across a row, never against the cross-framework tables above: those measure other frameworks on Node, and nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.
## Cost of secure-by-default (green-tea) ## Cost of secure-by-default (green-tea)
| Label | req/s | | Label | req/s |
| --- | --- | | --- | --- |
| security:false (parity) | 98,093 | | security:false (parity) | 29,777 |
| security:true (default) | 92,998 | | security:true (default) | 28,919 |
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box. The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~2.9% req/s on this box.
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs > Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately > `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
@@ -116,3 +126,170 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters. on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
<!-- keep-below: hand-written, survives `npm run bench` -->
## What moved between releases
These figures were measured per function and never per version. Every change on the request path
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
`npm run bench:compare` exist to close.
### The release gate: `26.9.0-beta.1` → `26.9.0-beta.2`
Ten cases, both trees on one box in one sitting, alternating which side ran first each round, sharing
one `node_modules` — the two revisions differ by a version string and nothing else in `package.json`,
so the only thing that moved between the sides is green-tea. Medians of three rounds:
| Scenario | 26.9.0-beta.1 | 26.9.0-beta.2 | Δ | |
| --- | --- | --- | --- | --- |
| hello | 90,615 | 89,853 | −0.8% | overlaps |
| param | 86,956 | 87,572 | +0.7% | overlaps |
| pipeline (3 steps) | 80,061 | 81,504 | +1.8% | overlaps |
| steps5 | 75,436 | 75,238 | −0.3% | overlaps |
| validate (POST) | 70,240 | 73,568 | +4.7% | overlaps |
| hello + security | 83,738 | 84,890 | +1.4% | overlaps |
| hello + cors predicate | 82,237 | 82,528 | +0.4% | overlaps |
| preflight + cors predicate | 111,223 | 114,220 | +2.7% | overlaps |
| param, 50 routes | 83,505 | 87,078 | +4.3% | **flagged** |
| param, 200 routes | 73,289 | 73,335 | +0.1% | overlaps |
Nine rows overlap and therefore say nothing, which is the result this gate exists to produce. The
release is a breaking one — `Plugin` became `{ name, mount }`, `serveDeno()` and `serveBun()` became
async, `@Provider({ export: true })` stopped being a thing a teapot can do, and an `HttpError` is now
recognised by a brand rather than by `instanceof` — but all of that is boot-time or error-path work.
None of it sits on the per-request path these cases walk, and the table agrees.
The tenth row is why "flagged" is not a synonym for "found something". `param, 50 routes` came out
+4.3% with separated ranges, in green-tea's favour, and it did not survive being asked twice: re-run
alone at seven rounds it is **+0.5% and overlapping**, with both sides swinging between 80,794 and
88,259 req/s. The reason to doubt it before re-running was that it had no mechanism — the matcher
work that could produce it would have to show at 200 routes too, and that row had already said
+0.1%. Treat a flagged row as an instruction to measure again, whichever direction it points; a win
nobody can explain is a measurement problem more often than it is a win.
The cross-framework tables above moved to a quiet box for this release, which is why their absolute
numbers are roughly a third of the previous run's: an idle 2019 desktop Ryzen against a laptop M4
Max. Two attempts on that laptop were discarded first, and the reason is worth recording. Each
framework's delta against its own previous number tracked its position in the run order rather than
anything in its code — the one measured second lost 7%, the ones measured last gained — while a
browser and the window server held around 60% of the machine throughout. That run would have read
as green-tea overtaking Fastify, which is the most flattering available reading of a broken
measurement and exactly the kind this file exists to refuse. The gate table above survives the same
contention, because both sides pay it and the order alternates; an absolute cross-framework number
does not.
What survived the move is the shape, and that is the part worth trusting. On both machines green-tea
is behind Fastify on `hello`, `param` and `pipeline` and ahead of it on `validate`, and roughly
2.8× ahead of Express throughout. The *size* of the gap did not survive: against Fastify it is
2-8% on the M4 and 7-15% here. A percentage quoted without the hardware it was measured on is not a
fact about the framework.
### The release gate: `26.8.0-beta.1` → `26.9.0-beta.1`
Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
one `node_modules` and one byte-identical server file. Medians of five rounds:
| Scenario | 26.8.0-beta.1 | 26.9.0-beta.1 | Δ |
| --- | --- | --- | --- |
| hello | 91,343 | 90,371 | −1.1% |
| param | 88,113 | 87,921 | −0.2% |
| pipeline (3 steps) | 80,934 | 80,893 | −0.1% |
| validate (POST) | 72,340 | 72,241 | −0.1% |
| hello + security | 85,967 | 86,426 | +0.5% |
| hello + cors predicate | 82,609 | 83,401 | +1.0% |
| preflight + cors predicate | 112,055 | 115,069 | **+2.7%** |
Every row but the last overlaps between the two sides and is noise. The preflight row does not: the
new tree wins all three rounds, which is where a `cors.origins` predicate stopped being evaluated
three times per request.
That change is a call count, not a rate, and the benchmark's predicate is a `Set` lookup — so the
saving is invisible in req/s here and would be two or three network round trips in the lookup the
option exists for:
| | per cross-origin GET | per preflight |
| --- | --- | --- |
| 26.8.0-beta.1 | 2 | 3 |
| 26.9.0-beta.1 | **1** | **1** |
### Against `26.7`, and why it is not a regression
The table this file carried until today was measured at `fe1831a`, before `26.8.0-beta.1`
shipped. Re-running
that tree today, under the same toolchain and dependencies, gives 94,403 req/s on `hello` and
93,361 on `param` against 89,527 and 85,839 for the current tree — roughly −5% and −8%. Against
`fastify` as a control, which moved +1.2% to +1.8% across the same scenarios, green-tea's ratio to
it fell 6.6% to 11.7%.
**That number is real and it is not a regression, because it is not the same program.** July matched
routes by splitting the path and comparing segments, returning on the first hit, in one flat file.
It had no route constraints, no specificity ranking, no per-request correlation, no lifecycle
stream, and one adapter. It was fast the way something is fast before it does anything.
What the interval bought, in the order it costs: a runtime-neutral request and response boundary,
which is what serves Deno, Bun and workerd from one core rather than one adapter; constraint and
specificity matching; a correlated event stream; and per-request identity.
The first of those is now measurable, because the runtimes table above did not exist either. The
same boundary that costs on Node is what puts the same application on Deno at 153,408 req/s and Bun
at 131,674 against Node's 90,976 — and above the 119,357 that Node's own `http` module manages with
no framework at all. Whether the trade is worth it is the reader's call. This file's job is to say
what it cost and what it bought.
### Figures recorded when each change landed
Measured at the time, in the code, against a microbenchmark rather than this harness:
| Where | Finding |
| --- | --- |
| `src/http/core.ts:63` | a per-request derivation that reached **45% of a whole request** before it was fixed |
| `src/http/core.ts:89` | six request-id generators compared; `crypto.randomUUID` at 76 ns was the fastest cross-runtime option, and the only alternatives that beat it are Node-only |
| `src/http/core.ts:229` | wrapping `dispatch` in a second async frame: 0.43 µs per request |
| `src/bus.ts:173` | spreading request identity into an event payload: ~197 ns on a two-step pipeline |
| `src/pipeline.ts:58` | one timestamp per step boundary instead of two: 25.2 ns against 45.3 ns per step |
| `src/http/headers.ts:30` | 146.4 ns against 55.9 ns for the same header answer |
| `src/http/body.ts:39` | 250 ns per request for a closure and the error context it captured |
| `src/http/router.ts:232` | per-segment decoding on a path nobody decodes: 95.8 ns for `/hello`, 342.7 ns for six segments |
**These do not add up to the release delta, and cannot.** They cite different baselines — 4.4 µs,
4.5 µs, 10.19 µs — because each was taken against whatever a request cost on the day. A dozen
findings in nanoseconds against inconsistent references is a discussion, not a total. A version-level
number measured against a fixed baseline is what was missing, not rigour.
### What is still unattributed
Three candidates for the `26.7` → `26.9` interval were measured and none of them account for it:
- **`crypto.randomUUID` per request** — removing it entirely lands within noise on every scenario,
and one row moves the wrong way. At 76 ns against a ~11 µs request it is ~0.7%, below what a load
test at this CV can resolve.
- **Specificity ranking in the matcher** — replacing it with July's first-match-wins is noise on all
four rows at this route-table size.
- **The bundle versus the TypeScript source** — every row overlaps, so the form the table loads does
not explain it either.
No single culprit was found. The remaining candidates are the neutral request and response objects
and the several small per-request allocations around them, which is a shape that resists a single
measurement.
## What this file does not measure
- **Route-table width was invisible until `26.9`.** Every matcher cost scales with how many
candidates a request walks past, and the cross-framework tables use six routes — so any matcher
change measures as noise there regardless of its size. `npm run bench:compare` carries 50- and
200-route cases for this reason. Settling route ranking when the table is built rather than per
request is worth nothing at six routes, +3.4% at fifty, and **+12% to +14.9% at two hundred**,
across twelve rounds without a crossing sample.
- **Boot time is absent.** Independent providers began booting concurrently in `26.9`: three
providers with no edges and 200 ms of work each went from 616 ms to 210 ms. No table here shows it.
- **Streaming is absent.** Every scenario is a buffered response. SSE framing, the encoder's
per-item work, and the stream lifecycle events are not exercised.
- **The cross-framework tables are Node-only**, and they load green-tea from `src/` through `tsx`
while the other frameworks load their published JavaScript. Measured today, that difference is
within noise — but it is a difference, and the runtimes table above avoids it by loading the built
bundle on all three.
- **The runtimes table compares each runtime's HTTP server, not its JavaScript engine.** `Deno.serve`
and `Bun.serve` are native stacks; Node's `http` is JavaScript. "green-tea on this runtime" is the
claim, and it is the one an application actually experiences.
+1036 -4
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
# CLAUDE.md
See [AGENTS.md](./AGENTS.md). It is the same guidance, kept in one place so the two files cannot drift apart.
+89
View File
@@ -0,0 +1,89 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **compliance@expressive-tea.io**. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
If you would rather write to a named person than to an address, the project lead reads
diego.resendez@expressive-tea.io. Reports about a maintainer, including the project lead,
should go to compliance@expressive-tea.io, which is not maintained by the project team.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+120 -5
View File
@@ -2,6 +2,36 @@
Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**. Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**.
## Where to send your changes
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main`, release tags, and `develop` — the last one under the name `contrib`. Which branch you target depends on where you are.
**From GitHub, if you are an outside contributor:** open your pull request against **`contrib`**. Not `main`. `main` on GitHub is a mirror of released code, and merging into it puts the two forges out of sync and breaks the next release push. A maintainer reviews on `contrib` and then carries your commits upstream into Gitea's `develop`, with your authorship and your sign-off intact. `contrib` is a mirror of `develop`, so you are working against the current code rather than the last release.
**From Gitea, if you have access:** follow the branch model below.
### Worked example
```bash
# fork Expressive-Tea/green-tea on GitHub, then
git clone git@github.com:<you>/green-tea.git
cd green-tea
git remote add upstream https://github.com/Expressive-Tea/green-tea.git
git fetch upstream
# branch from contrib, not from main
git checkout -b fix/close-timeout upstream/contrib
# ... make the change, add a test ...
git commit -s -m "fix: add a timeout to app.close()"
git push origin fix/close-timeout
```
Then open the pull request with **`contrib`** as the base branch.
`contrib` follows `develop`, so it moves whenever development does. If your branch has been open a while, rebase onto the current `contrib` before pushing again.
## Developer Certificate of Origin (DCO) ## Developer Certificate of Origin (DCO)
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork. We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork.
@@ -26,6 +56,34 @@ To sign off a range you forgot to sign:
git rebase --signoff <base> git rebase --signoff <base>
``` ```
Or, for the commit you just made:
```bash
git commit --amend -s
git push --force-with-lease
```
## Working with AI assistance
Use one if it helps. There is no permission to ask for and nothing to declare.
What we do ask is that you read what it hands you before it becomes a pull request. Every line that lands here is reviewed by a person, by hand, and usually that person is one person. A diff its own author hasn't read moves that work onto them, and turns review into proofreading — which is the thing review is worst at.
So go through the diff the way you would go through a stranger's, because that is what it is. If you can't say why a line is there, it isn't ready to send. That's the whole of it.
**What assistants tend to get wrong here in particular** — worth checking before you push:
- They add dependencies. Core has one runtime dependency, and that is a design constraint rather than an oversight.
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` is the Node suite only. CI runs the other three, and `npm run test:all` runs them locally.
- They delete comments they read as redundant. In this codebase a comment usually carries reasoning the code can't show on its own.
- They skip the test.
**Where you're unsure, say so** — not as a disclosure, as a pointer. "I'm not confident about the Deno path here" tells a reviewer where to spend their attention, and that is worth more to them than a pull request that merely looks clean.
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the work under this project's license, and that stays true however the text was produced.
If your assistant reads repository instructions, `AGENTS.md` has the conventions and the architecture notes.
## Branch model (GitFlow) ## Branch model (GitFlow)
- `main` — production-ready, protected. No direct pushes. - `main` — production-ready, protected. No direct pushes.
@@ -33,6 +91,7 @@ git rebase --signoff <base>
- `feature/<name>` — branch from `develop`. - `feature/<name>` — branch from `develop`.
- `hotfix/<name>` — branch from `main`. - `hotfix/<name>` — branch from `main`.
- `release/<version>` — release stabilization. - `release/<version>` — release stabilization.
- `contrib` — GitHub only. A mirror of `develop`, and where outside contributions land before a maintainer carries them into `develop`.
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.) `main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
@@ -40,17 +99,73 @@ git rebase --signoff <base>
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution. Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
## Before you open an MR ## Local setup
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 ```bash
npm test # all tests must pass npm install
npm run typecheck # must be clean — this includes the compile-time-guarantee type test
``` ```
That does one thing worth knowing about: the `prepare` script points `core.hooksPath` at
`.githooks/`, which installs a pre-commit gate. The gate formats and lint-fixes your staged
sources automatically, then refuses the commit if `npm run lint` or `npm run complexity:check`
fails. It is there so CI tells you nothing you couldn't have heard locally. Confirm it took:
```bash
git config core.hooksPath # should print .githooks
```
If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you install with
something other than npm, check this before your first commit rather than after.
`npm test` runs the Node suite under Vitest. The other three runtimes have their own commands
and their own toolchains:
```bash
npm run test:deno # needs deno
npm run test:bun # needs bun
npm run test:edge # Miniflare
npm run test:all # all four, plus the JSR gate (deno publish --dry-run)
```
CI runs all three on every push and pull request, in the `runtimes` job, and each one gates a
merge just as the Node suite does. You are not expected to install all three to fix a typo. You
are expected to run the one your change touches, and to say in the pull request which ones you ran,
so a red Bun job is not the first time anyone hears about it.
## Before you open a pull request
Run what CI runs:
```bash
npm run lint
npm run format:check
npm run typecheck # must be clean — this includes the compile-time-guarantee type test
npm test # all tests must pass
npm run complexity:check
npm run build
npm audit --omit=dev # only what ships blocks; CI reports the rest
```
plus the runtime suite for whatever your change touches (see *Local setup* above). CI runs Deno,
Bun and the edge in its `runtimes` job.
- Write tests for new behavior (TDD welcome). We use Vitest. - Write tests for new behavior (TDD welcome). We use Vitest.
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
- Keep runtime dependencies at zero beyond `reflect-metadata`. - Keep runtime dependencies at zero beyond `reflect-metadata`.
- New public API needs a doc note in `README.md`. - A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package.
- New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page.
- If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not.
On GitHub, workflows do not run on pull requests from forks until a maintainer approves them, so your first push may sit without any checks for a while. That is not a rejection.
## Reporting issues ## Reporting issues
Open an issue with a minimal reproduction: green-tea version, Node version, and the smallest module/route that shows the problem. Open an issue with a minimal reproduction: green-tea version, runtime and version, and the smallest module/route that shows the problem.
**Except for security.** If what you found is exploitable, do not open an issue — an issue is world-readable the moment you press the button. Email security@expressive-tea.io or use the [private advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new). [`SECURITY.md`](./SECURITY.md) has the scope and what to expect back.
## Code of conduct
By taking part here you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md), which is the Contributor Covenant 2.1. Reports go to compliance@expressive-tea.io.
+103 -20
View File
@@ -7,8 +7,13 @@
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p> <p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
<p align="center"> <p align="center">
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br /> <b>Declare intent. Derive execution.</b><br />
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵 You declare what each step <b>needs</b> and <b>produces</b>; green-tea derives the order,<br />
validates the wiring before it serves traffic, and runs only the slice each route requires.
</p>
<p align="center">
<i>Less infrastructure in your application. Less infrastructure in your head.</i> 🍵
</p> </p>
--- ---
@@ -38,6 +43,8 @@ Less to hold in your head. That's the tea.
npm install @green-tea/core@beta reflect-metadata npm install @green-tea/core@beta reflect-metadata
``` ```
Requires Node 22 or newer. Node 18 and 20 are end-of-life and are not supported. Deno, Bun and Cloudflare Workers run the same code.
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
```bash ```bash
@@ -51,9 +58,35 @@ npm install busboy # multipart/form-data file uploads
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time. - **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.) - **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on. - **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere. - **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`await app.listen()` → `await serveDeno()` / `await serveBun()` / `edgeHandler`) and nothing else — each one boots the app before it binds, so a provider that cannot start fails the deploy instead of answering `500`s from a port that looks healthy. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere. - **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser. - **Plugins can't sabotage you.** A plugin is `{ name, mount(api) }`. It gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
## Who does the work?
Every backend has the same set of infrastructure decisions. The question is which side of the
`import` they live on.
| Decision | Owned by |
|---|---|
| Execution order | green-tea — derived from `needs`/`provides`, never maintained by hand |
| Dependency validation | green-tea — boot fails when nothing provides a key |
| Which steps a route runs | green-tea — the graph slice its handler actually depends on |
| Streaming mechanics — framing, backpressure, cleanup, disconnects | green-tea |
| OpenAPI projection | green-tea — from the same metadata that runs the app |
| Secure transport defaults | green-tea — headers, CORS, TLS |
| Runtime serving boundary | green-tea — `listen`, `fetch`, `upgrade` per runtime |
| Shutdown sequencing | green-tea — drain, then teardown, inside one deadline |
| **Business rules** | **you** |
That division is the whole design, and it is why `reflect-metadata` is the only runtime dependency:
the goal is not a small number for its own sake, it is **fewer moving parts your team has to
understand, upgrade, coordinate and debug**. A framework that owns less pushes the difference into
your application, where it becomes your maintenance instead of disappearing.
Automated does not mean invisible. `app.explain()` prints the ordered chain, `app.graph()` renders
the live graph, and `app.openapi()` projects the same metadata — the graph is not documentation drawn
after the fact, it is the structure green-tea validates and executes.
## Real-time is a primitive, not a second framework ## Real-time is a primitive, not a second framework
@@ -98,9 +131,10 @@ class Live {
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn. Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
## Batteries included — still one dependency ## What the foundation already carries
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`: The parts a real API needs, owned by the framework rather than assembled in your application — and
without growing the runtime dependency tree past `reflect-metadata`:
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). - **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
@@ -108,19 +142,34 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **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. - **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. - **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. - **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. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything. - **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.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links. - **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 })`.
- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`.
- **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.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
## Benchmarks ## Benchmarks
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering. green-tea keeps a reproducible [autocannon](https://github.com/mcollina/autocannon) harness in
`bench/`, and it is written to be hard on green-tea rather than flattering. It answers two
different questions, and they need different setups:
On that harness, **green-tea handled more requests per second than every other framework in 3 of 4 scenarios** (JSON response, routing, and body-parsing-plus-validation), behind only raw `http` with no framework at all. In the fourth (a multi-step pipeline) it lands even with Fastify. - **How does green-tea compare to other frameworks?** `npm run bench` runs green-tea, Express 5,
Fastify 5, NestJS on Express and on Fastify, and raw Node `http` through the same scenarios on
one box, then writes [BENCHMARKS.md](./BENCHMARKS.md).
- **Did the last N commits cost anything?** `npm run bench:compare` runs two versions of green-tea
on one box in one sitting, alternating sides, so the difference is the code rather than the
machine's mood that day.
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`. This section carries no numbers on purpose. A ranking written into prose is a claim nobody
re-measures, and it goes stale with the next release. The figures, the hardware and date they
were taken on, and the caveats live in [BENCHMARKS.md](./BENCHMARKS.md). The caveats include
single-box loopback, trusting the ratios over the absolute numbers, and green-tea running with
`security: false` for header parity, with the cost of secure-by-default measured separately.
## How it compares ## How it compares
@@ -206,6 +255,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` | | `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | | `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` | | `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it. `@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
@@ -222,7 +275,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/). `@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 ## Two layers
@@ -243,26 +303,48 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet. **Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about. **Observability is a contract, not an integration.** Core emits a correlated lifecycle event stream — every request gets an id (an incoming `x-request-id` is adopted, not replaced), every event carries it, and each step reports its own duration. `createApp({ logger })` takes any logger; the default writes structured JSON, or a readable line on a TTY. Nothing in core writes to `console`, which is enforced by a lint rule rather than a promise. `createApp({ logRequests: true })` logs a line per request, off by default.
**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. **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 ≥ 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. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip.
**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. **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.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
## Docs & development ## Docs & development
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. - **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs).
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it. - **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
> **Changing public API? The docs are a separate repository now, and nothing tells you when you break them.**
> [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) imports nothing from here, so no build fails and no test turns red when a guide describes an API that no longer exists. **A pull request that changes public API updates the page documenting it, in the same pull request.** This is a rule rather than a check because no check exists yet — issue #18 is what a stale page looks like from a user's side, and that happened while both still lived in this repository.
```bash ```bash
npm install npm install
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes npm test # vitest (Node only) — the fast loop, ~2s
npm run test:all # everything below, plus the JSR gate — the pre-push check
npm run test:deno # deno test } a change to shared code can pass `npm test`
npm run test:bun # bun test } and still be broken on one of these
npm run test:edge # workerd via miniflare
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test) npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/ (tsup: dual ESM + CJS) npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
``` ```
`npm test` stays Node-only on purpose: it is the loop you run constantly, and booting Deno, Bun and
workerd into it would tax every run to catch what CI already catches on every push. Nothing here is
unguarded — the `runtimes` job runs all three, and `deno publish --dry-run` gates JSR. `test:all` is
for the moment before you push, when you would rather find out locally.
That last one is a second type-checker, not a packaging formality: `npm run typecheck` is `tsc` with
this repository's config, while `deno publish --dry-run` is Deno's checker with Deno's lib plus JSR's
slow-types rules over the public API. JSR serves `src/` directly, so what it rejects is what a JSR
consumer would have received.
## Roadmap ## Roadmap
- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`. - ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
@@ -270,10 +352,11 @@ npm run docs:dev # the documentation site (website/)
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup. - ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`. - ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices. - ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. - ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. Every CI run exercises all four; the Deno, Bun, and workerd suites gate a merge exactly as the Node one does.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving. - ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes. - ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables. - ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
- **next** — API freeze + first stable release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
## Versioning ## Versioning
+68
View File
@@ -0,0 +1,68 @@
# Security Policy
## Reporting a vulnerability
Email **security@expressive-tea.io**. Please do not open a public issue for something
exploitable — an issue is world-readable from the moment you press the button, and that is
the one thing a security report cannot be.
Include whatever you have: the version, the runtime, and the smallest app that shows it.
A route, a module and a request is usually enough. If you have a working exploit, send it;
if you only have a suspicion, send that instead of sitting on it.
You can also report privately through GitHub's
[security advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new),
which reaches the same people.
## What happens next
Acknowledgement within **5 working days**. A verdict on whether we agree it is a vulnerability
within **15**. If we agree, you get the fix timeline and a heads-up before the advisory goes
public. If we don't, you get the reasoning rather than silence.
Those numbers are deliberately slower than the 24 to 48 hours you will see quoted elsewhere.
That figure comes from the CERT Guide to Coordinated Vulnerability Disclosure and describes
vendors and coordinators — organizations with someone on rotation. This project is one person.
A number that only holds in a good week is worse than an honest one.
Which is why there is an escape hatch, and you should use it. **If you have no acknowledgement
after 10 working days**, write directly to diego.resendez@expressive-tea.io. If that is also
met with silence, consider yourself released from any embargo and disclose as you see fit. You
will not have done anything wrong: a project that goes quiet on a security report has spent
whatever claim it had on your patience.
## Disclosure window
We ask for **90 days** from your report before public disclosure, or until the fix ships,
whichever comes first. That is the industry default and we are not asking you for more than
anyone else does. If the fix is out in a week, so is the advisory.
If a vulnerability is being actively exploited, the window is however long it takes us to ship,
and we will say so rather than hold you to 90 days while users are being attacked.
We publish a GitHub advisory for anything that affects a released version, and credit you by
the name you ask for. Say so if you would rather not be named.
There is no bug bounty and no money, which we would rather state here than leave you to find
out after the work.
## Supported versions
While the package is in beta, only the most recent `26.x.y-beta.N` receives fixes. There is no
backport channel yet; when the first stable ships, this section gets the real table.
## Scope
In scope: anything in `src/` that ships in the published package — route matching, the request
pipeline, body parsing and its limits, the security headers and CORS handling, TLS setup, the
WebSocket upgrade path, the mesh wire protocol, static file serving and view rendering.
Out of scope: the benchmarks in `bench/`, the documentation site (now its own repository,
[green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)), dev-only tooling, and
anything that requires an attacker to already control your application code. Advisories in
build-time dependencies are worth telling us about, but they are not vulnerabilities in
green-tea and we handle them as ordinary dependency updates.
A denial of service that needs no authentication is in scope. Reports that amount to "this
endpoint is slow under load" generally are not — but if you are unsure which one you have,
send it and let us decide.
+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
+279
View File
@@ -0,0 +1,279 @@
/**
* Compares green-tea against an earlier green-tea, on one box, in one sitting.
*
* `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release
* actually has to pass: **did the last N commits cost anything.** It is a different measurement and
* it needs a different setup, because comparing today's numbers against a table generated weeks ago
* compares two machines-in-a-mood, not two versions.
*
* Usage:
*
* git worktree add /tmp/base v26.8.0-beta.1
* ln -s "$PWD/node_modules" /tmp/base/node_modules
* AB_BASE=/tmp/base npm run bench:compare
*
* The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has
* not moved between the two revisions — check that first, or the comparison is measuring a
* dependency bump.
*
* Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100),
* `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json).
*/
import autocannon from 'autocannon';
import { spawn } from 'child_process';
import { writeFileSync } from 'fs';
const DURATION = Number(process.env.AB_DURATION ?? 10);
const ROUNDS = Number(process.env.AB_ROUNDS ?? 3);
const CONNS = Number(process.env.AB_CONNS ?? 100);
const HEAD = process.cwd();
// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables.
const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare';
const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare';
function requireBase(): string {
const base = process.env.AB_BASE;
if (base) return base;
console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.');
process.exit(1);
}
const BASE = requireBase();
interface Case {
name: string;
path: string;
method?: 'GET' | 'POST' | 'OPTIONS';
body?: unknown;
headers?: Record<string, string>;
env?: Record<string, string>;
}
const ORIGIN = { origin: 'http://bench.example' };
const CASES: Case[] = [
{ name: 'hello', path: '/hello' },
{ name: 'param', path: '/users/42' },
{ name: 'pipeline (3 steps)', path: '/pipeline' },
{ name: 'steps5', path: '/steps/5' },
{ name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } },
{ name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } },
// The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets
// the header measures the path around it rather than the path through it.
{ name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN },
{
name: 'preflight + cors predicate',
path: '/hello',
method: 'OPTIONS',
env: { GT_CORS: '1' },
headers: { ...ORIGIN, 'access-control-request-method': 'GET' },
},
// Route-table width. Every matcher cost scales with the number of candidates a request walks
// past, and the cross-framework table has six routes — so a change that saves work per candidate
// measures as noise there no matter how real it is. `/users/:id` is registered last and is not
// all-static, so it takes the full scan rather than the early exit a literal path gets.
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
// Compression (CARD-16). `json 8KB uncompressed` is the same response uncompressed, so each compressed case
// has its own baseline in the table. `hello + compression` sits under the threshold: the cost of
// deciding not to encode, which is what most small responses pay once compression is on. Without
// `accept-encoding`, the 8 KB case measures negotiation alone.
{ name: 'json 8KB uncompressed', path: '/big' },
{ name: 'hello + compression', path: '/hello', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip, br' } },
{ name: 'json 8KB + compression, identity', path: '/big', env: { GT_COMPRESS: '1' } },
{ name: 'json 8KB + gzip', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } },
{ name: 'json 8KB + br', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'br' } },
];
const ONLY = process.env.AB_ONLY;
const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES;
function log(m: string): void {
process.stderr.write(`[compare] ${m}\n`);
}
async function boot(cwd: string, env: Record<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], {
cwd,
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env },
});
let stderr = '';
child.stderr.on('data', (d) => (stderr += d));
const port = await new Promise<number>((resolve, reject) => {
const t = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error(`no READY in 15s:\n${stderr}`));
}, 15000);
let buf = '';
child.stdout.on('data', (d) => {
buf += d;
const m = /READY (\d+)/.exec(buf);
if (m) {
clearTimeout(t);
resolve(Number(m[1]));
}
});
child.on('exit', (c) => {
clearTimeout(t);
reject(new Error(`exited ${c}:\n${stderr}`));
});
});
const kill = (): Promise<void> =>
new Promise<void>((r) => {
child.on('exit', () => r());
child.kill('SIGTERM');
setTimeout(() => {
try {
child.kill('SIGKILL');
} catch {
/* already dead */
}
}, 2000);
});
return { port, kill };
}
async function hit(port: number, c: Case, warmup = false): Promise<number> {
const r = (await autocannon({
url: `http://127.0.0.1:${port}${c.path}`,
connections: CONNS,
duration: DURATION,
pipelining: 1,
method: (c.method ?? 'GET') as 'GET',
headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers },
body: c.body ? JSON.stringify(c.body) : undefined,
})) as unknown as {
requests: { average: number };
non2xx?: number;
errors?: number;
timeouts?: number;
};
// A case whose route 404s still posts a req/s number, and a run whose connections all errored
// posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this
// case claims to send before believing any of it.
// Not on the warmup: a cold server drops a handful of connections from the opening burst, and
// absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise
// it exists to discard.
if (!warmup) {
const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0);
if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`);
if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`);
}
return r.requests.average;
}
const median = (xs: number[]): number => {
const s = [...xs].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
};
/**
* True when the two sides' sample ranges do not overlap at all.
*
* A weak signal on its own and stated as such: with three samples a pair of overlapping
* distributions separates by chance often enough to fool you, which it did the first time this was
* run. Treat a flagged row as "measure it again with more rounds", never as a result.
*/
const separated = (a: number[], b: number[]): boolean => {
const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)];
return x[0] > y[y.length - 1] || y[0] > x[x.length - 1];
};
/**
* Counts `cors.origins` invocations for one cross-origin GET and one preflight.
*
* Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved
* are invisible in req/s — but the option takes a function so it can be a lookup, and there the
* same saving is a network round trip.
*/
async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> {
const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server);
const base = `http://127.0.0.1:${port}`;
// The read carries no `Origin`, so asking cannot change the answer.
const read = async (): Promise<number> => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls;
try {
const before = await read();
await fetch(`${base}/hello`, { headers: ORIGIN });
const afterGet = await read();
await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } });
const afterPreflight = await read();
return { get: afterGet - before, preflight: afterPreflight - afterGet };
} finally {
await kill();
}
}
async function main(): Promise<void> {
const samples: Record<string, { base: number[]; head: number[] }> = {};
for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] };
for (let round = 0; round < ROUNDS; round++) {
// Alternate which side goes first. Thermal drift and background load over a half-hour run are
// real; alternating spreads them across both sides instead of charging them to whichever went
// second.
const order: Array<['base' | 'head', string]> =
round % 2 === 0
? [
['base', BASE],
['head', HEAD],
]
: [
['head', HEAD],
['base', BASE],
];
for (const [side, cwd] of order) {
for (const c of RUN_CASES) {
const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER);
try {
await hit(port, c, true); // warmup, discarded
const v = await hit(port, c);
samples[c.name][side].push(v);
log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`);
} finally {
await kill();
}
}
}
}
const rows = RUN_CASES.map((c) => {
const b = median(samples[c.name].base);
const h = median(samples[c.name].head);
return {
name: c.name,
base: b,
head: h,
delta: ((h - b) / b) * 100,
separated: separated(samples[c.name].base, samples[c.name].head),
samples: samples[c.name],
};
});
const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) };
writeFileSync(
process.env.AB_OUT ?? 'bench/compare-results.json',
JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2),
);
const f = (n: number): string => Math.round(n).toLocaleString();
console.log('\n| Scenario | base | head | Δ | |');
console.log('| --- | --- | --- | --- | --- |');
for (const r of rows) {
const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps';
console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`);
}
console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`);
console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+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);
});
+31 -1
View File
@@ -37,6 +37,8 @@ export interface RenderData {
scenarios: ScenarioBlock[]; scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[]; stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; reqSec: number }[]; secureCost: { label: string; reqSec: number }[];
/** Optional: results captured before the runtime matrix existed still render. */
runtimes?: { runtime: string; scenario: string; reqSec: number }[];
} }
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US'); const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
@@ -124,6 +126,33 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n'); return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
} }
/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */
function renderRuntimes(runtimes: RenderData['runtimes']): string {
if (!runtimes?.length) return '';
const names = [...new Set(runtimes.map((row) => row.runtime))];
const scenarios = [...new Set(runtimes.map((row) => row.scenario))];
const at = (runtime: string, scenario: string): number | undefined =>
runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec;
const header = `| Scenario | ${names.join(' | ')} |`;
const divider = `| --- | ${names.map(() => '---').join(' | ')} |`;
const lines = scenarios.map((scenario) => {
const cells = names.map((runtime) => {
const value = at(runtime, scenario);
return value === undefined ? '—' : fmtInt(value);
});
return `| ${scenario} | ${cells.join(' | ')} |`;
});
const note =
'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' +
'never against the cross-framework tables above: those measure other frameworks on Node, and ' +
'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.';
return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n');
}
function renderSecureCost(secureCost: RenderData['secureCost']): string { function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |'; const header = '| Label | req/s |';
const divider = '| --- | --- |'; const divider = '| --- | --- |';
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
} }
export function renderMarkdown(data: RenderData): string { export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data; const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
return [ return [
renderLeaderboard(scenarios), renderLeaderboard(scenarios),
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
'', '',
renderScenarios(scenarios), renderScenarios(scenarios),
renderStepScaling(stepScaling), renderStepScaling(stepScaling),
renderRuntimes(runtimes),
renderSecureCost(secureCost), renderSecureCost(secureCost),
renderMethodology(), renderMethodology(),
].join('\n'); ].join('\n');
+266 -204
View File
@@ -1,17 +1,17 @@
{ {
"env": { "env": {
"date": "2026-07-07", "date": "2026-09-22",
"commit": "fe1831a", "commit": "daf0fed",
"node": "v22.22.2", "node": "v22.22.2",
"os": "darwin", "os": "linux",
"cpu": "Apple M4 Max (16 cores)", "cpu": "AMD Ryzen 7 3700X 8-Core Processor (16 cores)",
"ram": "69 GB", "ram": "67 GB",
"pinned": false "pinned": false
}, },
"config": { "config": {
"conns": 100, "conns": 100,
"duration": 5, "duration": 10,
"runs": 3, "runs": 5,
"warmup": 1, "warmup": 1,
"pipelining": 1 "pipelining": 1
}, },
@@ -23,80 +23,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 115398.4, "median": 41630.55,
"min": 114822.4, "min": 41342.55,
"max": 115539.2, "max": 41973.82,
"stddev": 310.09010876768724, "stddev": 232.79156158245826,
"cv": 0.0026905088104554075 "cv": 0.0055977118567263305
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 4
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86764.8, "median": 32170.19,
"min": 86496, "min": 31235.64,
"max": 87123.2, "max": 32355.64,
"stddev": 256.9227813090051, "stddev": 403.36620390905324,
"cv": 0.002960121758353106 "cv": 0.012593571579786219
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 3,
"p999": 2 "p999": 5
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24366.4, "median": 10545.82,
"min": 24283.2, "min": 10480.37,
"max": 24417.6, "max": 10625.1,
"stddev": 55.38455460585383, "stddev": 47.02831087759791,
"cv": 0.002273984274990166 "cv": 0.004456044641032285
}, },
"p50": 3, "p50": 8,
"p99": 5, "p99": 13,
"p999": 8 "p999": 18
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 98092.8, "median": 29776.73,
"min": 98054.4, "min": 29557.1,
"max": 98668.8, "max": 29872.73,
"stddev": 281.0175795212842, "stddev": 120.92248317000461,
"cv": 0.002859589501804015 "cv": 0.004066812850878315
}, },
"p50": 0, "p50": 3,
"p99": 1, "p99": 6,
"p999": 2 "p999": 7
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 21761.6, "median": 9679.64,
"min": 21697.6, "min": 9566.91,
"max": 21896, "max": 9738.55,
"stddev": 82.67870880032535, "stddev": 58.2951632985104,
"cv": 0.0037952010918943873 "cv": 0.006025529205104781
}, },
"p50": 4, "p50": 9,
"p99": 6, "p99": 15,
"p999": 10 "p999": 21
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 95033.6, "median": 32418.91,
"min": 94240, "min": 32103.28,
"max": 95264, "max": 32582.55,
"stddev": 438.6166536839312, "stddev": 159.574135748874,
"cv": 0.00462452048886261 "cv": 0.004929287112917938
}, },
"p50": 1, "p50": 3,
"p99": 1, "p99": 4,
"p999": 2 "p999": 6
} }
] ]
}, },
@@ -107,80 +107,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 116332.8, "median": 41755.64,
"min": 115974.4, "min": 40952.73,
"max": 116409.6, "max": 42017.46,
"stddev": 189.66281191162406, "stddev": 439.72294183496837,
"cv": 0.001631663389130871 "cv": 0.010587809774433589
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 4
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86278.4, "median": 31708.37,
"min": 86137.6, "min": 31359.28,
"max": 86764.8, "max": 31846.55,
"stddev": 268.69839349476365, "stddev": 168.73300179869975,
"cv": 0.003110165492522174 "cv": 0.005328784944282288
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 4,
"p999": 2 "p999": 5
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23835.2, "median": 10375.64,
"min": 23803.2, "min": 10364,
"max": 24046.4, "max": 10452.73,
"stddev": 107.89690552662897, "stddev": 37.668132419858544,
"cv": 0.004515472130491916 "cv": 0.003621859193349617
}, },
"p50": 3, "p50": 9,
"p99": 5, "p99": 12,
"p999": 8 "p999": 17
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 93433.6, "median": 28706.19,
"min": 93152, "min": 28562.19,
"max": 93612.8, "max": 29050.91,
"stddev": 189.6628119116206, "stddev": 166.92265315408858,
"cv": 0.002030662686635119 "cv": 0.005803163694455583
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 6,
"p999": 2 "p999": 7
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20955.2, "median": 9257.1,
"min": 20948.8, "min": 9244,
"max": 21201.6, "max": 9285.46,
"stddev": 117.69157432317111, "stddev": 16.97885461390117,
"cv": 0.005594982425799189 "cv": 0.0018327336012062287
}, },
"p50": 4, "p50": 10,
"p99": 6, "p99": 15,
"p999": 11 "p999": 21
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 89312, "median": 29880,
"min": 89235.2, "min": 29744.73,
"max": 89529.6, "max": 29961.46,
"stddev": 124.68598780759793, "stddev": 90.38256681462417,
"cv": 0.001395338811201841 "cv": 0.003027383166346
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 4,
"p999": 2 "p999": 6
} }
] ]
}, },
@@ -192,80 +192,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 113491.2, "median": 39896.73,
"min": 112531.2, "min": 39847.28,
"max": 114809.6, "max": 40440.73,
"stddev": 933.9810324031724, "stddev": 235.6558649726337,
"cv": 0.008220892102882115 "cv": 0.0058846766178520865
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 5
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 85024, "median": 31436.37,
"min": 84512, "min": 31078.55,
"max": 85177.6, "max": 31562.91,
"stddev": 284.55819947576623, "stddev": 185.21052212010017,
"cv": 0.003351507726431956 "cv": 0.005909263441314207
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 4,
"p999": 2 "p999": 6
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23950.4, "median": 10365.46,
"min": 23902.4, "min": 10170.55,
"max": 24011.2, "max": 10542.19,
"stddev": 44.519758410046, "stddev": 129.83340146510884,
"cv": 0.0018585004345727763 "cv": 0.01252603707960138
}, },
"p50": 3, "p50": 9,
"p99": 5, "p99": 12,
"p999": 8 "p999": 18
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 84896, "median": 26838.55,
"min": 84243.2, "min": 26783.28,
"max": 85267.2, "max": 26872,
"stddev": 423.2825796347192, "stddev": 35.930271582608675,
"cv": 0.004991414284012342 "cv": 0.0013390899572667937
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 6,
"p999": 2 "p999": 8
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20824, "median": 9256.37,
"min": 20804.8, "min": 9187.28,
"max": 20878.41, "max": 9302.19,
"stddev": 31.17605954717337, "stddev": 42.180541200890175,
"cv": 0.001496278247605678 "cv": 0.0045584972844857205
}, },
"p50": 4, "p50": 10,
"p99": 6, "p99": 15,
"p999": 11 "p999": 22
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 87328, "median": 29402.91,
"min": 86867.2, "min": 29151.28,
"max": 87660.8, "max": 29689.46,
"stddev": 325.38753646827104, "stddev": 189.99449229911926,
"cv": 0.0037278603866430907 "cv": 0.006460862473261261
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 4,
"p999": 2 "p999": 6
} }
] ]
}, },
@@ -276,80 +276,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 100140.8, "median": 31783.28,
"min": 99846.4, "min": 31517.1,
"max": 100294.4, "max": 31824.73,
"stddev": 185.88177843875883, "stddev": 111.5598838292694,
"cv": 0.0018570746103533369 "cv": 0.003516116881358333
}, },
"p50": 0, "p50": 3,
"p99": 1, "p99": 5,
"p999": 2 "p999": 6
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 63721.6, "median": 20429.82,
"min": 63574.4, "min": 20397.82,
"max": 63760, "max": 20601.46,
"stddev": 79.99288857281053, "stddev": 73.12471046096515,
"cv": 0.0012560645345785087 "cv": 0.0035727493036941836
}, },
"p50": 1, "p50": 4,
"p99": 2, "p99": 8,
"p999": 3 "p999": 9
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 20097.6, "median": 8440.37,
"min": 20056, "min": 8407.64,
"max": 20174.41, "max": 8492,
"stddev": 49.04789518646266, "stddev": 29.52737333390846,
"cv": 0.0024390608203285337 "cv": 0.003496408589959768
}, },
"p50": 4, "p50": 11,
"p99": 6, "p99": 16,
"p999": 12 "p999": 24
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 77177.61, "median": 22005.1,
"min": 77126.4, "min": 21736,
"max": 77254.4, "max": 22186.91,
"stddev": 52.602458962379814, "stddev": 149.1731413626461,
"cv": 0.0006815013839797027 "cv": 0.006790967759795645
}, },
"p50": 1, "p50": 4,
"p99": 2, "p99": 7,
"p999": 2 "p999": 9
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 18856, "median": 7666.37,
"min": 18852.8, "min": 7645.28,
"max": 19067.2, "max": 7703.46,
"stddev": 100.32338821143516, "stddev": 20.418688106732038,
"cv": 0.005301010367660728 "cv": 0.002662071942974812
}, },
"p50": 5, "p50": 12,
"p99": 7, "p99": 18,
"p999": 30 "p999": 26
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 59145.6, "median": 18596.8,
"min": 59004.8, "min": 18540.37,
"max": 59376, "max": 18658.19,
"stddev": 153.00625985741647, "stddev": 37.943211988443956,
"cv": 0.002585636725423652 "cv": 0.0020404741150848267
}, },
"p50": 1, "p50": 4,
"p99": 3, "p99": 8,
"p999": 3 "p999": 11
} }
] ]
} }
@@ -358,27 +358,89 @@
{ {
"path": "/steps/0", "path": "/steps/0",
"steps": 0, "steps": 0,
"reqSec": 92281.6 "reqSec": 29196.37
}, },
{ {
"path": "/steps/3", "path": "/steps/3",
"steps": 3, "steps": 3,
"reqSec": 81529.61 "reqSec": 26563.64
}, },
{ {
"path": "/steps/5", "path": "/steps/5",
"steps": 5, "steps": 5,
"reqSec": 71993.61 "reqSec": 25314.19
} }
], ],
"secureCost": [ "secureCost": [
{ {
"label": "security:false (parity)", "label": "security:false (parity)",
"reqSec": 98092.8 "reqSec": 29776.73
}, },
{ {
"label": "security:true (default)", "label": "security:true (default)",
"reqSec": 92998.4 "reqSec": 28918.55
}
],
"runtimes": [
{
"runtime": "node",
"scenario": "JSON hello (overhead)",
"reqSec": 30378.91
},
{
"runtime": "node",
"scenario": "Route param",
"reqSec": 29203.64
},
{
"runtime": "node",
"scenario": "Pipeline (3 steps)",
"reqSec": 27208
},
{
"runtime": "node",
"scenario": "POST JSON + validation",
"reqSec": 22608.73
},
{
"runtime": "deno",
"scenario": "JSON hello (overhead)",
"reqSec": 51888
},
{
"runtime": "deno",
"scenario": "Route param",
"reqSec": 51785.6
},
{
"runtime": "deno",
"scenario": "Pipeline (3 steps)",
"reqSec": 50692.37
},
{
"runtime": "deno",
"scenario": "POST JSON + validation",
"reqSec": 35742.55
},
{
"runtime": "bun",
"scenario": "JSON hello (overhead)",
"reqSec": 46299.64
},
{
"runtime": "bun",
"scenario": "Route param",
"reqSec": 42788.37
},
{
"runtime": "bun",
"scenario": "Pipeline (3 steps)",
"reqSec": 39643.64
},
{
"runtime": "bun",
"scenario": "POST JSON + validation",
"reqSec": 31960
} }
] ]
} }
+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
+78 -4
View File
@@ -1,17 +1,30 @@
import autocannon from 'autocannon'; import autocannon from 'autocannon';
import { spawn, execSync } from 'child_process'; import { spawn, execSync } from 'child_process';
import os from 'os'; import os from 'os';
import { writeFileSync } from 'fs'; import { existsSync, readFileSync, writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios'; import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats'; import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render'; import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
/** Hand-written notes start here and are carried across regenerations verbatim. */
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
const SMOKE = process.env.BENCH_SMOKE === '1'; const SMOKE = process.env.BENCH_SMOKE === '1';
const CONNS = Number(process.env.BENCH_CONNS ?? 100); const CONNS = Number(process.env.BENCH_CONNS ?? 100);
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10); const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5); const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1); const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
/** Whether a runtime is on PATH. */
function which(cmd: string): boolean {
try {
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function log(msg: string): void { function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`); process.stderr.write(`[bench] ${msg}\n`);
} }
@@ -23,11 +36,25 @@ interface RunResult {
p999: number; p999: number;
} }
/**
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
* are handed to their own runtime, which is the whole point of measuring them.
*/
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
// missing flag fails as a boot timeout that reads like a framework problem.
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
bun: (file) => ({ cmd: 'bun', args: [file] }),
};
async function spawnServer( async function spawnServer(
name: string, name: string,
extraEnv: Record<string, string> = {}, extraEnv: Record<string, string> = {},
runtime: 'node' | 'deno' | 'bun' = 'node',
): Promise<{ port: number; kill: () => Promise<void> }> { ): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], { const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
const child = spawn(cmd, args, {
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv }, env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
}); });
let stderr = ''; let stderr = '';
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
})); }));
const stepScaling: RenderData['stepScaling'] = []; const stepScaling: RenderData['stepScaling'] = [];
const secureCost: RenderData['secureCost'] = []; const secureCost: RenderData['secureCost'] = [];
const runtimes: RenderData['runtimes'] = [];
for (const fw of frameworks) { for (const fw of frameworks) {
log(`booting ${fw}`); log(`booting ${fw}`);
@@ -145,10 +173,49 @@ async function main(): Promise<void> {
} }
} }
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
// fastify-on-Node would read as a comparison nobody made.
//
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
// runtime is not installed — a contributor without Bun should still get every other table.
for (const { runtime, server } of [
{ runtime: 'node', server: 'green-tea-node' },
{ runtime: 'deno', server: 'green-tea-deno' },
{ runtime: 'bun', server: 'green-tea-bun' },
] as const) {
if (runtime !== 'node' && !which(runtime)) {
log(`skipping ${runtime}: not installed`);
continue;
}
log(`booting green-tea on ${runtime}`);
try {
const { port, kill } = await spawnServer(server, {}, runtime);
try {
for (const s of SCENARIOS) {
const runs = await measure(port, s.path, s.method, s.body);
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
}
} finally {
await kill();
}
} catch (error) {
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
// of the run over.
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
}
}
const commit = execSync('git rev-parse --short HEAD').toString().trim(); const commit = execSync('git rev-parse --short HEAD').toString().trim();
const data: RenderData = { const data: RenderData = {
env: { env: {
date: new Date().toISOString().slice(0, 10), // Project time, not the runner's. A benchmark is often driven over ssh against a box that
// keeps UTC, and a run made on the evening of the 22nd then dates itself the 23rd — which
// reads as a day of drift against the commit and the changelog entry beside it.
date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }),
commit, commit,
node: process.version, node: process.version,
os: os.platform(), os: os.platform(),
@@ -160,8 +227,15 @@ async function main(): Promise<void> {
scenarios: scenarioBlocks, scenarios: scenarioBlocks,
stepScaling, stepScaling,
secureCost, secureCost,
runtimes,
}; };
writeFileSync('BENCHMARKS.md', renderMarkdown(data)); // Everything below the marker is written by hand and survives a re-run. The generated tables
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
// history this file exists to keep gets lost a second time.
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
writeFileSync('bench/results.json', JSON.stringify(data, null, 2)); writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
log('wrote BENCHMARKS.md + bench/results.json'); log('wrote BENCHMARKS.md + bench/results.json');
} }
+61
View File
@@ -0,0 +1,61 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+91
View File
@@ -0,0 +1,91 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
type Ctor = new (...args: any[]) => any;
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
// ~8 KB of JSON: well over the 1024-byte compression threshold, and repetitive the way list
// responses are, so the encoders do real work rather than bailing out on incompressible input.
const BIG = Array.from({ length: 120 }, (_, i) => ({ id: i, name: `user ${i}`, email: `user${i}@example.com`, active: i % 2 === 0 }));
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/big') big() { return BIG; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
// Filler routes, so the width of the route table becomes a dimension the harness can see.
//
// Every matcher cost discussed for this file — the specificity scan, the per-candidate
// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate
// routes a request has to walk past. At the six routes the cross-framework table uses, all of them
// measure as noise, which says nothing about them and everything about the instrument. `/users/:id`
// is declared last so a request for it pays the full scan.
function fillerRoutes(count: number): Ctor[] {
return Array.from({ length: count }, (_, i) => {
@Route(`/filler${i}`)
class Filler {
@Get('/:a/:b') ab(@param('a') a: string) {
return { a };
}
}
return Filler as Ctor;
});
}
const EXTRA = Number(process.env.GT_ROUTES ?? 0);
@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
// Only passed when asked for, so the file still boots against a revision without compression.
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
...(process.env.GT_COMPRESS === '1' ? { compression: true } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+1 -1
View File
@@ -30,5 +30,5 @@ class Bench {
class BenchModule {} class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false }); const app = createApp({ modules: [BenchModule], security: false });
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' }); const server = await serveBun(app, { port: 0, hostname: '0.0.0.0' });
console.log(`READY ${server.port}`); console.log(`READY ${server.port}`);
+1 -1
View File
@@ -30,4 +30,4 @@ class Bench {
class BenchModule {} class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false }); const app = createApp({ modules: [BenchModule], security: false });
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) }); await serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
+47
View File
@@ -0,0 +1,47 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
// Same BenchModule as green-tea.ts, but loaded from `dist/` rather than `src/`.
//
// The runtimes table exists to vary the runtime. The Deno and Bun servers import the built bundle
// because that is the only form those runtimes can load here, so a Node row reading `src/` through
// tsx would vary the load form at the same time and the table would answer neither question.
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/0') steps0() { return { hello: 'world' }; }
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
async function main(): Promise<void> {
const server = await app.listen(0);
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
console.log(`READY ${(server.address() as { port: number }).port}`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+10 -1
View File
@@ -1,5 +1,14 @@
{ {
"extends": "../tsconfig.json", "extends": "../tsconfig.json",
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true }, "compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true,
// The bench servers are ES modules, run by tsx, Deno and Bun rather than by the CommonJS build
// the root config describes. `serveDeno`/`serveBun` became async in 26.9.0-beta.2, so two of
// them now open with a top-level `await`, which `module: commonjs` rejects outright.
"module": "es2022",
"moduleResolution": "bundler"
},
"include": ["."] "include": ["."]
} }
+15
View File
@@ -1,4 +1,19 @@
{ {
"name": "@green-tea/core",
"version": "26.9.0-beta.2",
"license": "MIT",
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
// `@green-tea/core/bun` has to work whichever registry the reader installed from.
"exports": {
".": "./src/index.ts",
"./deno": "./src/deno.ts",
"./bun": "./src/bun.ts",
"./edge": "./src/edge.ts"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
},
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
Generated
+8 -4
View File
@@ -27,7 +27,7 @@
"npm:@types/autocannon@^7.12.7", "npm:@types/autocannon@^7.12.7",
"npm:@types/busboy@^1.5.4", "npm:@types/busboy@^1.5.4",
"npm:@types/express@^5.0.6", "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:@types/ws@^8.18.1",
"npm:autocannon@8", "npm:autocannon@8",
"npm:busboy@^1.6.0", "npm:busboy@^1.6.0",
@@ -35,7 +35,7 @@
"npm:esbuild@0.27.2", "npm:esbuild@0.27.2",
"npm:eslint@^9.39.5", "npm:eslint@^9.39.5",
"npm:express@^5.2.1", "npm:express@^5.2.1",
"npm:fastify@^5.11.0", "npm:fastify@^5.12.5",
"npm:graphql@^16.9.0", "npm:graphql@^16.9.0",
"npm:miniflare@^4.20260730.0", "npm:miniflare@^4.20260730.0",
"npm:prettier@^3.9.6", "npm:prettier@^3.9.6",
@@ -46,7 +46,7 @@
"npm:typescript-eslint@^8.65.0", "npm:typescript-eslint@^8.65.0",
"npm:typescript@^5.5.0", "npm:typescript@^5.5.0",
"npm:vite@^6.4.3", "npm:vite@^6.4.3",
"npm:vitest@^3.2.7", "npm:vitest@^4.1.11",
"npm:ws@^8.21.1" "npm:ws@^8.21.1"
], ],
"overrides": { "overrides": {
@@ -55,7 +55,11 @@
"hyperid": { "hyperid": {
"uuid": "11.1.1" "uuid": "11.1.1"
} }
} },
"undici": "7.30.1",
"sharp": "0.35.5",
"fastify": "$fastify",
"multer": "2.5.0"
} }
} }
} }
@@ -1,170 +0,0 @@
# Router correctness and security beta design
**Date:** 2026-08-02
**Target:** `26.8.0-beta.0`
**Status:** Approved
## Goal
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
## Scope
This change includes:
- first-class `HEAD` and `OPTIONS` routes;
- automatic `HEAD` fallback to `GET`;
- automatic bare `OPTIONS` responses;
- correct and deterministic `Allow` headers;
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
- route-pattern validation at boot;
- safe parameter constraints such as `:id(\d+)`;
- malformed URI handling as a client error;
- duplicate and ambiguous route detection;
- OpenAPI projection of constrained parameters;
- dependency remediation for the root package and `website/`;
- public documentation and changelog updates;
- the `26.8.0-beta.0` package-version bump.
This change excludes:
- a radix-tree matcher;
- arbitrary, unrestricted regular expressions;
- manual publication, npm tags, or registry mutations;
- mesh discovery, load balancing, and failover.
## Route semantics
### Path normalization
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
### Methods
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
### Pattern validation
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
- a catch-all outside the final segment;
- empty parameter or catch-all names;
- repeated parameter names in one pattern;
- repeated internal slashes in declarations;
- malformed constraints;
- duplicate routes with the same method and effective pattern;
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
Errors name the method, pattern, controller origin, and conflict when applicable.
### Segment constraints
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
Specificity remains deterministic:
1. static segment;
2. constrained parameter;
3. unconstrained parameter;
4. catch-all.
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
## Architecture
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
## Error behavior
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
## Dependency remediation
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
The root update will prefer the smallest supported versions that close each advisory:
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
- Miniflare moves to its current compatible patch with fixed Sharp;
- Fastify and compatible toolchain packages receive current patch/minor updates;
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
## Documentation
The change updates:
- the README routing section and roadmap;
- the Routing guide;
- the Decorators reference;
- the OpenAPI guide where constrained parameters affect output;
- the CHANGELOG and package version;
- the Starlight 404 configuration that currently emits a build warning.
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
## Verification
The implementation adds unit and integration coverage for:
- explicit and implicit `HEAD`;
- body suppression and header preservation;
- explicit and automatic `OPTIONS`;
- CORS-preflight precedence;
- deterministic `Allow` values;
- trailing slash equivalence and double-slash rejection;
- invalid percent encoding;
- route-declaration failures;
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
- OpenAPI path and `schema.pattern` output;
- Node and Fetch parity;
- mesh method serialization where relevant.
The release gate runs:
- root and website audits with zero known vulnerabilities;
- the runtime-only root audit separately;
- Node tests, typecheck, lint, format, complexity, and build;
- Deno, Bun, and Edge suites when their runtimes are available;
- documentation build without the current 404 warning;
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
- `npm pack --dry-run` to inspect the published artifact.
## CI and publication flow
Gitea remains the source of the release flow:
1. CI runs on `develop` and `main`.
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
4. A promoted `v*` tag triggers GitHub's `release.yml`.
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
@@ -1,679 +0,0 @@
# Router Security Beta Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
---
### Task 1: Compile and validate route patterns
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/types.ts`
- Test: `test/router.test.ts`
**Step 1: Write failing compiler tests**
Add tests that establish the supported grammar and precedence:
```typescript
describe('compilePattern', () => {
it('compiles constrained params and gives them precedence over plain params', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
```
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
**Step 2: Run the focused test and confirm RED**
Run:
```bash
npx vitest run test/router.test.ts
```
Expected: FAIL because `compilePattern` and constrained matching do not exist.
**Step 3: Implement the compiled representation**
In `src/http/router.ts`, add:
```typescript
type CompiledSegment =
| { kind: 'static'; value: string }
| { kind: 'param'; name: string; constraint?: RegExp }
| { kind: 'catchAll'; name: string };
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
catchAll: boolean;
}
```
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
**Step 4: Run tests and confirm GREEN**
Run:
```bash
npx vitest run test/router.test.ts
npm run typecheck
```
Expected: all router tests pass and TypeScript reports no errors.
**Step 5: Commit**
```bash
git add src/http/router.ts src/http/types.ts test/router.test.ts
git commit -s -m "feat(router): compile safe constrained patterns"
```
### Task 2: Validate request paths and route-table ambiguity
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/app/index.ts`
- Modify: `src/app/types.ts`
- Test: `test/router.test.ts`
- Test: `test/app.test.ts`
**Step 1: Write failing path-policy tests**
Add router tests for the approved normalization:
```typescript
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
```
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
```typescript
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
```
Cover the same path under different methods as valid.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/app.test.ts
```
Expected: FAIL because normalization and ambiguity checks are absent.
**Step 3: Implement request normalization**
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
**Step 4: Implement route-table validation**
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
**Step 5: Run focused and mesh tests**
```bash
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
npm run typecheck
```
Expected: all selected tests pass.
**Step 6: Commit**
```bash
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
git commit -s -m "fix(router): reject invalid and ambiguous paths"
```
### Task 3: Add HEAD and OPTIONS to the public decorator API
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/metadata.ts`
- Modify: `src/index.ts`
- Modify: `src/signals.ts`
- Test: `test/metadata.test.ts`
- Test: `test/smoke.test.ts`
**Step 1: Write failing decorator tests**
```typescript
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
```
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts
```
Expected: FAIL because the exports do not exist.
**Step 3: Implement decorators and messages**
Extend `HttpMethod`:
```typescript
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
```
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
```
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/core.ts`
- Modify: `src/http/web.ts`
- Modify: `src/http/server.ts`
- Test: `test/router.test.ts`
- Test: `test/http.test.ts`
- Test: `test/fetch.test.ts`
- Test: `test/parity.test.ts`
- Test: `test/transport-security.test.ts`
**Step 1: Write failing method-semantics tests**
Cover these cases in both Node and `app.fetch`:
```typescript
// Explicit HEAD wins.
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
// Streaming GET does not become implicit HEAD.
// Explicit OPTIONS wins.
// Automatic OPTIONS returns 204 and deterministic Allow.
// GET implies HEAD; every existing path implies OPTIONS.
// CORS preflight still runs before explicit/automatic OPTIONS.
// Double slash and malformed encoding return 400 with security headers.
```
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
```
Expected: new assertions fail under the current 405 behavior.
**Step 3: Implement method resolution**
In `src/http/router.ts`, add a stable method order and helpers:
```typescript
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
```
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
**Step 4: Implement core outcomes**
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
**Step 5: Align body acquisition in both adapters**
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
**Step 6: Run focused tests and confirm GREEN**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
npm run typecheck
```
Expected: all selected tests pass with Node/Fetch parity.
**Step 7: Commit**
```bash
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
```
### Task 5: Project constraints into OpenAPI and introspection
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/openapi.ts`
- Modify: `src/app/introspect.ts`
- Test: `test/openapi.test.ts`
- Test: `test/graph-viz.test.ts`
**Step 1: Write failing OpenAPI tests**
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
```typescript
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
);
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
```
Assert that automatic HEAD/OPTIONS operations are not invented.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
```
Expected: constrained template parsing or schema assertions fail.
**Step 3: Implement projection**
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
git commit -s -m "feat(openapi): document constrained route params"
```
### Task 6: Remove root and website dependency advisories
**Skills:** `@security-review`
**Files:**
- Modify: `package.json`
- Modify: `package-lock.json`
- Modify: `website/package.json`
- Modify: `website/package-lock.json`
- Test: `bench/servers/nestjs-express.ts`
- Test: `bench/servers/nestjs-fastify.ts`
**Step 1: Record the failing audit baseline**
```bash
npm audit
npm --prefix website audit
npm audit --omit=dev
```
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
**Step 2: Apply supported direct updates**
Update root dependencies with explicit commands so the manifests and lockfile agree:
```bash
npm install --save-dev vitest@^3.2.6 \
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
fastify@^5.11.0 miniflare@^4.20260730.0 \
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
```
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
```json
{
"overrides": {
"@nestjs/platform-fastify": {
"find-my-way": "9.7.0"
},
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
}
```
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
**Step 4: Prove compatibility before accepting overrides**
```bash
npm run typecheck
npm test
npm run bench
```
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
**Step 5: Verify clean audits**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
```
Expected: all three commands exit 0 with zero vulnerabilities.
**Step 6: Commit**
```bash
git add package.json package-lock.json website/package.json website/package-lock.json
git commit -s -m "chore(deps): remediate security advisories"
```
### Task 7: Add security and documentation gates to CI
**Skills:** `@security-review`
**Files:**
- Modify: `.github/workflows/ci.yml`
- Modify: `.github/workflows/release.yml`
**Step 1: Define the expected gates**
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
**Step 2: Update CI**
Add these steps after the root `npm ci`:
```yaml
- run: npm audit
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
```
Keep lint, format, complexity, typecheck, test, and build unchanged.
**Step 3: Update the GitHub release gate**
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
- Gitea `main` → Verdaccio `stg`;
- Gitea `main` and `v*` tags → GitHub;
- GitHub `v*` → npm OIDC release.
**Step 4: Validate workflow syntax and diff**
```bash
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
git diff --check
```
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
**Step 5: Commit**
```bash
git add .github/workflows/ci.yml .github/workflows/release.yml
git commit -s -m "ci: gate releases on clean dependency audits"
```
### Task 8: Audit and align the complete website documentation
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Review: every page under `website/src/content/docs/`
- Modify: `website/src/content/docs/guides/routing.md`
- Modify: `website/src/content/docs/reference/decorators.md`
- Modify: `website/src/content/docs/guides/openapi.md`
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
- Create: `website/src/content/docs/404.md`
**Step 1: Build a code-backed website documentation inventory**
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
Do not change a claim from memory. Each correction must be supported by code or a passing test.
**Step 2: Update routing documentation from the verified behavior**
Document:
- `@Head` and `@Options`;
- explicit-route priority and automatic fallbacks;
- canonical `Allow` behavior;
- `/path` equals `/path/`;
- `//` and malformed encoding return `400`;
- catch-all must be final;
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
- the matcher remains linear and a radix tree remains deferred.
Remove the current statement that bare OPTIONS returns 405.
**Step 3: Align cross-cutting website references**
At minimum, verify and correct:
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
- mesh route-conflict wording after effective-pattern normalization;
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
- navigation/frontmatter descriptions that still advertise the old router surface.
Keep intentional historical or roadmap statements only when they remain true.
**Step 4: Fix the Starlight 404 warning**
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
**Step 5: Validate the whole website documentation tree**
```bash
npm run docs:build
npm --prefix website audit
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
rg -n '\]\(/docs/' website/src/content/docs
git diff --check
```
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
**Step 6: Commit**
```bash
git add website/src/content/docs
git commit -s -m "docs(website): align guides with router behavior"
```
### Task 9: Align package documentation and prepare the August beta
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Modify: `README.md`
- Modify: `CHANGELOG.md`
- Modify: `src/index.ts`
- Modify: `package.json`
- Modify: `package-lock.json`
**Step 1: Align the package-facing documentation**
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
**Step 2: Bump the beta version consistently**
Run:
```bash
npm version 26.8.0-beta.0 --no-git-tag-version
```
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
**Step 3: Verify docs and version consistency**
```bash
npm run docs:build
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
git diff --check
```
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
**Step 4: Commit**
```bash
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
git commit -s -m "docs: document router completeness for beta"
```
### Task 10: Run the complete release-candidate verification
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
**Files:**
- Modify only if a verification failure reveals an in-scope defect.
**Step 1: Run static and Node gates**
```bash
npm run lint
npm run format:check
npm run complexity:check
npm run typecheck
npm run typecheck:bench
npm test
npm run build
```
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
**Step 2: Run multi-runtime gates**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
**Step 3: Run security, docs, and benchmark gates**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
npm run docs:build
npm run bench
```
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
**Step 4: Inspect the publish artifact without publishing**
```bash
npm pack --dry-run
```
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
**Step 5: Review branch and workflow boundaries**
```bash
git status --short --branch
git log --oneline --decorate develop..HEAD
git diff --check develop...HEAD
git diff --stat develop...HEAD
```
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
**Step 6: Commit any verification-only repair**
Only if Step 1–5 exposed an in-scope defect:
```bash
git add <exact repaired files>
git commit -s -m "fix: address beta verification findings"
```
Re-run the failed gate and the complete related suite after any repair.
+8
View File
@@ -23,4 +23,12 @@ export default tseslint.config(
], ],
}, },
}, },
{
// Nothing in core writes to console directly — every diagnostic goes through the injectable
// `Logger`, or an application cannot redirect it. This is the rule form of a check that was
// otherwise a `grep` somebody has to remember to run.
files: ['src/**/*.ts'],
ignores: ['src/logger.ts'], // the default logger *is* the console sink; that is its whole job
rules: { 'no-console': 'error' },
},
); );
+14 -7
View File
@@ -1,11 +1,18 @@
````markdown # green-tea examples
# green-tea example
Each file is a runnable app. Run one with `tsx`, which is already a dev dependency:
```bash ```bash
npx ts-node example/server.ts # or: npm run build && node dist/example/server.js npx tsx example/server.ts # the tour, below
curl -H 'x-token: u1' http://localhost:3000/api/users/9 npx tsx example/crud.ts # a CRUD API over an in-memory store, on :3300
npx tsx example/chat.ts # WebSocket rooms, on ws://localhost:4100/chat/:room?token=...
npx tsx example/graphql.ts # GraphQL queries and subscriptions over SSE, on :4200/graphql
``` ```
Demonstrates: typed context contract, graph-derived order, `app.inspect()`, `server.ts` demonstrates the typed context contract, graph-derived order, `app.inspect()`, a
and a logger plugin that observes the bus without touching the chain. logger plugin that observes the bus without touching the chain, streams, and a mesh teapot and
```` teacup. Try it with:
```bash
curl -H 'x-token: u1' http://localhost:3000/api/users/9
```
+10 -6
View File
@@ -31,8 +31,11 @@ class UserController {
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] }) @Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {} class ApiModule {}
const logger: Plugin = (api) => { const logger: Plugin = {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`)); name: 'step-logger',
mount(api) {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
},
}; };
export const app = createApp({ modules: [ApiModule], plugins: [logger] }); export const app = createApp({ modules: [ApiModule], plugins: [logger] });
@@ -75,9 +78,9 @@ if (require.main === module) {
// ── Mesh Demo (teapot / teacup) ─────────────────────────────────────────── // ── Mesh Demo (teapot / teacup) ───────────────────────────────────────────
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class ConfigProvider { class ConfigStep {
provide() { run() {
return { config: { env: 'demo' } }; return { config: { env: 'demo' } };
} }
} }
@@ -98,7 +101,7 @@ class PingController {
} }
} }
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] }) @Module({ mountpoint: '/mesh', steps: [ConfigStep, AuthStep], controllers: [PingController] })
class TeapotModule {} class TeapotModule {}
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } }); export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
@@ -119,6 +122,7 @@ if (require.main === module) {
console.log('teapot on http://localhost:3002'); console.log('teapot on http://localhost:3002');
const teacupApp = createApp({ const teacupApp = createApp({
modules: [TeacupModule], modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] }, mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] },
}); });
teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003')); teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003'));
+391 -541
View File
File diff suppressed because it is too large. Load diff
+18 -12
View File
@@ -1,15 +1,16 @@
{ {
"name": "@green-tea/core", "name": "@green-tea/core",
"version": "26.8.0-beta.0", "version": "26.9.0-beta.2",
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.", "description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
"license": "MIT", "license": "MIT",
"author": "green-tea contributors", "author": "green-tea contributors <projects@expressive-tea.io>",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea.git" "url": "git+https://github.com/Expressive-Tea/green-tea.git"
}, },
"bugs": { "bugs": {
"url": "https://github.com/Expressive-Tea/green-tea/issues" "url": "https://github.com/Expressive-Tea/green-tea/issues",
"email": "projects@expressive-tea.io"
}, },
"homepage": "https://green-tea.expressive-tea.io/docs/", "homepage": "https://green-tea.expressive-tea.io/docs/",
"keywords": [ "keywords": [
@@ -25,7 +26,7 @@
"node" "node"
], ],
"engines": { "engines": {
"node": ">=18" "node": ">=22"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@@ -89,19 +90,21 @@
"test:dev": "vitest", "test:dev": "vitest",
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/", "test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/", "test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts", "test:edge": "tsx test/edge/run.ts && tsx test/edge/compression.ts && npm run build && tsx test/edge/dist.ts",
"test:all": "npm test && npm run test:deno && npm run test:bun && npm run test:edge && deno publish --dry-run --allow-dirty",
"typecheck": "tsc --noEmit -p tsconfig.json", "typecheck": "tsc --noEmit -p tsconfig.json",
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
"lint": "eslint src", "lint": "eslint src",
"lint:fix": "eslint src --fix", "lint:fix": "eslint src --fix",
"format": "prettier --write \"src/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"", "format:check": "prettier --check \"src/**/*.ts\"",
"docs:dev": "npm --prefix website run dev",
"docs:build": "npm --prefix website run build",
"complexity": "ccts src", "complexity": "ccts src",
"complexity:check": "node scripts/check-complexity.mjs", "complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25", "complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts", "bench": "tsx bench/run.ts",
"bench:compare": "tsx bench/compare.ts",
"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", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true" "prepare": "git config core.hooksPath .githooks || true"
}, },
@@ -127,7 +130,10 @@
"uuid": "11.1.1" "uuid": "11.1.1"
} }
}, },
"undici": "7.29.0" "undici": "7.30.1",
"sharp": "0.35.5",
"fastify": "$fastify",
"multer": "2.5.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.5", "@eslint/js": "^9.39.5",
@@ -139,7 +145,7 @@
"@types/autocannon": "^7.12.7", "@types/autocannon": "^7.12.7",
"@types/busboy": "^1.5.4", "@types/busboy": "^1.5.4",
"@types/express": "^5.0.6", "@types/express": "^5.0.6",
"@types/node": "^18.19.0", "@types/node": "^22.20.5",
"@types/ws": "^8.18.1", "@types/ws": "^8.18.1",
"autocannon": "^8.0.0", "autocannon": "^8.0.0",
"busboy": "^1.6.0", "busboy": "^1.6.0",
@@ -147,7 +153,7 @@
"eslint": "^9.39.5", "eslint": "^9.39.5",
"esbuild": "0.27.2", "esbuild": "0.27.2",
"express": "^5.2.1", "express": "^5.2.1",
"fastify": "^5.11.0", "fastify": "^5.12.5",
"graphql": "^16.9.0", "graphql": "^16.9.0",
"miniflare": "^4.20260730.0", "miniflare": "^4.20260730.0",
"prettier": "^3.9.6", "prettier": "^3.9.6",
@@ -157,7 +163,7 @@
"typescript": "^5.5.0", "typescript": "^5.5.0",
"typescript-eslint": "^8.65.0", "typescript-eslint": "^8.65.0",
"vite": "^6.4.3", "vite": "^6.4.3",
"vitest": "^3.2.7", "vitest": "^4.1.11",
"ws": "^8.21.1" "ws": "^8.21.1"
} }
} }
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// Prints one version's section of CHANGELOG.md, for a GitHub release body.
//
// Reads the current file rather than the tag's copy on purpose: the changelog is the record, so a
// correction to an old entry should reach the release that describes it.
//
// Usage: node scripts/changelog-section.mjs <version> [tag]
// The optional tag makes relative links absolute — a release body resolves them against the release
// page, not the repository, and pinning to the tag keeps the link on the file as that version had it.
import { readFileSync } from 'node:fs';
const REPO = 'Expressive-Tea/green-tea';
const [version, tag] = process.argv.slice(2);
if (!version) {
console.error('usage: changelog-section.mjs <version> [tag]');
process.exit(2);
}
const lines = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8').split('\n');
const isHeading = (l) => l.startsWith('## [');
// The `[label]: url` block at the bottom of the file belongs to no section. Without this the last
// section swallows it, since nothing else comes after.
const isLinkRef = (l) => /^\[[^\]]+\]:\s+\S/.test(l);
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
if (start === -1) {
console.error(`no section for ${version}. Headings in CHANGELOG.md:\n${lines.filter(isHeading).join('\n')}`);
process.exit(1);
}
const rest = lines.slice(start + 1);
const stop = rest.findIndex((l) => isHeading(l) || isLinkRef(l));
const body = (stop === -1 ? rest : rest.slice(0, stop)).join('\n').trim();
const absolute = tag
? body.replace(/\]\(\.\/([^)\s]+)\)/g, `](https://github.com/${REPO}/blob/${tag}/$1)`)
: body;
console.log(absolute);
+1385 -201
View File
File diff suppressed because it is too large. Load diff
+112 -2
View File
@@ -1,5 +1,7 @@
import type http from 'http'; import type http from 'http';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { TeardownFn } from '../lifecycle';
import type { GraphNode } from '../graph'; import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz'; import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata'; import type { HttpMethod, Transport } from '../metadata';
@@ -35,7 +37,25 @@ export interface Explain {
/** A running application instance with lifecycle, introspection and graph-export methods. */ /** A running application instance with lifecycle, introspection and graph-export methods. */
export interface App { export interface App {
listen(port: number): Promise<http.Server>; listen(port: number): Promise<http.Server>;
close(): Promise<void>; /**
* Drains in-flight work, closes the server and mesh links, then runs teardown, all within
* `timeoutMs` (default `shutdownTimeoutMs`, else 10s).
*
* With `createApp({ health })` on, `/__ready__` answers `503 {"status":"draining"}` from the first
* line of this call, and the listener stays open for `health.drainDelayMs` before draining starts.
* That window is part of `timeoutMs`. On Deno and Bun the same happens in the `close()` that
* `serveDeno()`/`serveBun()` return.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
*
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
* their server, which is why the option is declared once on `createApp` and works on all three.
* Call it yourself only if you serve the app some other way.
*/
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
/** /**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its * Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
@@ -48,6 +68,22 @@ export interface App {
* shares this same memoized step — calling both never resolves the graph twice. * shares this same memoized step — calling both never resolves the graph twice.
*/ */
ready(): Promise<void>; ready(): Promise<void>;
/**
* Boots the providers now, instead of on the first request.
*
* The three serving helpers call it for you: `listen()` before it accepts a connection,
* `serveDeno()` and `serveBun()` before they bind. Calling it by hand is for the paths that have
* no startup of their own — `app.fetch` and `app.upgrade` driven by your own server, where a
* provider that throws fails *every* request, answered by the runtime with a 500 that never
* reaches `onError`, because the boot memo keeps the rejection. Calling this first turns that into
* a startup failure, which is where a bad key or an unreachable database belongs.
*
* Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike
* `ready()`, it does run provider factories.
*
* On workerd there is no startup outside a request, so calling it moves nothing.
*/
boot(): Promise<void>;
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */ /** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
fetch(request: Request): Promise<Response>; fetch(request: Request): Promise<Response>;
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
@@ -62,6 +98,12 @@ export interface App {
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */ /** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
degraded(): string[]; degraded(): string[];
bus: Bus; bus: Bus;
/**
* Where framework diagnostics are written — the one passed to `createApp({ logger })`, or the
* default. Exposed so the Deno and Bun adapters report through the application's logger rather
* than reaching past it to `console`, and so a plugin or a test can read what core would write.
*/
logger: Logger;
} }
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */ /** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
@@ -83,7 +125,12 @@ export interface RoutePlan {
args: ArgSpec[]; args: ArgSpec[];
} }
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */ /**
* Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to.
*
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
* API freeze, so it may change in a minor release.
*/
export interface MeshConfig { export interface MeshConfig {
secret?: string; secret?: string;
teapots?: Array<{ url: string; secret: string }>; teapots?: Array<{ url: string; secret: string }>;
@@ -95,4 +142,67 @@ export interface MeshConfig {
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter. * `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
*/ */
heartbeatMs?: number; heartbeatMs?: number;
/**
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
*
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep.
*
* It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes
* stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives
* up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a
* protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave
* `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed
* `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`.
*/
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/**
* What to do when a returning teapot's manifest no longer exports something the graph was
* validated against at boot (default: `'refuse'`).
*
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
* rather than left implicit so that arriving is additive rather than a change of default.
*
* Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its
* old ones: a route it added is served, one it dropped answers `404` (D15).
*/
onManifestChange?: 'refuse';
/**
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
* so 30s). Attempts use the same backoff as reconnection.
*
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
* has not settled — should not fail a deploy, and this is the grace for that. When the deadline
* passes the teacup warns and starts anyway: every export is a step or a proxied route, so
* nothing needed that link resolved by boot.
*
* Starting is not degrading, though. A teapot that never connected sent no manifest, so none of
* its steps or routes are registered: its routes 404 rather than 503, and a local node that needs
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace.
*
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
* its steps are not, because the graph was validated at boot without them (D15).
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
*/
bootTimeoutMs?: number;
}
/**
* Lifecycle participation for an application that does not want to be a plugin.
*
* Every method is optional, and the shape is an object rather than a single callback so later
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
*/
export interface Hooks {
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
onShutdown?: TeardownFn;
} }
+109 -7
View File
@@ -1,8 +1,17 @@
import { channel } from './channel'; import { channel } from './channel';
import type { Channel } from './channel'; import type { Channel } from './channel';
import type { App } from './app/types'; 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 { beginDrain } from './http/health';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; 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. // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -12,19 +21,38 @@ interface BunServerWebSocket {
send(data: string): number; send(data: string): number;
close(code?: number, reason?: string): void; close(code?: number, reason?: string): void;
terminate?(): void; terminate?(): void;
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
getBufferedAmount?(): number;
} }
interface BunWebSocketHandler { interface BunWebSocketHandler {
maxPayloadLength?: number;
open?(ws: BunServerWebSocket): void; open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void; message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void; close?(ws: BunServerWebSocket, code: number, reason: string): void;
drain?(ws: BunServerWebSocket): void;
error?(ws: BunServerWebSocket, error?: unknown): void; error?(ws: BunServerWebSocket, error?: unknown): void;
} }
interface BunServer { interface BunServer {
port: number; port: number;
stop(closeActiveConnections?: boolean): void; // Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it
// hid the fact that this is awaitable at all.
stop(closeActiveConnections?: boolean): Promise<void>;
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean; upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
requestIP(request: Request): { address: string; family: string; port: number } | null; requestIP(request: Request): { address: string; family: string; port: number } | null;
} }
/**
* What {@link serveBun} hands back: Bun's own server, plus the bounded `close()` that
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Bun,
* because a Bun app is served through `app.fetch` and never through `listen()`.
*/
export interface BunServeResult extends BunServer {
/**
* Drains in-flight requests, then force-closes whatever is left after `timeoutMs` (default:
* 10s). Same meaning as `app.close({ timeoutMs })` on Node.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
}
interface BunServeOptions { interface BunServeOptions {
port?: number; port?: number;
hostname?: string; hostname?: string;
@@ -39,6 +67,13 @@ interface BunConnData {
wsReq: WsRequest; wsReq: WsRequest;
inbound: Channel<unknown>; inbound: Channel<unknown>;
ac: AbortController; 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());
} }
/** /**
@@ -47,32 +82,65 @@ interface BunConnData {
* created during the upgrade and stashed on ws.data — there is nothing here to wire up. * created during the upgrade and stashed on ws.data — there is nothing here to wire up.
*/ */
function bunSocket(ws: BunServerWebSocket): WsSocket { 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 });
} }
/** /**
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level * Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state * websocket handler. The ServerWebSocket only exists in open(), so per-connection state
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade. * (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
* Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy.
*
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
*/ */
export function serveBun(app: App, options?: BunServeShortOptions): BunServer { export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
return Bun.serve({ // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
// failure rather than a 500 on every request.
//
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
// the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README.
await app.boot();
const server = Bun.serve({
...options, ...options,
fetch(request, server) { fetch(request, server) {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const inbound = channel(); const inbound = channel();
const ac = new AbortController(); const ac = new AbortController();
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? ''); 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; if (server.upgrade(request, { data })) return undefined;
return new Response('WebSocket upgrade failed', { status: 400 }); return new Response('WebSocket upgrade failed', { status: 400 });
} }
// The same object goes to `app.fetch`, which is what lets it find the peer again. The server,
// not its answer: `requestIP` runs only if something reads `ctx.ip` (see `peer.ts`).
setPeer(request, server);
return app.fetch(request); return app.fetch(request);
}, },
websocket: { 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) { open(ws) {
const { wsReq } = ws.data as BunConnData; const { wsReq } = ws.data as BunConnData;
@@ -83,16 +151,50 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
inbound.push(decodeMessage(message)); inbound.push(decodeMessage(message));
}, },
drain(ws) {
releaseDrain(ws);
},
close(ws) { close(ws) {
const { inbound, ac } = ws.data as BunConnData; const { inbound, ac } = ws.data as BunConnData;
inbound.close(); inbound.close();
ac.abort(); ac.abort();
releaseDrain(ws);
}, },
error(ws) { error(ws) {
const { inbound, ac } = ws.data as BunConnData; const { inbound, ac } = ws.data as BunConnData;
inbound.fail(new Error('websocket error')); inbound.fail(new Error('websocket error'));
ac.abort(); ac.abort();
releaseDrain(ws);
}, },
}, },
}); });
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.stop(false))
.then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
timeoutMs: ms,
runtime: 'bun',
}),
),
),
});
} }
+158 -3
View File
@@ -1,4 +1,28 @@
/** Names of every lifecycle event the framework emits over the {@link Bus}. */ /**
* Names of every lifecycle event the framework emits over the {@link Bus}.
*
* ### The request pair is a guarantee
*
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
* consumer may open per-request state on the first and close it on the second without checking
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
* does.
*
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
* every response shape so that the next one cannot break it quietly. The alternative — documenting
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
* exactly when an operator is reading it.
*
* ### `request:end` is terminal and universal; the others are additional
*
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
* the only one of these carrying the real status. **Count it, and nothing else.**
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
*/
export type LifecycleEvent = export type LifecycleEvent =
| 'boot:provider:start' | 'boot:provider:start'
| 'boot:provider:ok' | 'boot:provider:ok'
@@ -6,20 +30,136 @@ export type LifecycleEvent =
| 'request:step:enter' | 'request:step:enter'
| 'request:step:leave' | 'request:step:leave'
| 'request:step:error' | 'request:step:error'
// A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately
// *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its
// connection may live for hours, so `request:end` fires at the handler's return and these three
// describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is
// what lets a consumer join the two rather than watch them as unrelated streams of events.
| 'stream:open' | 'stream:open'
| 'stream:close' | 'stream:close'
| 'stream:error' | 'stream:error'
| 'mesh:connect' | 'mesh:connect'
| 'mesh:disconnect' | 'mesh:disconnect'
| 'mesh:rpc:error' | 'mesh:rpc:error'
| 'plugin:mounted'; // A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
// came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry'
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
| 'mesh:routes'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
| 'request:start'
| 'request:end'
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
// also a throw, which is a thing a status alone cannot express.
| 'request:failed'
| 'route:matched'
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
// misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
// no route either, and answers 200. Read the status from the `request:end` that follows.
| 'route:unmatched';
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */ /**
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
* the fields that say which request it belongs to.
*
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
* name, and requiring a shape they cannot fill would only mean inventing values for it.
*
* ### One failed request produces three events
*
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
* All three carry the same `requestId`, and the first implementation anyone writes counts the
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
* outcome.
*
* The division of labour, which is the thing to build against:
*
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
* received. This is the request counter and the latency histogram.
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
* rendered `422` is also a throw. This is a separate error counter, not a second request
* counter.
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
*
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
* the outcome from `request:end` and only the message from `request:failed`.
*/
export interface EventPayload { export interface EventPayload {
/**
* What the event is about, for a human reading a log line.
*
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
* which is bounded by construction.
*/
name: string; name: string;
scope?: string; scope?: string;
error?: unknown; error?: unknown;
durationMs?: number; durationMs?: number;
/** Correlates every event of one request. Adopted from `x-request-id` when a gateway sent one. */
requestId?: string;
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
traceId?: string;
/**
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
*
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
* that follows it: a single series for every path that was never a route, instead of a fallback
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
* starts with `/`.
*/
route?: string;
method?: string;
transport?: string;
/**
* The status the client received. Present on `request:end` always, and on `request:failed`
* except when a custom `onError` renderer threw while producing it — the one case where the
* framework does not know what was sent, and will not guess.
*/
status?: number;
/** `mesh:routes`: the teapot whose routes changed. */
url?: string;
/** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */
added?: string[];
/** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */
removed?: string[];
}
/**
* The subset of {@link EventPayload} that identifies a request, spread into each of its events.
*
* `route` carries the matched pattern rather than the URL that arrived, and that is load-bearing
* rather than cosmetic: a metrics consumer that labels a counter with a concrete path gets one
* label per distinct URL, and unbounded label cardinality takes down the metrics backend rather
* than the application. Handing anyone that shape by default would be the framework's fault.
*/
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
} }
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
@@ -34,6 +174,21 @@ export class Bus {
return () => listenerSet.delete(listener); return () => listenerSet.delete(listener);
} }
/**
* Whether anything is listening to `event` — for skipping the *construction* of a payload nobody
* will read.
*
* Not a micro-optimisation looking for a problem. A correlated payload is built by spreading the
* request's identity into it, and that spread was measured at ~197 ns per request on a two-step
* pipeline — against a ~4.5 µs in-process request, on a path where the overwhelmingly common
* case is an application that subscribes to nothing at all. `emit` cannot help: its argument is
* already built by the time it is called. Only the caller can decline to build it.
*/
hasListeners(event: LifecycleEvent): boolean {
const listenerSet = this.listeners.get(event);
return listenerSet !== undefined && listenerSet.size > 0;
}
/** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */ /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
emit(event: LifecycleEvent, payload: EventPayload): void { emit(event: LifecycleEvent, payload: EventPayload): void {
for (const listener of this.listeners.get(event) ?? []) { for (const listener of this.listeners.get(event) ?? []) {
+45 -2
View File
@@ -14,6 +14,40 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
} }
/**
* Internal: tells a source its consumer has gone, without waiting for it to finish. An async
* generator runs `return()` only once its pending `next()` settles, which for an idle source may be
* never, and a `return()` may also throw or reject. None of that may hold up or break the cleanup
* that calls this (GitHub #40). Not exported from the package.
*/
export function releaseIterator(iterator: AsyncIterator<unknown> | undefined): void {
try {
void Promise.resolve(iterator?.return?.()).catch(() => {});
} catch {
/* a return() that throws synchronously */
}
}
/**
* 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> { interface Sub<T> {
iterator: AsyncIterator<T>; iterator: AsyncIterator<T>;
push(value: T, cap: number): void; push(value: T, cap: number): void;
@@ -84,9 +118,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * 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). * @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 cap = opts.buffer ?? Infinity;
const subs = new Set<Sub<T>>(); const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false; let done = false;
let closedFlag = false; let closedFlag = false;
@@ -117,5 +151,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
subs.add(sub); subs.add(sub);
return sub.iterator; return sub.iterator;
}, },
[CHANNEL_TAP](sink) {
if (done) {
sink.end();
return () => {};
}
subs.add(sink);
return () => subs.delete(sink);
},
}; };
} }
+14 -10
View File
@@ -6,8 +6,8 @@ export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknow
interface Binding { interface Binding {
scope: Scope; scope: Scope;
factory: Factory; factory: Factory;
cached?: unknown; /** The app-scoped value, cached as a promise from the moment the factory starts. */
resolved?: boolean; cached?: Promise<unknown>;
} }
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */ /** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
@@ -30,14 +30,18 @@ export class Container {
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> { async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
const binding = this.bindings.get(token); const binding = this.bindings.get(token);
if (!binding) throw new Error(`unknown token: ${token}`); if (!binding) throw new Error(`unknown token: ${token}`);
if (binding.scope === 'app' && binding.resolved) return binding.cached; if (binding.scope === 'request') return binding.factory(ctx);
const value = await binding.factory(ctx); if (binding.cached) return binding.cached;
if (binding.scope === 'app') { // The pending promise is cached, not the settled value (GitHub #46): a resolve that starts
binding.cached = value; // while the factory is still running must wait for it, or it runs the factory a second time.
binding.resolved = true; // A rejection is not kept — it clears the cache, so the next resolve retries, as it did when
} // only successes were cached. The async wrapper turns a synchronous throw into that rejection.
const pending = (async () => binding.factory(ctx))();
return value; binding.cached = pending;
pending.catch(() => {
if (binding.cached === pending) binding.cached = undefined;
});
return pending;
} }
} }
+150
View File
@@ -0,0 +1,150 @@
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
/**
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
*/
export interface CookieOptions {
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
maxAge?: number;
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
expires?: Date;
/** `Path`. Default `'/'`. */
path?: string;
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
domain?: string;
/**
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
* (for example `secure: !isDev`).
*/
secure?: boolean;
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
httpOnly?: boolean;
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
sameSite?: 'strict' | 'lax' | 'none';
/** `Partitioned` (CHIPS). Requires `secure`. */
partitioned?: boolean;
}
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
// eslint-disable-next-line no-control-regex
const BAD_VALUE = /[\u0000- ;,\u007f]/;
/**
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
* and the other control characters are refused too, because a `;` inside `Path` would start a new
* attribute and change what the cookie means without breaking the header.
*/
// eslint-disable-next-line no-control-regex
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
/**
* Serialises one `Set-Cookie` header value.
*
* Throws, naming the field, rather than producing a header that would split or reshape the
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
*
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
*
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
* element is sent as its own `Set-Cookie` line on every adapter.
*
* @example
* setCookie('session', id, { maxAge: 3600 })
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
*/
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
if (typeof name !== 'string' || !TOKEN.test(name))
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
if (typeof value !== 'string' || BAD_VALUE.test(value))
throw new TypeError(
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
);
const secure = options.secure ?? true;
const sameSite = options.sameSite ?? 'lax';
const parts = [`${name}=${value}`];
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
parts.push(`Max-Age=${options.maxAge}`);
}
if (options.expires !== undefined) {
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
parts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
if (secure) parts.push('Secure');
if (options.httpOnly ?? true) parts.push('HttpOnly');
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
if (sameSite === 'none' && !secure)
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
if (options.partitioned) {
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
parts.push('Partitioned');
}
return parts.join('; ');
}
function attribute(name: string, field: string, value: string): string {
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
throw new TypeError(
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
);
return value;
}
/**
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
*
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
* the header is client state the server did not choose and the request may not even need it.
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
*
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
*/
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
const out: Record<string, string> = Object.create(null);
if (header === undefined) return out;
const raw = Array.isArray(header) ? header.join('; ') : header;
for (const pair of raw.split(';')) {
const eq = pair.indexOf('=');
if (eq === -1) continue;
const key = pair.slice(0, eq).trim();
if (key === '' || key in out) continue;
out[key] = decode(pair.slice(eq + 1).trim());
}
return out;
}
function decode(value: string): string {
if (!value.includes('%')) return value;
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
+85 -4
View File
@@ -1,8 +1,11 @@
import type { App } from './app/types'; import type { App } from './app/types';
import { beginDrain } from './http/health';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; 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) // The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. // Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
interface WebSocket extends EventfulSocket { interface WebSocket extends EventfulSocket {
binaryType: string; binaryType: string;
} }
@@ -22,6 +25,23 @@ interface DenoHttpServer {
finished: Promise<void>; finished: Promise<void>;
shutdown(): Promise<void>; shutdown(): Promise<void>;
} }
/**
* What {@link serveDeno} hands back: Deno's own server, plus the bounded `close()` that
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Deno,
* because a Deno app is served through `app.fetch` and never through `listen()`.
*/
export interface DenoServer extends DenoHttpServer {
/**
* Drains in-flight requests, returning after at most `timeoutMs` (default: 10s).
*
* **The deadline bounds the wait, not the connections** — unlike Node's `app.close()` and Bun's
* `close()`, which force the remainder shut. Deno offers no force-close that composes with a
* drain already under way: aborting the serve signal at that point throws `BadResource` from
* Deno's own listener, uncaught. Whatever is still open when this resolves ends with the process.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
}
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>; type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
declare const Deno: { declare const Deno: {
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer; serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
@@ -31,9 +51,29 @@ declare const Deno: {
/** /**
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. * Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
* WebSocket messages flow through app.upgrade over the shared neutral core. * WebSocket messages flow through app.upgrade over the shared neutral core.
* Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy.
*
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
*/ */
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { export async function serveDeno(app: App, options?: DenoServeOptions): Promise<DenoServer> {
return Deno.serve(options ?? {}, (request, info) => { // The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
// failure rather than a 500 on every request.
//
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
// the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README.
await app.boot();
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to
// own one to offer a deadline at all. A caller-supplied signal still works and still aborts the
// server — it is chained into ours rather than replaced, so neither party loses its control.
const ac = new AbortController();
options?.signal?.addEventListener('abort', () => ac.abort(), { once: true });
const server = Deno.serve({ ...options, signal: ac.signal }, (request, info) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
// Deno invalidates request connection metadata as soon as the upgrade is accepted. // Deno invalidates request connection metadata as soon as the upgrade is accepted.
const wsRequest = toWsRequest(request, info.remoteAddr.hostname); const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
@@ -44,6 +84,47 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer
return response; 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); return app.fetch(request);
}); });
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.shutdown())
.then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
// surfaces uncaught — not catchable at this call site, and fatal under `deno test`.
// Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot
// escalate from graceful to forced the way Node's closeAllConnections() and Bun's
// stop(true) can, and the deadline here bounds how long `close()` waits, not when the
// connections die. Exiting the process after `close()` resolves is what ends them.
() => {},
closeOptions.timeoutMs ?? 10_000,
(ms) =>
app.logger.warn(
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
'a server that is already draining, so remaining connections end when the process does.',
{ timeoutMs: ms, runtime: 'deno' },
),
),
),
});
} }
+29 -1
View File
@@ -1,5 +1,7 @@
import type { App } from './app/types'; import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { setProxyClient } from './http/peer';
import { MARK_EDGE } from './http/compression';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures. // Declares only what we call; mirrors the real workerd signatures.
@@ -15,15 +17,29 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair. * Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` * Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response. * compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*
* **`compression` never encodes here.** Cloudflare compresses in front of the Worker, so core sets
* only `Vary: Accept-Encoding`; wrapping the app in `edgeHandler` marks it as edge explicitly.
*/ */
export function edgeHandler( export function edgeHandler(
app: App, app: App,
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> { ): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
return (request, _env, ctx) => { return (request, _env, ctx) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept(); server.accept();
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? ''); // No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
const wsReq = toWsRequest(request, '');
recordClient(wsReq, request);
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server)); const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
if (ctx?.waitUntil) ctx.waitUntil(lifecycle); if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle; else void lifecycle;
@@ -31,6 +47,18 @@ export function edgeHandler(
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket }); return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
} }
recordClient(request, request);
return app.fetch(request); return app.fetch(request);
}; };
} }
/**
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
* option; HTTP and WebSocket both go through here and through the same check on the app side.
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
* and an untrusted header is whatever the client chose to send.
*/
function recordClient(source: object, request: Request): void {
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
}
+100 -2
View File
@@ -11,10 +11,106 @@ export interface StreamEncoder {
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
// being recognised across them would silently degrade back to an id-less `data:` frame.
const SSE_EVENT = Symbol.for('green-tea.sse-event');
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
export interface SseFields {
/**
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
* `@header('last-event-id')` and resume from there.
*/
id?: string;
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
event?: string;
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
retry?: number;
}
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
export interface SseEvent<T = unknown> extends SseFields {
readonly [SSE_EVENT]: true;
data: T;
}
/** Type guard: true when a stream item was built by {@link sse}. */
export function isSseEvent(item: unknown): item is SseEvent {
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
}
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
function assertFieldSafe(field: string, value: string): void {
if (!/[\r\n\0]/.test(value)) return;
throw new Error(
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
'one would end the field and let the rest of the value be read as further SSE fields. ' +
`Received ${JSON.stringify(value)}.`,
);
}
/**
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
* instead of a bare `data:` frame.
*
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
* marker in both directions and stores nothing — a source that can resume, resumes; one that
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
*
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
*
* @example
* ```ts
* @Sse('/feed')
* feed(@header('last-event-id') from: string) {
* return (async function* () {
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
* })();
* }
* ```
*/
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
// reconnection delay at the default rather than at the value the app asked for.
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
}
return { [SSE_EVENT]: true, data, ...fields };
}
/**
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
*/
function sseFrame(item: unknown): string {
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
let frame = '';
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
if (item.event !== undefined) frame += `event: ${item.event}\n`;
if (item.id !== undefined) frame += `id: ${item.id}\n`;
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
}
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */ /** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = { export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }, headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
encode: (item) => `data: ${JSON.stringify(item)}\n\n`, encode: sseFrame,
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`, encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n', ping: () => ': ping\n\n',
}; };
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
/** Newline-delimited JSON encoder: one JSON object per line. */ /** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = { export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' }, headers: { 'content-type': 'application/x-ndjson' },
encode: (item) => `${JSON.stringify(item)}\n`, // Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`, encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
}; };
+79 -5
View File
@@ -42,16 +42,61 @@ export interface GraphNode {
origin: string; origin: string;
} }
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ /**
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { * Maps every token to the one node that produces it; throws when a second node provides a token.
*
* One producer per token, across modules, plugins, mesh steps and built-ins alike (GitHub #35, D9).
* This used to be `producedBy.set(key, node)`, last one wins: plugin nodes are registered after
* module nodes, so a plugin's `scope.add` that provided `user` silently replaced the app's own `user`
* for every route that needed it. Checking here, on the whole graph, rather than at each place a node
* is registered, is what covers every path — current and future — and makes the built-in tokens
* (`logger`, `rooms`, `events`) safe by rule instead of by registration order.
*/
function producers(nodes: GraphNode[]): Map<string, GraphNode> {
const producedBy = new Map<string, GraphNode>(); const producedBy = new Map<string, GraphNode>();
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
for (const node of nodes) {
for (const key of node.provides) {
const prior = producedBy.get(key);
if (prior && prior !== node) {
throw new Error(
`token '${key}' is provided twice: by '${prior.name}' (${prior.origin}) and by '${node.name}' (${node.origin}) — ` +
'a token has exactly one producer; rename one of them, or use `overrides` to replace a runner',
);
}
producedBy.set(key, node);
}
}
return producedBy;
}
/**
* Orders nodes so every dependency precedes its dependents; throws on a token with two producers,
* missing keys or cycles.
*/
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
const producedBy = producers(nodes);
// validate dependencies exist // validate dependencies exist
for (const node of nodes) { for (const node of nodes) {
for (const key of node.needs) { for (const key of node.needs) {
if (!seedKeys.includes(key) && !producedBy.has(key)) { if (seedKeys.includes(key)) continue;
throw new Error(`missing dependency: ${key} needed by ${node.name}`); const producer = producedBy.get(key);
if (!producer) throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
// A node that needs its own token is a cycle of one (GitHub #43): it would read a value nobody
// wrote yet. `producers` already allows one producer per token, so no other node can supply
// it; only a seed makes the need real, and the seed case continued above. Same wording as the
// cycle check below, so both read as the one error they are.
if (producer === node) {
throw new Error(
`cycle detected: ${node.name} -> ${node.name} (it needs '${key}', which only it provides)${note}. ` +
`Remove '${key}' from its needs, or move the work that produces '${key}' into a step it needs.`,
);
} }
} }
} }
@@ -78,6 +123,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
return ordered; return ordered;
} }
/**
* Groups an already topo-sorted list into dependency levels: nothing in a level can constrain
* anything else in it, and a level depends only on the levels before it — so a level can run
* concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain
* nothing and are ignored.
*/
export function topoLevels(ordered: GraphNode[]): GraphNode[][] {
const producedBy = new Map<string, GraphNode>();
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
const depthOf = new Map<GraphNode, number>();
const levels: GraphNode[][] = [];
// One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's
// needs already has its depth by the time the node is reached.
for (const node of ordered) {
let depth = 0;
for (const key of node.needs) {
const producer = producedBy.get(key);
if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1);
}
depthOf.set(node, depth);
(levels[depth] ??= []).push(node);
}
return levels;
}
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */ /** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
const producedBy = new Map<string, GraphNode>(); const producedBy = new Map<string, GraphNode>();
+164
View File
@@ -0,0 +1,164 @@
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
// the caller as a {@link BodyReader}.
import { HttpError, isHttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure {
fail: { status: number; headers: Record<string, string | string[]>; body: string };
}
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
export type MaybePromise<T> = T | Promise<T>;
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
return value instanceof Promise;
}
/**
* Reads the raw request body, enforcing `limit`.
*
* 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.
* That header means nothing on the fetch side, and is a forbidden response header on some
* runtimes, so the adapter that needs it is the one that attaches it.
*
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
* reader can be built **once per server** instead of once per request: a closure capturing the
* request measured at 250 ns per request together with the error-context object it captured —
* more than the duplicate route resolution this whole indirection removes.
*/
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 {
// The numeric test first: nearly every request is under the limit, so the shape check below runs
// only for the rare one that would be refused.
return contentLength != null && Number(contentLength) > limit && /^\d+$/.test(contentLength);
}
/**
* The media type of a Content-Type value: the part before any parameters, trimmed and lowercased,
* since media types are case-insensitive (RFC 9110 §8.3.1). Matching a substring of the raw header
* instead let a parameter choose the parser: `text/plain; x=application/json` was parsed as JSON.
*/
function mediaType(contentType: string): string {
const semi = contentType.indexOf(';');
return (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
}
/** 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 };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
maxFieldBytes?: number,
): Promise<ParseResult> {
const type = mediaType(contentType);
// `+json` is the structured-syntax suffix for JSON (RFC 6839): `application/problem+json`,
// `application/vnd.api+json` and `application/json-patch+json` are JSON documents too.
if (buf !== undefined && (type === 'application/json' || type.endsWith('+json'))) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && type === 'application/x-www-form-urlencoded') {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && type === 'multipart/form-data') {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates, maxFieldBytes }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501) or a field is over the limit (413);
// anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
/**
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
*
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
* character for character, because each adapter had to route the request itself in order to know
* whether to read a body — and so ended up owning every policy that depends on the matched route.
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
* runtimes quietly disagree about limits.
*/
export function acquireBody(
read: BodyReader,
source: unknown,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
const acquired = read(source, limit);
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
// this whole path without a single promise, and an `async` wrapper here would allocate one
// regardless. Same reason `handle()` is not async.
return isPromise(acquired)
? acquired.then((settled) => parseAcquired(settled, limit, matched, opts, req))
: parseAcquired(acquired, limit, matched, opts, req);
}
function parseAcquired(
acquired: { bytes: Buffer | undefined } | BodyFailure,
limit: number,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
if ('fail' in acquired) return acquired;
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
// off the promise path entirely.
if (acquired.bytes === undefined) return { body: undefined };
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
// A field is bounded by the body limit alone. busboy's own 1 MiB default would otherwise cut any
// larger field that `maxBodyBytes` was raised to admit.
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts, limit).then((parsed) =>
'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body },
);
}
+441
View File
@@ -0,0 +1,441 @@
// src/http/compression.ts — response compression (CARD-16, #112, D13 strategy B).
//
// The per-runtime contract, as measured in SPIKE-COMPRESSION.md and SPIKE-COMPRESSION-B.md:
// - Node, Deno, Bun: `node:zlib` only, loaded lazily. Buffered bodies always go through the async
// API: at 32 connections the sync API stalled the event loop for 9–13 ms even below 64 KiB, and
// async gave 4× (Node) to 8× (Bun) the throughput. Streams go through createGzip /
// createBrotliCompress, flushed after every frame, error frame and ping, so each event is
// decodable the moment it arrives. br quality is fixed at 4 (zlib's default 11 stalls 6–33 ms).
// - Deno runs `node:zlib`'s async API on the main thread (2.9.7), so there core compression is
// CPU work on the event loop. That is documented, not worked around: no Deno branch here.
// - Edge (workerd): core never encodes. Cloudflare compresses in front of the Worker, an encoded
// body plus `Content-Encoding` is encoded a second time, and a bundled Worker cannot even
// `require('node:zlib')`. Core sets `Vary` and nothing else.
// - No `CompressionStream` anywhere: it cannot flush, so it would hold SSE frames back.
import { mergeVary } from '../security';
import { nodeRequire } from '../node-require';
import { findHeader } from './conditional';
import type { NeutralOutcome } from './core';
/** A content-coding core can produce. */
export type Encoding = 'br' | 'gzip';
/** The public `createApp({ compression })` object form. */
export interface CompressionOptions {
/** Smallest buffered body, in bytes, worth encoding. Default `1024`. Streams ignore it. */
threshold?: number;
/** Encodings core may produce, in server preference order. Default `['br', 'gzip']`. */
encodings?: Array<'br' | 'gzip'>;
}
/** Resolved, validated configuration. `encode: false` is the edge mode: `Vary` only. */
export interface CompressionConfig {
threshold: number;
encodings: Encoding[];
encode: boolean;
}
/** Fixed brotli quality. See the module comment. */
export const BR_QUALITY = 4;
const KNOWN: readonly Encoding[] = ['br', 'gzip'];
/**
* Marks an app as running on the edge, so core never encodes for it. `edgeHandler` calls it: that
* covers the official adapter whatever the Worker's compat flags, including the case detection
* cannot see (an old compat date without `navigator`, unbundled so `node:zlib` loads). A property
* on the app rather than on the public `App` type, and `Symbol.for` because each tsup entry carries
* its own copy of this module — the same arrangement as `WS_MAX_MESSAGE_BYTES`.
*/
export const MARK_EDGE: unique symbol = Symbol.for('green-tea.mark-edge');
/** The `[MARK_EDGE]` hook for an app: turns encoding off for good. A no-op when compression is off. */
export function edgeMarker(cfg: CompressionConfig | undefined): () => void {
return () => {
if (cfg) cfg.encode = false;
};
}
/**
* Whether this process is a Cloudflare Workers isolate. workerd sets `navigator.userAgent` to
* exactly this string under the `global_navigator` compat flag, on by default since 2022-03-21.
* Detected in `createApp` so `export default { fetch: app.fetch }`, which never passes through
* `edgeHandler`, is covered too.
*/
export function isWorkerd(): boolean {
const nav = (globalThis as { navigator?: { userAgent?: string } }).navigator;
return nav?.userAgent === 'Cloudflare-Workers';
}
interface ZlibStream {
write(chunk: Uint8Array | string): boolean;
flush(kind: number, cb: () => void): void;
end(): void;
destroy(): void;
on(event: string, fn: (...args: never[]) => void): this;
once(event: string, fn: (...args: never[]) => void): this;
pipe<T>(dest: T): T;
}
interface Zlib {
gzip(b: Uint8Array, cb: (e: Error | null, r: Buffer) => void): void;
brotliCompress(b: Uint8Array, o: object, cb: (e: Error | null, r: Buffer) => void): void;
createGzip(): ZlibStream;
createBrotliCompress(o: object): ZlibStream;
constants: Record<string, number>;
}
let zlibModule: Zlib | undefined;
/** Lazy, so the edge bundle never evaluates `node:zlib`. */
const zlib = (): Zlib => (zlibModule ??= nodeRequire<Zlib>('node:zlib'));
/**
* Encode only off workerd, and only where `node:zlib` actually loads. In a bundled Worker
* `nodeRequire` throws, and without this probe every compressible edge response was a 500
* (SPIKE-COMPRESSION-B §6.1). Evaluated once, at `createApp`.
*/
function canEncode(): boolean {
if (isWorkerd()) return false;
try {
return typeof zlib().gzip === 'function';
} catch {
return false;
}
}
/** Validates `createApp({ compression })`. Returns `undefined` when compression is off. */
export function resolveCompression(
option: boolean | CompressionOptions | undefined,
encode: () => boolean = canEncode,
): CompressionConfig | undefined {
if (option === undefined || option === false) return undefined;
if (option !== true && (typeof option !== 'object' || option === null))
throw new TypeError('createApp({ compression }): expected a boolean or { threshold?, encodings? }');
const opts: CompressionOptions = option === true ? {} : option;
const threshold = opts.threshold ?? 1024;
if (!Number.isInteger(threshold) || threshold < 0)
throw new TypeError(
`createApp({ compression }): threshold must be a non-negative integer, got ${String(threshold)}`,
);
const encodings = opts.encodings ?? ['br', 'gzip'];
if (!Array.isArray(encodings) || encodings.length === 0)
throw new TypeError('createApp({ compression }): encodings must be a non-empty array');
for (const e of encodings)
if (!KNOWN.includes(e))
throw new TypeError(`createApp({ compression }): unknown encoding '${String(e)}' — expected 'br' or 'gzip'`);
return { threshold, encodings: [...new Set(encodings)], encode: encode() };
}
/**
* The qvalue grammar of RFC 9110 §12.4.2: `0` with up to three decimals, or `1` with up to three
* zeros. `Number()` alone would admit `2`, `1e0` or `-1`, and a `q=2` would outrank the server's
* preference.
*/
const QVALUE = /^(0(\.\d{0,3})?|1(\.0{0,3})?)$/;
/** `q` of one `Accept-Encoding` member, or 1 when absent. A malformed or out-of-range `q` excludes it. */
function weightOf(params: string[]): number {
for (const param of params) {
const eq = param.indexOf('=');
if (eq !== -1 && param.slice(0, eq).trim().toLowerCase() === 'q') {
const raw = param.slice(eq + 1).trim();
return QVALUE.test(raw) ? Number(raw) : 0;
}
}
return 1;
}
/**
* `Accept-Encoding` negotiation (RFC 9110 §12.5.3). Returns the encoding to use, or `undefined` for
* identity. Highest `q` wins; a tie goes to server preference, the order of `encodings`. `*` covers
* every encoding not named explicitly, and `q=0` excludes. An absent header means identity:
* §12.5.3 allows any coding then, but an absent header is overwhelmingly a client that would not
* decode one.
*/
export function negotiate(accept: string | undefined, encodings: Encoding[]): Encoding | undefined {
if (!accept) return undefined;
const q = new Map<string, number>();
for (const part of accept.split(',')) {
const [rawName, ...params] = part.split(';');
const name = rawName.trim().toLowerCase();
if (name) q.set(name, weightOf(params));
}
let best: Encoding | undefined;
let bestQ = 0;
for (const e of encodings) {
const weight = q.get(e) ?? q.get('*') ?? 0;
if (weight > bestQ) {
best = e;
bestQ = weight;
}
}
return best;
}
const COMPRESSIBLE =
/^\s*(text\/|application\/(json|javascript|xml|wasm|x-ndjson)\s*(;|$)|image\/svg\+xml\s*(;|$)|application\/[^;\s]+\+(json|xml)\s*(;|$))/i;
type Headers = Record<string, string | string[]>;
/**
* Whether the response's representation could vary by `Accept-Encoding` at all. When it cannot —
* already encoded, a range, no or an incompressible type, `no-transform` — core neither encodes
* nor adds `Vary`. A buffered body under the threshold is the same case, decided in
* {@link compressBuffered} once the size is known. Request-side reasons (HEAD, the client's header) do not appear here: those
* responses still get `Vary`, so a shared cache keys them correctly.
*/
function eligible(headers: Headers): boolean {
// One pass over the keys rather than one `read` per header: every response with compression on
// comes through here, and four case-insensitive scans plus two regexes cost ~8% of a small Deno
// request. The first key of each name wins, as `findHeader` would pick it.
let type: string | undefined;
let cacheControl: string | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
const lower = key.toLowerCase();
if (lower === 'content-encoding' || lower === 'content-range') return false;
if (lower === 'content-type') type ??= Array.isArray(value) ? value.join(', ') : value;
else if (lower === 'cache-control') cacheControl ??= Array.isArray(value) ? value.join(', ') : value;
}
if (!type || !compressibleType(type)) return false;
return cacheControl === undefined || !NO_TRANSFORM.test(cacheControl);
}
const NO_TRANSFORM = /(^|[\s,])no-transform\s*(,|$)/i;
// ponytail: a one-entry memo, since an app answers nearly every response with the same type or two;
// a bounded map if a mix of types ever measures.
let lastType: string | undefined;
let lastCompressible = false;
function compressibleType(type: string): boolean {
if (type !== lastType) {
lastType = type;
lastCompressible = COMPRESSIBLE.test(type);
}
return lastCompressible;
}
function withVary(headers: Headers): Headers {
const key = findHeader(headers, 'vary');
const out = { ...headers };
let existing: string | undefined;
if (key !== undefined) {
const value = out[key];
existing = Array.isArray(value) ? value.join(', ') : value;
delete out[key];
}
out.vary = mergeVary(existing, 'Accept-Encoding');
return out;
}
/** Headers for an encoded body: `Vary` merged, `Content-Encoding` set, `Content-Length` dropped (it described the identity body). */
function encodedHeaders(headers: Headers, encoding: Encoding): Headers {
const out = withVary(headers);
const length = findHeader(out, 'content-length');
if (length !== undefined) delete out[length];
out['content-encoding'] = encoding;
return out;
}
const brParams = (size?: number) => {
const c = zlib().constants;
const params: Record<number, number> = { [c.BROTLI_PARAM_QUALITY]: BR_QUALITY };
if (size !== undefined) params[c.BROTLI_PARAM_SIZE_HINT] = size;
return { params };
};
/** Encodes one buffered body with the async zlib API — never the sync one (see the module comment). */
function encodeBody(body: Uint8Array, encoding: Encoding): Promise<Buffer> {
const z = zlib();
return new Promise((resolve, reject) => {
const done = (err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out));
if (encoding === 'br') z.brotliCompress(body, brParams(body.byteLength), done);
else z.gzip(body, done);
});
}
/** A fresh compressing stream plus the flush mode that makes it emit everything written so far. */
function createEncoderStream(encoding: Encoding): { stream: ZlibStream; flushKind: number } {
const z = zlib();
if (encoding === 'br')
return { stream: z.createBrotliCompress(brParams()), flushKind: z.constants.BROTLI_OPERATION_FLUSH };
return { stream: z.createGzip(), flushKind: z.constants.Z_SYNC_FLUSH };
}
/** The request facts compression needs. */
export interface CompressionRequest {
method: string;
headers: Record<string, string | string[] | undefined>;
}
const acceptOf = (req: CompressionRequest): string | undefined => {
const v = req.headers['accept-encoding'];
return Array.isArray(v) ? v.join(', ') : v;
};
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
type Streamed = Extract<NeutralOutcome, { kind: 'stream' }>;
/** Decides a buffered outcome. Returns it untouched, with `Vary` only, or encoded. */
function compressBuffered(
cfg: CompressionConfig,
req: CompressionRequest,
outcome: Buffered,
): Buffered | Promise<Buffered> {
const { status, headers, body } = outcome;
// A 304 carries `Vary` whatever else it has: it usually has no `Content-Type`, so the
// eligibility test would drop it, and a cache needs the same key it stored the 200 under.
if (status === 304) return { ...outcome, headers: withVary(headers) };
if (status === 204 || !eligible(headers)) return outcome;
const vary = (): Buffered => ({ ...outcome, headers: withVary(headers) });
if (status < 200 || req.method === 'HEAD' || !cfg.encode) return vary();
// Under the threshold the body is sent identity whatever the client accepts, so `Accept-Encoding`
// played no part and there is no `Vary` to send (RFC 9110 §12.5.5). A cache that stores this
// response for everyone is right to: every client accepts identity. Skipping it matters on Deno,
// which pays ~10% of a small request for a `Vary` header. Measured without allocating the bytes.
const size = typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
if (size < cfg.threshold) return outcome;
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return vary();
const bytes = typeof body === 'string' ? Buffer.from(body) : body;
return encodeBody(bytes, encoding).then((encoded) => ({
...outcome,
headers: encodedHeaders(headers, encoding),
body: encoded,
}));
}
/** Decides a stream: its headers, and the encoding the adapter applies frame by frame. `threshold` does not apply. */
function compressStream(cfg: CompressionConfig, req: CompressionRequest, outcome: Streamed): Streamed {
if (!eligible(outcome.headers)) return outcome;
if (req.method === 'HEAD' || !cfg.encode) return { ...outcome, headers: withVary(outcome.headers) };
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return { ...outcome, headers: withVary(outcome.headers) };
return { ...outcome, headers: encodedHeaders(outcome.headers, encoding), encoding };
}
/**
* Applies `createApp({ compression })` to an outcome, after `handle()` and before the adapter
* writes it. One function for both adapters, so Node and the fetch runtimes cannot diverge. The
* ETag (CARD-15) was taken in `dispatch` on the identity body and is not touched: it is weak, so
* one tag describes every coding.
*/
export function compressOutcome(
cfg: CompressionConfig | undefined,
req: CompressionRequest,
outcome: NeutralOutcome,
): NeutralOutcome | Promise<NeutralOutcome> {
if (!cfg) return outcome;
return outcome.kind === 'stream' ? compressStream(cfg, req, outcome) : compressBuffered(cfg, req, outcome);
}
/**
* Wraps a web byte stream so every chunk is compressed and flushed on its own: one SSE frame in,
* one decodable compressed chunk out. This is the thing `CompressionStream` cannot do.
*/
export function compressWebStream(source: ReadableStream<Uint8Array>, encoding: Encoding): ReadableStream<Uint8Array> {
const { stream: z, flushKind } = createEncoderStream(encoding);
const reader = source.getReader();
let pending: Uint8Array[] = [];
let failure: unknown;
z.on('data', (c: Uint8Array) => pending.push(c));
// Without a listener a zlib error is an uncaught exception that takes the process down.
z.on('error', (err: unknown) => (failure ??= err));
const take = (): Uint8Array | undefined => {
if (pending.length === 0) return undefined;
const chunk = pending.length === 1 ? pending[0] : Buffer.concat(pending);
pending = [];
return new Uint8Array(chunk.buffer as ArrayBuffer, chunk.byteOffset, chunk.byteLength);
};
return new ReadableStream<Uint8Array>({
async pull(controller) {
const { value, done } = await reader.read();
if (done) {
await new Promise<void>((resolve) => {
z.once('end', resolve);
z.once('error', () => resolve());
z.end();
});
} else {
z.write(value);
await new Promise<void>((resolve) => z.flush(flushKind, resolve));
}
if (failure !== undefined) {
controller.error(failure);
await reader.cancel(failure).catch(() => {});
return;
}
const out = take();
if (out) controller.enqueue(out);
if (done) controller.close();
},
async cancel(reason) {
z.destroy();
await reader.cancel(reason);
},
});
}
/** Where `pipeStream` writes frames: `res` itself, or a flushing compressor piped into it. */
export interface FrameSink {
write(chunk: string | Buffer): boolean;
/** The emitter whose `drain` ends a backpressure wait. */
drains: NodeJS.EventEmitter;
end(): void;
destroy(): void;
}
/** The Node stream path's sink. Without an encoding it is `res`, unchanged. */
export function frameSink(res: NodeJS.WritableStream & { destroy(): void }, encoding?: Encoding): FrameSink {
if (!encoding) return { write: (c) => res.write(c), drains: res, end: () => void res.end(), destroy: () => {} };
const { stream: zs, flushKind } = createEncoderStream(encoding);
zs.on('error', () => res.destroy());
zs.pipe(res);
return {
write(chunk) {
const ok = zs.write(chunk);
// Flushed per frame: the point of an event stream is that each event arrives when it happens.
zs.flush(flushKind, () => {});
return ok;
},
drains: zs as unknown as NodeJS.EventEmitter,
end: () => zs.end(), // `pipe` ends `res` once the compressor has drained
destroy: () => zs.destroy(),
};
}
+121
View File
@@ -0,0 +1,121 @@
// src/http/conditional.ts — ETags and conditional GET (RFC 9110 §8.8.3, §13.1.2, §13.1.3, §15.4.5).
type HeaderBag = Record<string, string | string[] | undefined>;
/** The first value of a request header, or `undefined`. */
function single(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value.join(', ') : value;
}
/**
* Splits an `If-None-Match` list on the commas that sit outside quotes. An entity-tag may legally
* contain a comma inside its quotes (`"a,b"`), so a plain `split(',')` would cut one tag in two.
*/
function splitTags(header: string): string[] {
const tags: string[] = [];
let start = 0;
let quoted = false;
for (let i = 0; i < header.length; i++) {
const ch = header[i];
if (ch === '"') quoted = !quoted;
else if (ch === ',' && !quoted) {
tags.push(header.slice(start, i).trim());
start = i + 1;
}
}
tags.push(header.slice(start).trim());
return tags.filter(Boolean);
}
/** The opaque part of an entity-tag: `W/"x"` and `"x"` both become `"x"` (weak comparison). */
const opaque = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
/**
* Whether `If-None-Match` matches `etag` under the weak comparison GET and HEAD use
* (RFC 9110 §13.1.2): `W/"x"` matches `"x"`, and `*` matches any current representation.
*/
export function ifNoneMatchMatches(header: string, etag: string): boolean {
const own = opaque(etag.trim());
for (const tag of splitTags(header)) if (tag === '*' || opaque(tag) === own) return true;
return false;
}
/**
* Whether a resource last modified at `mtimeMs` is unchanged since an `If-Modified-Since` date.
* HTTP dates have one-second resolution, so the modification time is truncated to the second first;
* otherwise a file written at 12:00:00.400 would never match the `Last-Modified` it was served with.
* An unparseable date is ignored, as RFC 9110 §13.1.3 requires.
*/
export function notModifiedSince(header: string, mtimeMs: number): boolean {
const since = Date.parse(header);
if (Number.isNaN(since)) return false;
return Math.floor(mtimeMs / 1000) * 1000 <= since;
}
/**
* Decides a conditional GET/HEAD: `If-None-Match` when present, else `If-Modified-Since` when the
* caller has a modification time to compare (static files only — handler responses have none).
*/
export function isNotModified(headers: HeaderBag, etag: string, mtimeMs?: number): boolean {
const inm = single(headers['if-none-match']);
if (inm !== undefined) return ifNoneMatchMatches(inm, etag);
const ims = single(headers['if-modified-since']);
return ims !== undefined && mtimeMs !== undefined && notModifiedSince(ims, mtimeMs);
}
/** Weak validator for a static file, from the `stat` the resolver already does: `W/"<size>-<mtimeMs base36>"`. */
export function staticEtag(size: number, mtimeMs: number): string {
return `W/"${size}-${Math.floor(mtimeMs).toString(36)}"`;
}
/**
* Weak validator for a buffered body: its byte length plus a 32-bit FNV-1a hash of its bytes, in
* base 36. FNV rather than `crypto.subtle.digest`: it is synchronous and dependency-free, where
* `subtle` costs a promise per response. It is not collision-resistant and need not be — an ETag
* detects change, it does not authenticate. The length narrows a collision to equal-length bodies.
*
* Weak, so one tag can describe every content-coding of the same body (CARD-16 hashes before it
* encodes). Strings are hashed as UTF-8, so the tag matches what goes on the wire.
*/
export function bodyEtag(body: string | Uint8Array): string {
const bytes = typeof body === 'string' ? Buffer.from(body, 'utf8') : body;
let hash = 0x811c9dc5;
for (let i = 0; i < bytes.length; i++) {
hash ^= bytes[i];
hash = Math.imul(hash, 0x01000193);
}
return `W/"${bytes.length.toString(36)}-${(hash >>> 0).toString(36)}"`;
}
/** The key under which `headers` holds `name`, case-insensitively, or `undefined`. */
export function findHeader(headers: Record<string, unknown>, name: string): string | undefined {
for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return key;
return undefined;
}
/**
* The headers of a `304` built from the `200` it stands for: everything but the `content-*`
* headers that describe a body (`content-type`, `content-length`, `content-encoding`, …), plus
* `transfer-encoding`. `content-location` is kept: §15.4.5 lists it among the fields a 304 sends. `ETag`, `Vary`, `Cache-Control`, `Last-Modified` and anything else a cache
* would update stay (RFC 9110 §15.4.5). Injected security headers are merged later by the adapter,
* exactly as on a `200`.
*/
export function notModifiedHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]> {
const out: Record<string, string | string[]> = {};
for (const key of Object.keys(headers)) {
const lower = key.toLowerCase();
if ((lower.startsWith('content-') && lower !== 'content-location') || lower === 'transfer-encoding') continue;
out[key] = headers[key];
}
return out;
}
+412 -44
View File
@@ -5,23 +5,104 @@ import { isStreamResult, type PipelineResult } from '../pipeline';
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router'; import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream'; import { pickEncoder } from './stream';
import type { RouteDef, HttpOptions } from './types'; import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views';
import type { Encoding } from './compression';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */ /**
* `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.
*
* 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 => crypto.randomUUID();
/**
* A runtime-neutral inbound request.
*
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
* body, it first had to route the request itself — a body is only read for a request that reaches
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
* a four-route app walked its table two and a half times per request. Handing over the *ability*
* to read instead of the result moves that decision here, where the route is known anyway.
*/
export interface NeutralRequest { export interface NeutralRequest {
method: string; method: string;
url: string; // path + query, e.g. "/users/9?x=1" url: string; // path + query, e.g. "/users/9?x=1"
headers: Record<string, string | string[] | undefined>; headers: Record<string, string | string[] | undefined>;
body: unknown; // already-parsed body /** Called only once a route matches, so an unmatched request still never reads a body. */
readBody: BodyReader;
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
source: unknown;
secure: boolean; secure: boolean;
ip: string; /**
* The client address, resolved only when something reads `ctx.ip`. A function of `source` rather
* than a closure, so an adapter passes one module-level function and allocates nothing per request.
*/
resolveIp: (source: unknown, opts: HttpOptions | undefined) => string;
requestId: string;
traceId?: string;
}
// Module scope, not a local inside `correlateRequest`. Declared there it was a closure allocated
// on every single request, which measured at 0.16 us against a ~4.4 us one — 45% of the whole
// observability overhead, for a helper that captures nothing.
const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
/**
* Derives a request's identity from its headers, for the adapters to stamp on a `NeutralRequest`.
*
* **Called by the adapters, not by {@link handle}**, and the placement is the point. An adapter's
* `BodyReader` renders its own `413` (`server.ts`, `web.ts`) without `handle()` ever producing it,
* so identity has to exist before the read starts. Generating it in here would leave precisely the
* failures an operator most wants to correlate with nothing to correlate them by.
*
* An `x-request-id` from a gateway is adopted rather than replaced — a service behind a proxy must
* not open a second identity for a request that already has one. `traceparent` is carried through
* untouched: core implements no propagation spec, and W3C Trace Context belongs to the exporter.
*/
export function correlateRequest(headers: Record<string, string | string[] | undefined>): {
requestId: string;
traceId?: string;
} {
const incoming = first(headers['x-request-id'])?.trim();
const traceId = first(headers.traceparent)?.trim();
// `randomUUID` is not the lazy choice here, it is the measured one. Every supported runtime
// already batches entropy behind it, so the obvious "faster" replacements are not:
//
// crypto.randomUUID() 76 ns
// batched getRandomValues + hex, 12 bytes 50 ns cross-runtime, saves 0.26% of a request
// batched + Buffer.toString('hex') 49 ns Node-only, so it cannot be used here
// uint32 -> toString(36) from a pool 114 ns
// Math.random() x2 -> base36 265 ns 3.5x SLOWER; string work dominates
// getRandomValues per call, unbatched 472 ns
//
// The only cross-runtime win is 26 ns, against ~10.19 us for a real socketed request. A hand-
// rolled entropy pool is not worth 0.26%. A lazy getter is separately useless: the adapters and
// the payload builders both spread this object, and the first spread materialises it.
return { requestId: incoming || randomUUID(), traceId: traceId || undefined };
} }
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ /** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome = export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer } | { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder }; | {
kind: 'stream';
headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
route: string;
/** Set by `compressOutcome`: the adapter encodes each frame with it and flushes. */
encoding?: Encoding;
};
/** {@link handle}'s result for a normal (non-preflight) request. */ /** {@link handle}'s result for a normal (non-preflight) request. */
export interface HandleResult { export interface HandleResult {
@@ -45,7 +126,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> }, req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> { ): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
return injected; return injected;
} }
@@ -54,20 +135,76 @@ function errorOutcome(
req: NeutralRequest, req: NeutralRequest,
injected: Record<string, string>, injected: Record<string, string>,
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string | string[]> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: bodyless({
kind: 'buffered', kind: 'buffered',
status: rendered.status, status: rendered.status,
headers: { ...rendered.headers, ...headers }, headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body, body: req.method === 'HEAD' ? '' : rendered.body,
}, }),
}; };
} }
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
/**
* A `304` has no body on any adapter, and none of the headers that describe one. This is the one
* place every buffered outcome passes through on its way out, so a handler that throws
* `NotModified` — rendered by the default renderer as a JSON envelope — answers the same bodiless
* `304` the ETag path does. Node would drop the body of a 304 by itself; the fetch adapters already
* null it; the `content-type` would still have gone out on both.
*/
function bodyless(outcome: Buffered): Buffered {
if (outcome.status !== 304) return outcome;
return { kind: 'buffered', status: 304, headers: notModifiedHeaders(outcome.headers), body: '' };
}
/**
* Answers a static hit: `ETag` + `Last-Modified` from the resolver's `stat`, `Cache-Control` from the
* `static` option, and a `304` — decided before the file is read, so a revalidation costs a `stat`
* and nothing more. HEAD never reads either.
*/
async function staticOutcome(hit: StaticHit, req: NeutralRequest): Promise<Buffered> {
const etag = staticEtag(hit.size, hit.mtimeMs);
const headers: Record<string, string> = {
'content-type': hit.contentType,
etag,
'last-modified': new Date(hit.mtimeMs).toUTCString(),
'cache-control': hit.cacheControl,
};
if (isNotModified(req.headers, etag, hit.mtimeMs))
return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : await hit.read() };
}
/**
* `createApp({ etag: true })` for a handler response: a buffered `200` to GET/HEAD gets a weak ETag
* from its body — computed before HEAD blanks the body, so HEAD and GET carry the same tag — unless
* the handler set one, which is kept and only compared. A match becomes a bodiless `304`. The
* handler has already run: this saves bandwidth, not work.
*/
function tagged(
result: { status: number; headers: Record<string, string | string[]>; body: string },
req: NeutralRequest,
): Buffered {
const key = findHeader(result.headers, 'etag');
const existing = key === undefined ? undefined : result.headers[key];
// ETag is single-valued: from an array, the last value wins, as a repeated `setHeader` would.
const own = Array.isArray(existing) ? existing[existing.length - 1] : existing;
const etag = own ?? bodyEtag(result.body);
const headers = { ...result.headers, [key ?? 'etag']: etag };
if (isNotModified(req.headers, etag)) return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : result.body };
}
async function unmatchedOutcome( async function unmatchedOutcome(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
@@ -77,18 +214,7 @@ async function unmatchedOutcome(
): Promise<HandleResult> { ): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path); const hit = await opts.static(path);
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
} }
const allow = allowedMethods(routes, path); const allow = allowedMethods(routes, path);
@@ -104,17 +230,221 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {}); return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
} }
/**
* The `route` reported for a request no route matched.
*
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
* single series where the concrete path would produce one per distinct URL.
*/
export const UNMATCHED_ROUTE = '<unmatched>';
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace {
route?: string;
}
/** /**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response. * caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
*
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
* here in milliseconds while its connection may live for hours, and ending the span at close would put
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
*/ */
export async function handle( export function handle(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
req: NeutralRequest, req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req); const bus = opts?.bus;
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
if (
bus === undefined ||
!(
bus.hasListeners('request:start') ||
bus.hasListeners('request:end') ||
bus.hasListeners('route:matched') ||
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined, injected);
}
return observedDispatch(routes, opts, req, bus, injected);
}
/**
* Whether anything is listening for the request pair — the one check both adapters need before
* paying for a `performance.now()` on a request they are about to refuse.
*/
export function watchingRequests(bus: Bus | undefined): bus is Bus {
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
}
/**
* Emits the lifecycle pair for a request shed before routing.
*
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
* time a server sheds — under load, which is when it can least afford them.
*
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
* costs nothing for a subscriber of one.
*/
export function emitShedPair(
bus: Bus,
req: { method: string; url: string; requestId?: string; traceId?: string },
startedAt: number,
): void {
const name = `${req.method} ${req.url}`;
if (bus.hasListeners('request:start'))
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
if (bus.hasListeners('request:end'))
bus.emit('request:end', {
name,
method: req.method,
status: 503,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
async function observedDispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0;
const trace: Trace = {};
if (bus.hasListeners('request:start'))
bus.emit('request:start', {
name: `${req.method} ${req.url}`,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
});
const result = await dispatch(routes, opts, req, bus, trace, injected);
if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
// by the time anything is piped.
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
bus.emit('request:end', {
name: trace.route ?? `${req.method} ${req.url}`,
method: req.method,
route: trace.route,
status,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
return result;
}
/**
* The request a route handler receives.
*
* `ip` is resolved on its first read and kept. Most routes never read it, and on Bun resolving it
* is a native call. A step may assign it, as it may any key. The accessor is on the prototype rather
* than in an object literal: a literal with an accessor is a slow object in V8 and JSC, and every
* read of every key paid for it, which cost Node and Deno 15-24%.
*/
class RouteRequest {
method: string;
url: string;
headers: NeutralRequest['headers'];
query: Record<string, string>;
protocol: 'http' | 'https';
requestId: string;
traceId: string | undefined;
private resolved: string | undefined = undefined;
constructor(
private readonly req: NeutralRequest,
private readonly opts: HttpOptions | undefined,
public params: Record<string, string>,
public body: unknown,
) {
this.method = req.method;
this.url = req.url;
this.headers = req.headers;
this.query = parseQuery(req.url);
this.protocol = req.secure ? 'https' : 'http';
this.requestId = req.requestId;
this.traceId = req.traceId;
}
get ip(): string {
return (this.resolved ??= this.req.resolveIp(this.req.source, this.opts));
}
set ip(value: string) {
this.resolved = value;
}
/**
* A stream body runs after the response has started, when the socket the address would come
* from may already be gone, so once a stream is returned an address nothing has read yet is `''`.
*/
seal(): void {
this.resolved ??= '';
}
}
/** Runs the matched route's handler, turning a throw into the standard error envelope. */
async function runHandler(
matched: MatchedRoute,
req: NeutralRequest,
body: unknown,
opts: HttpOptions | undefined,
): Promise<PipelineResult> {
const request = new RouteRequest(req, opts, matched.params, body);
let result: PipelineResult;
try {
result = await matched.def.handler(request);
} catch (error) {
result = renderError(error, req, opts?.onError, opts?.logger);
}
if (isStreamResult(result)) request.seal();
return result;
}
async function dispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> {
// Both adapters compute this before routing, because a response written above `handle()` — a
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
const injected = precomputed ?? computeInjected(opts, req);
let path: string; let path: string;
try { try {
@@ -124,42 +454,80 @@ export async function handle(
} }
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) }; return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
} }
const matched = resolveRoute(routes, req.method, path); const matched = resolveRoute(routes, req.method, path);
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected); if (!matched) {
// `name` here is the path that arrived, and it is the one value in this payload that must never
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
// and some of them to get it wrong.
if (trace) trace.route = UNMATCHED_ROUTE;
let result: PipelineResult; if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', {
name: `${req.method} ${path}`,
route: UNMATCHED_ROUTE,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
});
try { return unmatchedOutcome(routes, opts, req, path, injected);
result = await matched.def.handler({
method: req.method,
url: req.url,
headers: req.headers,
params: matched.params,
query: parseQuery(req.url),
body: req.body,
protocol: req.secure ? 'https' : 'http',
ip: req.ip,
});
} catch (error) {
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
} }
if (trace) trace.route = matched.def.pattern;
if (bus?.hasListeners('route:matched'))
bus.emit('route:matched', {
name: matched.def.pattern,
route: matched.def.pattern,
method: req.method,
transport: matched.def.transport,
requestId: req.requestId,
traceId: req.traceId,
});
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
// object per request bought nothing.
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
// caller merges `injected` into it exactly as it does for every other outcome.
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
const result = await runHandler(matched, req, acquired.body, opts);
if (isStreamResult(result)) { if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; return {
injected,
outcome: {
kind: 'stream',
headers: encoder.headers,
stream: result.stream,
encoder,
route: matched.def.pattern,
},
};
} }
if (opts?.etag && result.status === 200 && (req.method === 'GET' || req.method === 'HEAD'))
return { injected, outcome: tagged(result, req) };
return { return {
injected, injected,
outcome: { outcome: bodyless({
kind: 'buffered', kind: 'buffered',
status: result.status, status: result.status,
headers: result.headers, headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body, body: req.method === 'HEAD' ? '' : result.body,
}, }),
}; };
} }
+64 -3
View File
@@ -1,5 +1,7 @@
import { mergeVary } from '../security'; import { mergeVary } from '../security';
const hasOwn = Object.prototype.hasOwnProperty;
/** /**
* Merges a handler's response headers with authoritative `injected` headers * Merges a handler's response headers with authoritative `injected` headers
* (security + CORS). Injected keys win case-insensitively; `vary` is merged. * (security + CORS). Injected keys win case-insensitively; `vary` is merged.
@@ -10,7 +12,6 @@ export function mergeInjectedHeaders(
injected: Record<string, string>, injected: Record<string, string>,
): Record<string, any> { ): Record<string, any> {
const merged: Record<string, any> = {}; const merged: Record<string, any> = {};
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
let handlerVary: string | undefined; let handlerVary: string | undefined;
if (handlerHeaders) if (handlerHeaders)
@@ -18,11 +19,23 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase(); const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') { if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key]; // A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
// every token a handler listed instead of stringifying the array by accident.
const value = handlerHeaders[key];
handlerVary = Array.isArray(value) ? value.join(', ') : value;
continue; continue;
} }
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; // `injected` is looked up directly instead of through a lowercased Set rebuilt per response.
// Every key it can hold is written as a lowercase literal in `src/security.ts` — both
// `buildSecurityHeaders` and `resolveCors`, which are its only sources — so lowercasing them
// again produced a copy of the keys it already had. Three allocations per response (an array,
// a mapped array, a Set) to answer a question the object answers itself: 146.4 ns against
// 55.9 ns.
//
// `hasOwnProperty` rather than `in`: a handler is free to send a header called `constructor`
// or `toString`, and `in` would find those on Object.prototype and silently drop them.
if (!hasOwn.call(injected, lowerKey)) merged[key] = handlerHeaders[key];
} }
Object.assign(merged, injected); Object.assign(merged, injected);
@@ -30,3 +43,51 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary; else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged; return merged;
} }
/**
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
* adapters sending the same bytes. So every other array is joined with `, ` here, before
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
*/
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
let out: Record<string, unknown> | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
out ??= { ...headers };
out[key] = value.join(', ');
}
return (out as T | undefined) ?? headers;
}
/**
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
*
* A record of plain strings, which is nearly every response, is returned untouched: Deno and Bun
* build their native headers from a record directly, and filling a `Headers` from JS instead measured
* 5–8% on every Deno request.
*/
export function toWebHeaders(headers: Record<string, unknown>): Headers | Record<string, string> {
if (Object.values(headers).every((value) => typeof value === 'string')) return headers as Record<string, string>;
const out = new Headers();
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
if (!Array.isArray(value)) out.set(key, String(value));
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
else out.set(key, value.join(', '));
}
return out;
}
+170
View File
@@ -0,0 +1,170 @@
import type { ReservedPath } from './reserved-paths';
/** Liveness probe path: `200` whenever the process answers. */
export const LIVE_PATH = '/__live__';
/** Readiness probe path: `503` while booting or draining, `200` otherwise. */
export const READY_PATH = '/__ready__';
/** The probe paths, as reserved-path entries for the boot check (only while `health` is on). */
export const HEALTH_RESERVED: readonly ReservedPath[] = [
{ path: LIVE_PATH, purpose: 'the liveness probe, health: true' },
{ path: READY_PATH, purpose: 'the readiness probe, health: true' },
];
/**
* Where an app is in its life, as `/__ready__` reports it.
*
* `booting` until `boot()` resolves, `ready` after, `draining` from the moment `close()` starts.
* Moves forward only: a boot that finishes while draining does not make the app ready again.
*/
export type HealthPhase = 'booting' | 'ready' | 'draining';
/** What the adapters read to answer a probe. Lives on {@link HttpOptions}; absent when `health` is off. */
export interface HealthProbe {
phase(): HealthPhase;
/** Optional providers that failed to boot, as `app.degraded()` reports them. */
degraded(): string[];
}
/**
* Close-time hook on the app object for the adapters that own the server (`serveDeno`, `serveBun`):
* marks the app draining and resolves after `drainDelayMs`, so the listener stays open while
* `/__ready__` answers `503`. Idempotent — later calls share the first window. Symbol-keyed because it
* is adapter plumbing, not public API.
*/
export const HEALTH_DRAIN: unique symbol = Symbol.for('green-tea.health-drain');
/** Starts the drain window on `app` (see {@link HEALTH_DRAIN}); resolves at once when health is off. */
export function beginDrain(app: object): Promise<void> {
return (app as { [HEALTH_DRAIN]?: () => Promise<void> })[HEALTH_DRAIN]?.() ?? Promise.resolve();
}
/** A probe response, before the adapter merges in the injected security headers. */
export interface ProbeAnswer {
status: number;
headers: Record<string, string>;
body: string;
}
const JSON_NO_STORE = { 'content-type': 'application/json', 'cache-control': 'no-store' };
/** The readiness body and status for the current phase. */
function readiness(probe: HealthProbe): { status: number; body: object } {
const phase = probe.phase();
if (phase === 'booting') return { status: 503, body: { status: 'booting' } };
if (phase === 'draining') return { status: 503, body: { status: 'draining' } };
const degraded = probe.degraded();
return degraded.length
? { status: 200, body: { status: 'degraded', degraded } }
: { status: 200, body: { status: 'ok' } };
}
/**
* Answers `/__live__` or `/__ready__`, or returns `undefined` for any other path.
*
* Called by each adapter before the request gate and before `handle()`, so a probe runs no step,
* provider, plugin or `onError`, emits no lifecycle event, and is never shed by
* `maxConcurrentRequests`. `url` may carry a query string; only the exact path is a probe.
*/
export function answerProbe(method: string, url: string, probe: HealthProbe): ProbeAnswer | undefined {
const query = url.indexOf('?');
const path = query === -1 ? url : url.slice(0, query);
if (path !== LIVE_PATH && path !== READY_PATH) return undefined;
if (method !== 'GET' && method !== 'HEAD') {
return {
status: 405,
headers: { ...JSON_NO_STORE, allow: 'GET, HEAD' },
body: JSON.stringify({ error: 'Method Not Allowed' }),
};
}
const { status, body } = path === LIVE_PATH ? { status: 200, body: { status: 'ok' } } : readiness(probe);
return { status, headers: { ...JSON_NO_STORE }, body: method === 'HEAD' ? '' : JSON.stringify(body) };
}
/** `createApp({ health })`, normalised. `undefined` when health is off. */
export interface HealthConfig {
drainDelayMs: number;
}
/**
* Validates `createApp({ health })` and normalises it. Throws on anything but `true`, `false`,
* `undefined` or `{ drainDelayMs?: number }`, and on a `drainDelayMs` that does not fit in the shutdown
* budget next to the teardown reservation.
*/
export function resolveHealth(
health: unknown,
shutdownTimeoutMs: number | undefined,
teardownTimeoutMs: number | undefined,
): HealthConfig | undefined {
if (health === undefined || health === false) return undefined;
if (health === true) return { drainDelayMs: 0 };
if (typeof health !== 'object' || health === null || Array.isArray(health)) {
throw new Error(`health must be true, false or { drainDelayMs?: number } — got ${JSON.stringify(health)}`);
}
const unknown = Object.keys(health).filter((key) => key !== 'drainDelayMs');
if (unknown.length) {
throw new Error(
`health: unknown option ${unknown.map((key) => `'${key}'`).join(', ')} — only drainDelayMs is supported`,
);
}
const drainDelayMs = (health as { drainDelayMs?: unknown }).drainDelayMs ?? 0;
if (typeof drainDelayMs !== 'number' || !Number.isFinite(drainDelayMs) || drainDelayMs < 0) {
throw new Error(`health.drainDelayMs must be a non-negative number of milliseconds — got ${String(drainDelayMs)}`);
}
const budget = shutdownTimeoutMs ?? 10_000;
const reserved = teardownTimeoutMs ?? 0;
if (drainDelayMs + reserved > budget) {
throw new Error(
`health.drainDelayMs (${drainDelayMs}) plus teardownTimeoutMs (${reserved}) cannot exceed ` +
`shutdownTimeoutMs (${budget}) — the drain window is spent out of the shutdown budget, ` +
'so close() would have no time left to drain connections or run teardown.',
);
}
return { drainDelayMs };
}
/**
* The health state machine for one app: wraps `bootGraph` so a resolved boot marks it ready, and
* offers the drain that `close()` (and `serveDeno`/`serveBun` through {@link HEALTH_DRAIN}) starts.
* With health off the probe is absent and the drain resolves at once.
*/
export function trackHealth(
health: HealthConfig | undefined,
bootGraph: () => Promise<void>,
degraded: () => string[],
): { bootApp: () => Promise<void>; healthProbe: HealthProbe | undefined; drain: () => Promise<void> } {
// Forward only: a boot that resolves after close() started stays draining.
let phase: HealthPhase = 'booting';
// Shared by every drain call. Left referenced on purpose: the process must stay up for the window.
let drainWindow: Promise<void> | undefined;
const bootApp = async (): Promise<void> => {
await bootGraph();
if (phase === 'booting') phase = 'ready';
};
const drain = (): Promise<void> => {
if (!health) return Promise.resolve();
if (!drainWindow) {
phase = 'draining';
const ms = health.drainDelayMs;
drainWindow = ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
}
return drainWindow;
};
return { bootApp, healthProbe: health ? { phase: () => phase, degraded } : undefined, drain };
}
+64
View File
@@ -0,0 +1,64 @@
// 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.
//
// Bun records its server rather than an address. `server.requestIP()` is a native call that builds
// an object, and making it on every request measured 7–11% on Bun; recording the server is free, and
// the address is asked for only when something reads `ctx.ip`. Deno hands the address over already
// resolved, so it records the string.
const KEY = Symbol.for('@green-tea/core:peer');
/** Names a request's socket peer on demand: Bun's server. */
export interface PeerSource {
requestIP(request: Request): { address: string } | null;
}
const registry = globalThis as { [KEY]?: WeakMap<Request, string | PeerSource> };
const peers = (registry[KEY] ??= new WeakMap<Request, string | PeerSource>());
/** Records the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, peer: string | PeerSource): void {
if (peer) peers.set(request, peer);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
const peer = peers.get(request);
return typeof peer === 'object' ? (peer.requestIP(request)?.address ?? '') : (peer ?? '');
}
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
// decide that, because the option lives on the app, so it records the value and the app decides.
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
export function setProxyClient(source: object, ip: string): void {
if (ip) proxyClients.set(source, ip);
}
/**
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
* disagree about whether the header counts.
*/
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
return trustProxy ? (proxyClients.get(source) ?? '') : '';
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Per-server/adapter request budget.
*
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
*/
export interface RequestGate {
/**
* Whether a budget is actually configured.
*
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
* per-request cost behind it should be skipped entirely.
*/
limited: boolean;
acquire(): boolean;
release(): void;
}
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
export function createRequestGate(limit: number | undefined): RequestGate {
let active = 0;
const limited = limit !== undefined && limit > 0;
return {
limited,
acquire(): boolean {
if (limit === undefined || limit <= 0) return true;
if (active >= limit) return false;
active++;
return true;
},
release(): void {
if (limit === undefined || limit <= 0) return;
if (active > 0) active--;
},
};
}
+60 -9
View File
@@ -1,18 +1,69 @@
import type http from 'http'; import type http from 'http';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { declaresOverLimit } from './body';
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ /** 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> { export function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
const chunks: Buffer[] = []; // A declared length over the limit is refused without waiting for the first chunk, which could
let total = 0; // otherwise sit until the request timeout. The fetch adapter makes the same check.
const contentLength = req.headers['content-length'];
if (declaresOverLimit(contentLength, maxBodyBytes)) return Promise.reject(new HttpError(413, 'Payload Too Large'));
for await (const chunk of req) { // No `Transfer-Encoding` and no (or a zero) `Content-Length` is a request without a body (RFC 9112
total += (chunk as Buffer).length; // §6.3) — every GET. Node's parser has already finished it, so there is nothing to wait for, and
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); // subscribing to the stream anyway measured ~4% on an 8 KB GET response. Node drains the unread
chunks.push(chunk as Buffer); // request itself when the response ends.
} if (req.headers['transfer-encoding'] === undefined && (contentLength === undefined || contentLength === '0'))
return Promise.resolve(undefined);
return chunks.length === 0 ? undefined : Buffer.concat(chunks); // Listeners rather than `for await`: the async iterator costs a promise and a microtask per chunk,
// which a JSON POST pays on every request. The semantics are the iterator's: the running total
// still enforces the limit, an over-limit body destroys the request as leaving the loop did, and a
// stream that errors or closes before `end` rejects.
return new Promise<Buffer | undefined>((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
const settle = (): void => {
req.off('data', onData);
req.off('end', onEnd);
req.off('error', onError);
req.off('close', onClose);
};
const onData = (chunk: Buffer): void => {
total += chunk.length;
if (total <= maxBodyBytes) {
chunks.push(chunk);
return;
}
settle();
req.destroy();
reject(new HttpError(413, 'Payload Too Large'));
};
const onEnd = (): void => {
settle();
resolve(chunks.length === 0 ? undefined : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
};
const onError = (err: Error): void => {
settle();
reject(err);
};
const onClose = (): void => {
settle();
reject(Object.assign(new Error('Premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }));
};
req.on('data', onData);
req.on('end', onEnd);
req.on('error', onError);
req.on('close', onClose);
});
} }
/** Returns the first comma-separated token of a header value (handles array-valued headers). */ /** Returns the first comma-separated token of a header value (handles array-valued headers). */
+49
View File
@@ -0,0 +1,49 @@
import { compilePattern, matchPattern } from './router';
/**
* A path the framework answers itself, ahead of the route table, so no declared route may claim it.
*
* Each adapter intercepts these before route matching. A user route that could also match one would
* be served on some code paths and shadowed on others, which is exactly the "works on Node, refused
* on Deno" split a reserved path exists to prevent, so the boot refuses it instead.
*/
export interface ReservedPath {
/** The concrete request path, e.g. `/__mesh__/control`. */
path: string;
/** What the framework serves there, for the error message (e.g. `the mesh control channel`). */
purpose: string;
}
/**
* Returns the reserved path `pattern` would claim, or `undefined` when it claims none.
*
* A pattern claims a reserved path when it matches it *and* its first segment is the reserved path's
* own first segment, spelled literally. The literal-prefix half is deliberate: `/:org/:repo` or a
* `/:rest*` fallback also match `/__mesh__/control`, but they never ask for it — the adapter intercepts
* the reserved path before matching, so such a route simply never sees that one path, the same way
* on every runtime. Refusing them would fail the boot of ordinary apps for a path they never named.
* A literal pattern is therefore checked by equality and a parameterised one (`/__mesh__/:x`,
* `/__mesh__/:rest*`) by matching the reserved path against it.
*/
export function claimedReservedPath(pattern: string, reserved: readonly ReservedPath[]): ReservedPath | undefined {
const first = compilePattern(pattern).segments[0];
if (first?.kind !== 'static') return undefined;
return reserved.find(
(entry) => entry.path.split('/')[1] === first.value && matchPattern(pattern, entry.path) !== undefined,
);
}
/**
* Throws when `pattern` claims a reserved path. `subject` names the declaration for the message,
* e.g. `route GET /__mesh__/control at Chat.control`.
*/
export function assertNotReserved(pattern: string, subject: string, reserved: readonly ReservedPath[]): void {
const claimed = claimedReservedPath(pattern, reserved);
if (!claimed) return;
throw new Error(
`${subject} uses the reserved path ${claimed.path} (${claimed.purpose}) — ` +
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
);
}
+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;
}
+546 -45
View File
@@ -1,4 +1,4 @@
import type { RouteDef, MatchedRoute } from './types'; import type { RouteDef, RouteTable, MatchedRoute } from './types';
export type CompiledSegment = export type CompiledSegment =
| { kind: 'static'; value: string } | { kind: 'static'; value: string }
@@ -33,13 +33,21 @@ interface ConstraintToken {
separator: boolean; 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. */ /** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
function readConstraintToken(source: string): ConstraintToken | undefined { 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; if (!atom) return undefined;
const rest = source.slice(atom.length); 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); if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
return { return {
@@ -139,8 +147,19 @@ function segmentShape(segment: CompiledSegment): string {
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p'; 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, localTreeBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */ /** Compiles and validates one route pattern. Results are cached by source string. */
export function compilePattern(pattern: string): CompiledPattern { export function compilePattern(pattern: string): CompiledPattern {
seamCounts.compilePattern++;
const cached = compiledCache.get(pattern); const cached = compiledCache.get(pattern);
if (cached) return cached; if (cached) return cached;
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`); if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
@@ -163,27 +182,117 @@ export function compilePattern(pattern: string): CompiledPattern {
return compiled; return compiled;
} }
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
/**
* Classifies one path segment as `.`, `..`, or neither.
*
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
* plain form resolves away from.
*/
function dotSegment(segment: string): '.' | '..' | undefined {
if (segment === '.' || segment === '..') return segment;
if (segment.length > 6 || !segment.includes('%')) return undefined;
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
return decoded === '.' || decoded === '..' ? decoded : undefined;
}
/**
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
*
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
* simply not recoverable there, so rejecting dot segments outright — which is what this module
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
* runtimes. Resolving is the only rule all four can agree on.
*
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
*/
function resolveDotSegments(path: string): string {
const out: string[] = [];
for (const segment of path.split('/').slice(1)) {
const dots = dotSegment(segment);
if (dots === '.') continue;
if (dots === '..') {
out.pop();
continue;
}
out.push(segment);
}
return `/${out.join('/')}`;
}
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */ /** Applies the public trailing-slash policy and validates every segment's percent encoding. */
export function normalizeRequestPath(path: string): string { export function normalizeRequestPath(path: string): string {
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash'); if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash'); if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
try { // Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment); // `%` at all — which is most of them — pays only the scans.
} catch { const resolved =
throw new InvalidRequestPathError('invalid request path: malformed path encoding'); (path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path;
const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
// Validation only — the decoded value is deliberately discarded, matching is done on the raw
// path. So the work is skipped entirely unless there is something to validate.
//
// This used to split the path and call `decodeURIComponent` per segment, on every request, and
// throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment
// route — around 8% of a whole request, spent proving that a string nobody decodes could be
// decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths.
//
// One call on the whole string rather than per segment is the same check: `decodeURIComponent`
// throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment
// decodes fine either way. Only the throw matters here, never the result.
if (normalized.includes('%')) {
try {
decodeURIComponent(normalized);
} catch {
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
}
} }
return normalized; return normalized;
} }
function decodeSegment(value: string): string { function decodeSegment(value: string): string {
return decodeURIComponent(value); // Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
// runs for every param segment of every candidate route the scan reaches.
return value.includes('%') ? decodeURIComponent(value) : value;
} }
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined { /**
const pathSegs = path.split('/').filter(Boolean); * Splits a request path into its non-empty segments.
*
* Called once per request by the scanning functions below, not once per candidate route. It used to
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
* registered route on every request, always producing the same array.
*/
function splitPath(path: string): string[] {
return path.split('/').filter(Boolean);
}
/**
* Matches one compiled pattern against a request's segments.
*
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
* several routes decoded the same string once per route. Position is all decoding depends on, so one
* array shared across the scan is the same answer for less work.
*/
function matchCompiled(
compiled: CompiledPattern,
pathSegs: string[],
decoded?: Array<string | undefined>,
): Record<string, string> | undefined {
const params: Record<string, string> = {}; const params: Record<string, string> = {};
for (let index = 0; index < compiled.segments.length; index++) { for (let index = 0; index < compiled.segments.length; index++) {
@@ -201,7 +310,7 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
continue; continue;
} }
const value = decodeSegment(pathSegs[index]); const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined; if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value; params[segment.name] = value;
} }
@@ -211,13 +320,18 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
/** Matches a compiled segment pattern and returns its decoded parameters. */ /** Matches a compiled segment pattern and returns its decoded parameters. */
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined { export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
return matchCompiled(compilePattern(pattern), path); return matchCompiled(compilePattern(pattern), splitPath(path));
} }
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */ /**
function moreSpecific(a: string, b: string): number { * Orders patterns by exactness, then static/constrained/plain segment specificity.
const scoreA = compilePattern(a); *
const scoreB = compilePattern(b); * Takes compiled patterns rather than their source strings: it used to re-derive both through
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
*/
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
const scoreA = a;
const scoreB = b;
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
@@ -230,23 +344,387 @@ function moreSpecific(a: string, b: string): number {
return 0; return 0;
} }
/** Finds the most specific route matching both method and path; ties keep registration order. */ /**
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { * One route at a terminal of the index.
let best: MatchedRoute | undefined; *
let bestPattern = ''; * `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;
}
for (const route of routes) { /** A `:param` edge. Plain params share one edge; constrained ones share an edge per constraint source. */
if (route.method !== method) continue; interface ParamEdge {
const params = matchPattern(route.pattern, path); constraintSource: string | undefined;
if (!params) continue; constraint: RegExp | undefined;
node: RadixNode;
}
if (!best || moreSpecific(route.pattern, bestPattern) > 0) { // ponytail: a segment trie — one edge per whole path segment, no compression of single-child static
best = { params, def: route }; // chains. Lookup cost already follows path depth, not route count; compressing would save a few map
bestPattern = route.pattern; // 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[]>;
}
/**
* 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>();
/** The array a {@link RouteTable} holds right now. Servers call it once per request. */
export function currentRoutes(table: RouteTable): RouteDef[] {
return typeof table === 'function' ? table() : table;
}
/** 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. 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[], RouteIndex>();
function newNode(): RadixNode {
return { statics: new Map(), params: [], exact: [], catchAll: [], min: Infinity };
}
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;
} }
return best; let edge = node.params.find((candidate) => candidate.constraintSource === segment.constraintSource);
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;
}
/**
* The last local trees built, and the `(def, position)` entries they were built from.
*
* When mesh membership changes, the app publishes a new array whose local entries are the same
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
* first local def, so it is collected with the table that owns it.
*/
const localTreeCache = new WeakMap<
RouteDef,
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
>();
function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean {
return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order);
}
function localTrees(local: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
if (!local.length) return buildTrees(local);
const cached = localTreeCache.get(local[0].def);
if (cached && sameEntries(cached.entries, local)) return cached.trees;
seamCounts.localTreeBuilds++;
const trees = buildTrees(local);
localTreeCache.set(local[0].def, { entries: local, trees });
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: localTrees(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 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 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. */ /** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
@@ -255,28 +733,37 @@ export interface ResolvedRoute extends MatchedRoute {
} }
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined { export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
const explicit = matchRoute(routes, method, path); const index = routeIndex(routes);
if (explicit) return { ...explicit, implicitHead: false }; 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; if (method !== 'HEAD') return undefined;
const fallback = matchRoute( // Only a buffered GET can answer HEAD. The filter applies inside the ranking, so a higher-ranked
routes.filter((route) => route.transport === 'buffer'), // streaming GET is passed over for a lower-ranked buffered one rather than ending the search.
'GET', const fallback = findRoute(index, 'GET', search, isBuffered);
path, return fallback ? { params: paramsOf(fallback, search), def: fallback.def, implicitHead: true } : undefined;
);
return fallback ? { ...fallback, implicitHead: true } : undefined;
} }
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; 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[] { export function allowedMethods(routes: RouteDef[], path: string): string[] {
const index = routeIndex(routes);
const search = newSearch(path);
const methods = new Set<string>(); const methods = new Set<string>();
for (const route of routes) { for (const method of index.methods) {
if (!matchPattern(route.pattern, path)) continue; // A buffered GET answers both GET and HEAD, so it is looked for first; only a GET path served
methods.add(route.method); // by streaming routes alone needs the second lookup.
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD'); 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'); if (methods.size) methods.add('OPTIONS');
@@ -289,9 +776,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
}); });
} }
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ /**
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
*
* The query string is everything after the **first** `?` and before a `#`, if one is present.
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
* `{ q: 'what?now' }`.
*/
export function parseQuery(url: string): Record<string, string> { export function parseQuery(url: string): Record<string, string> {
const queryString = url.split('?')[1] ?? ''; // Most requests carry no query string, and the work below is not free for them:
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
// Measured at 92.3 ns against 18.6 ns for this check.
const start = url.indexOf('?');
if (start < 0) return {};
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
const hash = url.indexOf('#', start + 1);
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
const out: Record<string, string> = {}; const out: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value; for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
return out; return out;
+235 -141
View File
@@ -1,29 +1,37 @@
import type http from 'http'; import type http from 'http';
import type https from 'https'; import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import { isHttpError, HttpError } from '../signals'; import type { Bus, Correlation } from '../bus';
import type { Bus } from '../bus'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { buildSecurityHeaders, resolveCors } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders, joinListHeaders } from './headers';
import { handle } from './core'; import {
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; handle,
correlateRequest,
computeInjected,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
type NeutralOutcome,
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types';
import { currentRoutes } from './router';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
import { answerProbe } from './health';
import { compressOutcome } from './compression';
interface HandlerConfig { interface HandlerConfig {
routes: RouteDef[]; routes: RouteTable;
bus?: Bus; bus?: Bus;
opts?: HttpOptions; opts?: HttpOptions;
maxBody: number;
trustProxy: boolean; trustProxy: boolean;
} }
/** A ready-to-send error response produced while acquiring the request body. */
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
/** Builds the {@link ErrorRequest} handed to a user error renderer. */ /** Builds the {@link ErrorRequest} handed to a user error renderer. */
function errorRequest(req: http.IncomingMessage): ErrorRequest { function errorRequest(req: http.IncomingMessage): ErrorRequest {
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers }; return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
@@ -31,143 +39,271 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
/** /**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions. * @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go).
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events. * @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path. * @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options. * @param opts Limits, TLS, security, CORS, and body-parsing options.
*/ */
/** `ctx.ip` on Node, for `NeutralRequest.resolveIp`: the forwarded hop under `trustProxy`, else the socket peer. */
function nodeIp(source: unknown, opts: HttpOptions | undefined): string {
return deriveIp(source as http.IncomingMessage, opts?.trustProxy ?? false);
}
export function createHttpServer( export function createHttpServer(
routes: RouteDef[], routes: RouteTable,
wsRoutes: WsRouteDef[] = [], wsRoutes: WsRouteDef[] = [],
bus?: Bus, bus?: Bus,
meshControl?: MeshControl, meshControl?: MeshControl,
opts?: HttpOptions, opts?: HttpOptions,
): http.Server { ): http.Server {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
const trustProxy = opts?.trustProxy ?? false; const trustProxy = opts?.trustProxy ?? false;
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy }); const handler = createRequestHandler({ routes, bus, opts, trustProxy });
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe // Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen(). // (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports const nodeHttp = nodeRequire<typeof import('http')>('http');
const nodeHttp = require('http') as typeof import('http'); const nodeHttps = nodeRequire<typeof import('https')>('https');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls const server: http.Server = (opts?.tls
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler) ? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server; : nodeHttp.createServer(handler)) as unknown as http.Server;
const maxConnections = opts?.limits?.maxConnections ?? 1000;
if (maxConnections > 0) {
server.maxConnections = maxConnections;
let lastDropWarn = 0;
server.on('drop', ({ remoteAddress, remotePort }) => {
const now = Date.now();
if (now - lastDropWarn < 60_000) return;
lastDropWarn = now;
opts?.logger?.warn(
`maxConnections (${maxConnections}) reached \u2014 dropped connection from ${remoteAddress ?? 'unknown'}:${remotePort ?? 'unknown'}`,
{ maxConnections, remoteAddress, remotePort },
);
});
}
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_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; return server;
} }
/** /**
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core. * Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`, * Describes the request, supplies the {@link BodyReader} the core calls once a route matches, then
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is * writes the result to `res` (buffered or streamed). Routing, body parsing, limits and error
* installed here — and stays the single source of truth for merging headers into every response — * rendering all live in the core. The security-header monkeypatch is installed here — and stays the
* so `handle()`'s own `injected` is intentionally unused by this adapter. * single source of truth for merging headers into every response — so `handle()`'s own `injected`
* is intentionally unused by this adapter.
*/ */
function createRequestHandler(cfg: HandlerConfig) { function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, maxBody, trustProxy } = cfg; const { routes, bus, opts, trustProxy } = cfg;
// Built once per server, not once per request — see `BodyReader`.
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`
const url = req.url ?? '/'; // would be an `unhandledRejection` — and under Node's default mode, the end of the process.
const path = url.split('?')[0]; // Caught here, at the one place every request passes through (#108).
const method = req.method ?? 'GET'; 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 // Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead. // (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy); const secure = deriveSecure(req, trustProxy);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; // Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers);
// One computation for the whole request: this object is patched into every response below, and
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
// `cors.origins` may be a predicate with a network call in it.
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected); patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily if (writeProbe(req, res, opts)) return;
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
// Mirror handle()'s own preflight/route-match decision here, so we only read the body let result: HandleResult | Preflight;
// (below) for a request that actually reaches a route handler — matching prior behaviour. let acquired = false;
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']); const watching = watchingRequests(bus);
let matched: ReturnType<typeof resolveRoute>; const startedAt = watching ? performance.now() : 0;
try { try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path)); if (!gate.acquire()) {
} catch { if (watching)
matched = undefined; // handle() owns the standard 400 envelope and injected headers emitShedPair(
} bus,
{
method: req.method ?? 'GET',
url: req.url ?? '/',
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
let body: unknown; res.writeHead(503, {
'content-type': 'application/json',
if (matched) { 'retry-after': '1',
const acquired = await acquireBody(req, matched, opts, maxBody); connection: 'close',
});
if ('fail' in acquired) { res.end(JSON.stringify({ error: 'Service Unavailable' }));
res.writeHead(acquired.fail.status, acquired.fail.headers);
res.end(acquired.fail.body);
return; return;
} }
body = acquired.body; // Both the flag and the listener are skipped when no budget is configured, which is most
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
// with nothing on the other side of it.
if (gate.limited) {
acquired = true;
res.once('close', () => {
if (!acquired) return;
acquired = false;
gate.release();
});
}
result = await handle(
currentRoutes(routes), // once per request, see buildFetch
opts,
{
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
resolveIp: nodeIp,
},
injected,
);
} finally {
if (acquired) {
acquired = false;
gate.release();
}
} }
const result = await handle(routes, opts, { const written = writeResult(req, res, result, { opts, bus, correlation });
method, if (written) await written;
url, }
headers: req.headers,
body,
secure,
ip: deriveIp(req, trustProxy),
});
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
return;
}
res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body);
};
} }
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */ /**
async function acquireBody( * Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16).
* Module scope rather than inside `serve`, whose closure would charge every branch here again.
*
* Deliberately not `async`, like `handle()`: a buffered response without compression is written
* synchronously and returns nothing to await, so the common request allocates no promise here.
* Only a stream, or a compressed body, returns one.
*/
function writeResult(
req: http.IncomingMessage, req: http.IncomingMessage,
matched: MatchedRoute, res: http.ServerResponse,
opts: HttpOptions | undefined, result: HandleResult | Preflight,
maxBody: number, ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
): Promise<{ body: unknown } | BodyFailure> { ): Promise<void> | undefined {
let buf: Buffer | undefined; if ('preflight' in result) {
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default res.writeHead(204, result.preflight);
res.end();
return undefined;
}
const compression = ctx.opts?.compression;
if (!compression) return writeOutcome(res, result.outcome, ctx);
const decided = compressOutcome(compression, { method: req.method ?? 'GET', headers: req.headers }, result.outcome);
return decided instanceof Promise
? decided.then((outcome) => writeOutcome(res, outcome, ctx))
: writeOutcome(res, decided, ctx);
}
/** Pipes a stream (returning its promise) or writes a buffered outcome in one go (returning nothing). */
function writeOutcome(
res: http.ServerResponse,
outcome: NeutralOutcome,
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
): Promise<void> | undefined {
if (outcome.kind === 'stream') return pipeStream(res, outcome, ctx.bus, ctx.opts?.streams, ctx.correlation);
res.writeHead(outcome.status, outcome.headers);
res.end(outcome.body);
return undefined;
}
/**
* Answers a health probe and returns true, or returns false for any other request. Runs before the
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
* event sees one. Written through the patched writeHead, so the security headers still land.
*/
function writeProbe(req: http.IncomingMessage, res: http.ServerResponse, opts: HttpOptions | undefined): boolean {
const probe = opts?.health && answerProbe(req.method ?? 'GET', req.url ?? '/', opts.health);
if (!probe) return false;
res.writeHead(probe.status, probe.headers);
res.end(probe.body);
return true;
}
/**
* 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 { try {
buf = await readBody(req, bodyLimit); res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
} catch (error) { res.end('{"error":"Internal Server Error"}');
const rendered = renderError(error, errorRequest(req), opts?.onError); } catch {
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } }; res.destroy();
} }
}
const contentType = String(req.headers['content-type'] ?? ''); /**
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; * The Node half of body acquisition: bytes off the socket, and the over-limit answer.
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; *
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts); * `readBody` enforces the limit against the running total as chunks arrive, so an oversized upload
* is rejected without being buffered. `connection: close` on that response is load-bearing — it
* stops the remainder of the upload from continuing to arrive on a kept-alive socket.
*/
function readRequestBytes(
source: unknown,
limit: number,
opts: HttpOptions | undefined,
): Promise<{ bytes: Buffer | undefined } | BodyFailure> {
const req = source as http.IncomingMessage;
if ('error' in parsed) { return readBodyBytes(req, limit).then(
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError); (bytes) => ({ bytes }),
return { fail: rendered }; (error: unknown) => {
} const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
return { body: parsed.body }; },
);
} }
/** /**
@@ -180,49 +316,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined; const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged = mergeInjectedHeaders(handlerHeaders, injected); const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
}; };
} }
/** 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 };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Bounds a graceful shutdown by a deadline, forcing whatever is left.
*
* Shared by the Deno and Bun adapters so the two cannot drift into different meanings of the same
* `timeoutMs`, and shaped like the Node path in `closeApp`: try to drain, and if the deadline
* passes first, force the remainder and resolve anyway.
*
* The race is the point, and it is not paranoia. Both runtimes' force calls were measured against
* a handler that never resolves and returned immediately, but `Bun.stop(true)` was also measured
* waiting out a handler with a pending timer — same call, ~2s, because it awaits pending async
* work rather than only open connections. Awaiting the force call would therefore inherit exactly
* the unbounded wait the deadline exists to prevent. Resolving on our own timer means `close()`
* returns within `timeoutMs` whatever either runtime decides to wait for.
*
* @param graceful Drain in flight work. Unbounded — that is what the deadline is for.
* @param force Stop waiting and drop what is left. Fire-and-forget; its promise is not awaited.
*/
export function closeWithDeadline(
graceful: () => Promise<void>,
force: () => void,
timeoutMs: number,
onTimeout?: (timeoutMs: number) => void,
): Promise<void> {
return new Promise<void>((resolve) => {
let settled = false;
// Armed before `finish` exists, and deliberately: setTimeout cannot invoke its callback
// synchronously, so `finish` is always assigned by the time this can reach it. The reverse
// ordering would rest on when the runtime's own promise settles. Mirrors `closeApp`.
const timer = setTimeout(() => {
if (settled) return;
onTimeout?.(timeoutMs);
force();
finish();
}, timeoutMs);
timer.unref?.();
const finish = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
// A graceful path that rejects still has to end the shutdown: the deadline covers a slow
// close, not a broken one, and leaving close() pending forever is the worse failure. Called
// inside `then` so a graceful path that throws before returning its promise counts as a
// rejection too, rather than rejecting close() and leaving the timer to force a closed server.
void Promise.resolve().then(graceful).then(finish, finish);
});
}
+125
View File
@@ -0,0 +1,125 @@
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
import type { Logger } from '../logger';
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
type Signal = (typeof SIGNALS)[number];
interface SignalApi {
runtime: string;
on(signal: Signal, handler: () => void): void;
off(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface DenoSignals {
addSignalListener(signal: Signal, handler: () => void): void;
removeSignalListener(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface ProcessSignals {
on(signal: Signal, handler: () => void): unknown;
off?(signal: Signal, handler: () => void): unknown;
removeListener?(signal: Signal, handler: () => void): unknown;
exit(code: number): void;
}
/**
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
* listener holds the process open until it is removed. Node and Bun share `process`.
*/
function signalApi(): SignalApi | undefined {
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
if (typeof deno?.addSignalListener === 'function')
return {
runtime: 'deno',
on: (signal, handler) => deno.addSignalListener(signal, handler),
off: (signal, handler) => deno.removeSignalListener(signal, handler),
exit: (code) => deno.exit(code),
};
const proc = (globalThis as { process?: ProcessSignals }).process;
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
const remove = proc.off ?? proc.removeListener;
return {
runtime: 'node',
on: (signal, handler) => void proc.on(signal, handler),
off: (signal, handler) => void remove?.call(proc, signal, handler),
exit: (code) => proc.exit(code),
};
}
return undefined;
}
/**
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
* the process from exiting on its own.
*
* The close is expected to unregister first thing, which leaves a **second signal falling through
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
*
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
* not a clean one and an orchestrator should be told.
*/
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
const api = signalApi();
if (!api) {
logger.warn(
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
);
return () => {};
}
const registered: Array<[Signal, () => void]> = [];
const remove = (): void => {
while (registered.length) {
const [signal, handler] = registered.pop()!;
api.off(signal, handler);
}
};
for (const signal of SIGNALS) {
const handler = (): void => {
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
void close().then(
() => api.exit(0),
(error: unknown) => {
logger.error(`shutdown failed after ${signal}`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
api.exit(1);
},
);
};
try {
api.on(signal, handler);
registered.push([signal, handler]);
} catch (error) {
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
// platform does have beats refusing to start over the one it does not.
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
}
}
return remove;
}
+36 -17
View File
@@ -2,7 +2,10 @@ import type http from 'http';
import { once } from 'events'; import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata'; import type { Transport } from '../metadata';
import type { Bus } from '../bus'; import type { Bus, Correlation } from '../bus';
import type { NeutralOutcome } from './core';
import { frameSink } from './compression';
import { releaseIterator } from '../channel';
const PING_MS = 15_000; const PING_MS = 15_000;
@@ -27,29 +30,41 @@ export function pickEncoder(transport: Transport, accept: string): StreamEncoder
return pick(accept); return pick(accept);
} }
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ /**
* Pipes a stream outcome to the response, with keep-alive pings and backpressure handling. With
* `outcome.encoding` set (CARD-16), frames go through a `node:zlib` stream piped into `res`, flushed
* after every frame, error frame and ping, so each event is decodable on arrival.
*/
export async function pipeStream( export async function pipeStream(
res: http.ServerResponse, res: http.ServerResponse,
stream: AsyncIterable<unknown>, outcome: Extract<NeutralOutcome, { kind: 'stream' }>,
encoder: StreamEncoder,
bus?: Bus, bus?: Bus,
name = '',
streams?: Set<() => void>, streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> { ): Promise<void> {
res.writeHead(200, encoder.headers); const { stream, encoder, route: name } = outcome;
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
// is always the route pattern, never the concrete path the request events can carry — but a
// consumer following the documented contract labels on `route` and would otherwise find it
// absent on the longest-lived thing the server does. See `EventPayload.name`.
const trace = { name, route: name, ...correlation };
res.writeHead(200, outcome.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
bus?.emit('stream:open', { name }); bus?.emit('stream:open', trace);
const sink = frameSink(res, outcome.encoding);
const iterator = stream[Symbol.asyncIterator](); const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined; let ping: ReturnType<typeof setInterval> | undefined;
if (encoder.ping) { if (encoder.ping) {
ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping = setInterval(() => sink.write(encoder.ping!()), PING_MS);
ping.unref?.(); ping.unref?.();
} }
const stop = () => { const stop = () => {
if (ping) clearInterval(ping); if (ping) clearInterval(ping);
void Promise.resolve(iterator.return?.()).catch(() => {}); // A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
sink.destroy();
releaseIterator(iterator);
}; };
res.on('close', stop); res.on('close', stop);
@@ -64,25 +79,29 @@ export async function pipeStream(
streams?.add(closer); streams?.add(closer);
const onClose = once(res, 'close'); const onClose = once(res, 'close');
// `next()` is raced against the disconnect (GitHub #40): an idle source's may never settle, and
// waiting on it kept this loop and its closer alive long after the client had gone.
const gone = onClose.then(() => undefined);
try { try {
while (true) { while (true) {
const { value, done } = await iterator.next(); const step = await Promise.race([iterator.next(), gone]);
if (done) break; if (!step || step.done) break;
const { value } = step;
if (!res.write(encoder.encode(value))) { if (!sink.write(encoder.encode(value))) {
await Promise.race([once(res, 'drain'), onClose]); await Promise.race([once(sink.drains, 'drain'), onClose]);
if (res.destroyed) break; // let finally clean up if (res.destroyed) break; // let finally clean up
} }
} }
} catch (err) { } catch (err) {
bus?.emit('stream:error', { name, error: err }); bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err); const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame); if (frame && !res.writableEnded) sink.write(frame);
} finally { } finally {
if (ping) clearInterval(ping); if (ping) clearInterval(ping);
streams?.delete(closer); streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end(); if (!res.writableEnded && !res.destroyed) sink.end();
bus?.emit('stream:close', { name }); bus?.emit('stream:close', trace);
} }
} }
+66 -1
View File
@@ -1,21 +1,60 @@
import type { Transport } from '../metadata'; import type { Transport } from '../metadata';
import type { HealthProbe } from './health';
import type { PipelineResult } from '../pipeline'; import type { PipelineResult } from '../pipeline';
import type { ErrorRenderer } from '../transformers'; import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views'; import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { CompressionConfig } from './compression';
/** Per-request size and timeout ceilings applied by the server. */ /** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits { export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000 maxBodyBytes?: number; // default 1_000_000
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
requestTimeoutMs?: number; // default 30_000 requestTimeoutMs?: number; // default 30_000
headersTimeoutMs?: number; // default 10_000 headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000 keepAliveTimeoutMs?: number; // default 5_000
maxParts?: number; // default 1000 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. */ /** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
export interface HttpOptions { export interface HttpOptions {
/**
* Lifecycle events go here. Carried on the options rather than as a parameter so `handle()` —
* the one place both the Node and Fetch adapters meet — can emit without either adapter growing
* a separate channel for it.
*/
bus?: Bus;
/** Where this server writes diagnostics. Optional because `createHttpServer` takes no options at all in tests. */
logger?: Logger;
limits?: RequestLimits; limits?: RequestLimits;
streams?: Set<() => void>; streams?: Set<() => void>;
tls?: TlsOptions; tls?: TlsOptions;
@@ -25,6 +64,15 @@ export interface HttpOptions {
bodyDuplicates?: 'array' | 'last'; bodyDuplicates?: 'array' | 'last';
onError?: ErrorRenderer; onError?: ErrorRenderer;
static?: StaticResolver; static?: StaticResolver;
/**
* Answers `/__live__` and `/__ready__` ahead of the gate and the route table (`createApp({ health })`).
* Absent when health is off, so no path is intercepted.
*/
health?: HealthProbe;
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
etag?: boolean;
/** Resolved `createApp({ compression })`; absent when compression is off. */
compression?: CompressionConfig;
} }
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
@@ -37,6 +85,10 @@ export type RouteHandler = (req: {
body: unknown; body: unknown;
protocol: 'http' | 'https'; protocol: 'http' | 'https';
ip: string; ip: string;
/** Correlates every lifecycle event this request emits; see `correlateRequest` in `./core`. */
requestId: string;
/** An incoming `traceparent`, carried verbatim for an exporter to interpret. */
traceId?: string;
}) => Promise<PipelineResult>; }) => Promise<PipelineResult>;
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */ /** A registered HTTP route: method, path pattern, streaming transport, and handler. */
@@ -50,6 +102,13 @@ export interface RouteDef {
maxParts?: number; // per-route override of the server's multipart maxParts maxParts?: number; // per-route override of the server's multipart maxParts
} }
/**
* A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes
* a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes
* a new array, so a request sees the whole old table or the whole new one.
*/
export type RouteTable = RouteDef[] | (() => RouteDef[]);
/** Result of matching a request path against a route: extracted params plus the matched definition. */ /** Result of matching a request path against a route: extracted params plus the matched definition. */
export interface MatchedRoute { export interface MatchedRoute {
params: Record<string, string>; params: Record<string, string>;
@@ -73,6 +132,12 @@ export interface WsRouteDef {
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ /** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
export interface MeshControl { export interface MeshControl {
path: string; 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 * 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. * consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
+320 -106
View File
@@ -1,35 +1,99 @@
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, type HandleResult } from './core'; import type { Bus, Correlation } from '../bus';
import { mergeInjectedHeaders } from './headers'; import { createRequestGate } from './request-gate';
import { parseRequestBody } from './server'; import {
import { normalizeRequestPath, resolveRoute } from './router'; handle,
computeInjected,
correlateRequest,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types'; import type { RouteTable, HttpOptions } from './types';
import { answerProbe } from './health';
import { currentRoutes } from './router';
import { compressOutcome, compressWebStream } from './compression';
import type { NeutralOutcome } from './core';
import { releaseIterator } from '../channel';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */ /**
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> { * Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
* cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the
* lifecycle of a stream must not depend on which adapter is serving it.
*/
export function asReadableStream(
source: AsyncIterable<unknown>,
encoder: StreamEncoder,
bus?: Bus,
name = '',
correlation: Correlation = {},
): ReadableStream<Uint8Array> {
const iterator = source[Symbol.asyncIterator](); const iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder(); const te = new TextEncoder();
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
// says label on `route`, so both are carried.
const trace = { name, route: name, ...correlation };
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
// its own path — so the close is latched rather than emitted from each of the three exits.
let closed = false;
// Settles on `cancel`, so a `pull` waiting on an idle source's `next()` stops waiting (GitHub #40).
let cancelled!: (step: undefined) => void;
const gone = new Promise<undefined>((resolve) => (cancelled = resolve));
const close = (): void => {
if (closed) return;
closed = true;
bus?.emit('stream:close', trace);
};
return new ReadableStream<Uint8Array>({ return new ReadableStream<Uint8Array>({
start() {
bus?.emit('stream:open', trace);
},
async pull(controller) { async pull(controller) {
try { try {
const { value, done } = await iterator.next(); const step = await Promise.race([iterator.next(), gone]);
if (!step) return;
const { value, done } = step;
if (done) { if (done) {
close();
controller.close(); controller.close();
return; return;
} }
const encoded = encoder.encode(value); controller.enqueue(frame(encoder.encode(value)));
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
controller.enqueue(bytes);
} catch (err) { } catch (err) {
controller.error(err); bus?.emit('stream:error', { ...trace, error: err });
const errorFrame = encoder.encodeError(err);
close();
// Framed and closed cleanly, which is what the Node adapter does and the better answer for
// the client: an SSE consumer that received an `error` event knows what happened, where a
// transport-level failure is indistinguishable from the connection simply dropping.
// `controller.error` is kept for the encoder that has no error frame to offer, because
// then breaking the stream is the only signal left.
if (errorFrame === null) {
controller.error(err);
return;
}
controller.enqueue(frame(errorFrame));
controller.close();
} }
}, },
async cancel() { // Not awaited: `return()` on a generator still waiting in `next()` would hold the cancel open.
await iterator.return?.(); cancel() {
close();
cancelled(undefined);
releaseIterator(iterator);
}, },
}); });
} }
@@ -44,130 +108,280 @@ function headersToRecord(headers: Headers): Record<string, string> {
} }
/** /**
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the * The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where *
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures * Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* (413/400/501) carry them too. * 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 errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response { function readFetchBytes(
const headers = mergeInjectedHeaders(rendered.headers, injected); source: unknown,
return new Response(rendered.body, { status: rendered.status, headers }); limit: number,
opts: HttpOptions | undefined,
): MaybePromise<{ bytes: Buffer | undefined } | BodyFailure> {
const request = source as Request;
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
// 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);
}
// A well-formed declared length within the limit bounds the body already: the runtime's HTTP parser
// frames it by that header, so `arrayBuffer()`, native in Bun, Deno and workerd, cannot overrun.
// The reader loop below measured 4x slower on a Bun JSON POST. `byteLength` is still checked, for
// a `Request` built in user code whose header and body disagree.
if (/^\d+$/.test(request.headers.get('content-length') ?? '')) {
return request
.arrayBuffer()
.then((buffer) =>
buffer.byteLength > limit
? tooLarge(request, opts)
: { bytes: buffer.byteLength === 0 ? undefined : Buffer.from(buffer) },
);
}
// 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 and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node * Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure. * 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 acquireFetchBody( async function readBounded(
request: Request, reader: ReadableStreamDefaultReader<Uint8Array>,
matched: MatchedRoute, limit: number,
headers: Record<string, string>, ): Promise<Buffer | undefined | null> {
path: string, const chunks: Uint8Array[] = [];
maxBody: number, let total = 0;
opts: HttpOptions | undefined,
injected: Record<string, string>,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
if (request.body) { for (;;) {
const arrayBuffer = await request.arrayBuffer(); const { done, value } = await reader.read();
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; if (done) break;
if (arrayBuffer.byteLength > bodyLimit) { total += value.byteLength;
return {
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected), if (total > limit) {
}; reader.cancel().catch(() => {});
return null;
} }
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); chunks.push(value);
} }
const contentType = headers['content-type'] ?? ''; return total === 0 ? undefined : Buffer.concat(chunks, total);
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
return {
response: errorResponse(
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
injected,
),
};
}
return { body: parsed.body };
} }
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ /** The over-limit answer, shared by the declared-length check and the stream count. */
function outcomeToResponse(result: HandleResult): Response { function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>; // 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);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
if (result.outcome.kind === 'stream') { /**
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); * Whatever the host runtime's `Response` accepts as a body. Derived from the constructor rather
* than written as `BodyInit`, because that name is not global under this `lib` (`es2020` plus
* `@types/node`) even though `Response` itself is — and Deno spells the same idea from its own lib.
*/
type ResponseBody = ConstructorParameters<typeof Response>[0];
/**
* Narrows a buffered body to something the runtime's `Response` accepts.
*
* A Node `Buffer` is a `Uint8Array` at runtime, so every runtime here takes one — but its declared
* backing store is `ArrayBufferLike`, which admits `SharedArrayBuffer`, and `BodyInit` accepts only
* `ArrayBuffer`-backed views. Deno's lib therefore rejects it outright: this is the `app.fetch` path,
* so the mismatch reaches Deno, Bun and edge alike. Node never allocates a Buffer over a
* `SharedArrayBuffer`, which is what makes the assertion on the backing store safe to state.
*
* `byteOffset`/`byteLength` are load-bearing, not defensive. `Buffer.from` and `Buffer.allocUnsafe`
* hand back a window into a shared 8 KB pool, so re-viewing the backing store without them yields
* the whole pool — neighbouring allocations included. Today the only Buffer reaching here comes from
* `fs.promises.readFile`, which returns an exactly-sized allocation, so nothing currently trips that.
* `StaticHit.body` is typed `Buffer` though, and a pooled one is a correct value for it.
*
* Re-viewing rather than copying: this is the buffered-response path, and a copy per response would
* be a real cost on the runtimes that have no other adapter.
*/
export function toBodyInit(body: string | Buffer): ResponseBody {
if (typeof body === 'string') return body;
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
}
/** Converts an outcome (already through `compressOutcome`) into a web `Response`, buffered or streamed. */
function outcomeToResponse(
outcome: NeutralOutcome,
injected: Record<string, string>,
bus?: Bus,
correlation: Correlation = {},
): Response {
const headers = toWebHeaders(mergeInjectedHeaders(outcome.headers, injected));
if (outcome.kind === 'stream') {
const frames = asReadableStream(outcome.stream, outcome.encoder, bus, outcome.route, correlation);
return new Response(outcome.encoding ? compressWebStream(frames, outcome.encoding) : frames, { headers });
} }
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body; const body = [204, 205, 304].includes(outcome.status) ? null : toBodyInit(outcome.body);
return new Response(body, { status: result.outcome.status, headers }); return new Response(body, { status: outcome.status, headers });
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(request: Request, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return (request.headers.get('x-forwarded-for') ?? '').split(',')[0].trim();
}
/**
* `ctx.ip` on the fetch path, for `NeutralRequest.resolveIp`. Mirrors Node's `deriveIp`
* (src/http/request.ts): only trust `x-forwarded-for` when the proxy is trusted, and take its first
* hop, because 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 ''. Ahead of
* both, under `trustProxy` only: the address the edge adapter read from `cf-connecting-ip`.
* Cloudflare sets that header itself, while XFF can carry hops the client supplied, so on the edge
* it wins (CARD-23).
*/
function fetchIp(source: unknown, opts: HttpOptions | undefined): string {
const request = source as Request;
return trustedProxyClient(request, opts?.trustProxy) || forwardedFor(request, opts) || peerOf(request);
} }
/** /**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the * describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed). * calls once a route matches, and converts the outcome to a `Response` (buffered or streamed).
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/ */
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; // Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (request: Request): Promise<Response> => { return async (request: Request): Promise<Response> => {
const url = new URL(request.url); const url = new URL(request.url);
const path = url.pathname + url.search; const path = url.pathname + url.search;
const headers = headersToRecord(request.headers); const headers = headersToRecord(request.headers);
let matched: ReturnType<typeof resolveRoute>; // Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(headers);
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so a preflight — the one response
// this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers });
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(opts?.bus);
const startedAt = watching ? performance.now() : 0;
try { try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname)); if (!gate.acquire()) {
} catch { if (watching)
matched = undefined; // handle() renders the shared 400 response without reading a body emitShedPair(
opts!.bus!,
{
method: request.method,
url: path,
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: toWebHeaders(
mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
),
});
}
acquired = gate.limited;
result = await handle(
// Read once per request: a mesh teacup swaps its table when peers come and go, and one
// request must route and build `Allow` against the same table (CARD-19).
currentRoutes(routes),
opts,
{
...correlation,
method: request.method,
url: path,
headers,
readBody,
source: request,
secure,
resolveIp: fetchIp,
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
injected,
);
} finally {
// Release when routing/handling finishes, not when a returned stream finishes.
// Long-lived streams therefore do not permanently consume the request budget.
if (acquired) gate.release();
} }
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
// would have installed before body acquisition.
const injected = computeInjected(opts, { secure, headers });
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
const result = await handle(routes, opts, {
method: request.method,
url: path,
headers,
body,
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()
: '',
});
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch // so picks up the same authoritative security headers `injected` carries.
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
if ('preflight' in result) { if ('preflight' in result) {
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) }); return new Response(null, {
status: 204,
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
});
} }
return outcomeToResponse(result); const decided = compressOutcome(opts?.compression, { method: request.method, headers }, result.outcome);
return decided instanceof Promise
? decided.then((outcome) => outcomeToResponse(outcome, injected, opts?.bus, correlation))
: outcomeToResponse(decided, injected, opts?.bus, correlation);
}; };
} }
/**
* Answers a health probe through the Fetch API, or returns `undefined` for any other request (or when
* `health` is off). `app.fetch` calls this before awaiting the boot, which is what lets `/__ready__`
* report `booting` at all, and before the gate and `handle()`, for the same reasons as the Node adapter.
*/
export function answerFetchProbe(request: Request, opts: HttpOptions | undefined): Response | undefined {
if (!opts?.health) return undefined;
const url = new URL(request.url);
const probe = answerProbe(request.method, url.pathname + url.search, opts.health);
if (!probe) return undefined;
const injected = computeInjected(opts, {
secure: url.protocol === 'https:',
headers: headersToRecord(request.headers),
});
return new Response(probe.body || null, {
status: probe.status,
headers: mergeInjectedHeaders(probe.headers, injected) as Record<string, string>,
});
}
+56 -9
View File
@@ -1,6 +1,7 @@
import { channel } from '../channel'; import { channel, type Channel } from '../channel';
import type { App } from '../app/types'; 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';
/** /**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
@@ -9,6 +10,7 @@ import type { WsRequest, WsSocket } from './ws-core';
*/ */
const decoder = new TextDecoder(); const decoder = new TextDecoder();
const CONNECTING = 0; // WebSocket.CONNECTING
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient 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()). */ /** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
@@ -38,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). */ /** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
export interface EventfulSocket { export interface EventfulSocket {
readonly readyState: number; 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; send(data: string): void;
close(code?: number, reason?: string): void; close(code?: number, reason?: string): void;
addEventListener( addEventListener(
@@ -68,7 +72,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
ac.abort(); 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);
},
});
} }
/** /**
@@ -77,8 +92,8 @@ export function eventSocket(host: EventfulSocket): WsSocket {
* callers never have to guard an already-closed socket. * callers never have to guard an already-closed socket.
*/ */
export function neutralSocket( export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void }, host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>, inbound: Channel<unknown>,
ac: AbortController, ac: AbortController,
): WsSocket { ): WsSocket {
return { return {
@@ -90,6 +105,7 @@ export function neutralSocket(
send: (data) => { send: (data) => {
host.send(data); host.send(data);
}, },
drained: () => pollDrained(host, ac.signal),
close: (code, reason) => { close: (code, reason) => {
try { try {
host.close(code, reason); host.close(code, reason);
@@ -107,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. */ /** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
export type SocketCtor = new (url: string) => EventfulSocket; export type SocketCtor = new (url: string) => EventfulSocket;
/** /**
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and * The WebSocket client implementation: the platform global where it exists, else the `ws`
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global. * 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, * 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 * so one bridge covers both. That is verified rather than assumed: `ws` implements the
@@ -123,8 +171,7 @@ export function loadWebSocketCtor(): SocketCtor {
if (platform) return platform; if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<SocketCtor>('ws');
return require('ws') as SocketCtor;
} }
/** /**
+353 -6
View File
@@ -1,7 +1,9 @@
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import { CHANNEL_TAP, releaseIterator, type TappableChannel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router'; 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). */ /** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
export interface WsRequest { export interface WsRequest {
@@ -19,6 +21,337 @@ export interface WsSocket {
send(data: string): void; send(data: string): void;
close(code?: number, reason?: string): void; close(code?: number, reason?: string): void;
terminate(): 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;
/** The tail of each socket's {@link sendWhenDrained} queue. */
const sendQueues = new WeakMap<WsSocket, Promise<void>>();
/**
* Sends on `socket` in call order, each frame only once {@link WsSocket.drained} lets it (#41).
* For senders outside the outbound pump, such as concurrent mesh RPCs. Waiting one at a time is
* the point: callers that each waited on their own would all be released by the same drain and
* all send, putting one frame per caller over the mark. Queued, the buffer peaks at the mark plus
* one frame, however many callers wait.
*
* `frame` runs at send time, so a caller that settled while queued (a timeout) returns
* `undefined` and sends nothing. Nothing is sent once the socket has closed.
*/
export function sendWhenDrained(socket: WsSocket, frame: () => string | undefined): Promise<void> {
const sent = (sendQueues.get(socket) ?? Promise.resolve()).then(async () => {
if (socket.drained) await socket.drained();
if (socket.abort.aborted) return;
const data = frame();
if (data !== undefined) socket.send(data);
});
sendQueues.set(
socket,
sent.catch(() => {}),
);
return sent;
}
/** 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. `onWiden` runs
* then too, for an adapter that holds a bound of its own until that point.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
widened?: InboundLimits,
onWiden?: () => void,
): 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);
onWiden?.();
},
},
}),
}) 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. */ /** Finds the first ws route whose pattern matches `path`, capturing its params. */
@@ -64,9 +397,18 @@ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer:
return { 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> { async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
while (true) { 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(); const { value, done } = await iterator.next();
if (done) break; if (done) break;
if (!socket.isOpen) break; if (!socket.isOpen) break;
@@ -109,15 +451,20 @@ export async function runWsConnection(
): Promise<void> { ): Promise<void> {
const { closer } = trackConnection(socket, streams); const { closer } = trackConnection(socket, streams);
const name = route.def.pattern; const name = route.def.pattern;
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
// keeps one identity per connection instead of one per emitter.
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
let iterator: AsyncIterator<unknown> | undefined; let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => { const onAbort = () => {
streams?.delete(closer); streams?.delete(closer);
void Promise.resolve(iterator?.return?.()).catch(() => {}); releaseIterator(iterator);
}; };
socket.abort.addEventListener('abort', onAbort, { once: true }); socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name }); bus?.emit('stream:open', trace);
try { try {
const outbound = await route.def.open({ const outbound = await route.def.open({
@@ -129,9 +476,9 @@ export async function runWsConnection(
iterator = outbound[Symbol.asyncIterator](); iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator); await pumpOutbound(socket, iterator);
} catch (err) { } catch (err) {
bus?.emit('stream:error', { name, error: err }); bus?.emit('stream:error', { ...trace, error: err });
closeOnError(socket, err); closeOnError(socket, err);
} finally { } finally {
bus?.emit('stream:close', { name }); bus?.emit('stream:close', trace);
} }
} }
+163 -26
View File
@@ -1,24 +1,37 @@
import type http from 'http'; import type http from 'http';
import { channel } from '../channel'; import { channel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import {
import type { WsRouteDef, MeshControl } from './types'; runWsConnection,
matchWsRoute,
trackUntil,
boundInbound,
controlBounds,
wsMessageBytes,
HELLO_FRAME_BYTES,
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';
import { MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null { function loadWss(): any | null {
try { try {
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
// support don't fail. When absent this throws and we fall back to null (501 on upgrade). // support don't fail. When absent this throws and we fall back to null (501 on upgrade).
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
return require('ws').WebSocketServer;
} catch { } catch {
return null; return null;
} }
} }
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */ /** Writes a bodyless HTTP status to the raw socket and destroys it. */
function reject501(socket: any): void { function rejectUpgrade(socket: any, status: number, text: string): void {
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
socket.destroy(); socket.destroy();
} }
@@ -31,27 +44,81 @@ function handleMeshUpgrade(
socket: any, socket: any,
head: Buffer, head: Buffer,
streams?: Set<() => void>, streams?: Set<() => void>,
limits?: RequestLimits,
): boolean { ): boolean {
if (path !== meshControl.path) return false; if (path !== meshControl.path) return false;
if (!wss) { if (!wss) {
reject501(socket); rejectUpgrade(socket, 501, 'Not Implemented');
return true; 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, and
// `capPreAuthBytes` keeps `ws` from assembling anything larger first.
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the // 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. // `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 // 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. // 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. // serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => { wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws); const lift = capPreAuthBytes(ws, socket, head);
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed, lift);
void trackUntil(neutral, meshControl.handle(neutral), streams); void trackUntil(neutral, meshControl.handle(neutral), streams);
}); });
return true; return true;
} }
/** Bytes an unauthenticated control peer may send: one hello-sized frame plus headers and a close frame. */
const PRE_AUTH_WIRE_BYTES = HELLO_FRAME_BYTES + 1024;
/**
* Closes a control peer that sends more than a hello's worth of bytes before its hello is accepted.
* `maxPayload` is set once per `WebSocketServer`, and the control channel's must fit an
* authenticated RPC (about 7 MB at the defaults), so without this an unauthenticated peer could
* make `ws` assemble a frame that size before `boundInbound` sees it and refuses it. This counts
* raw socket bytes instead, so the peer is closed `1009` about 64 KiB in. Returns the function that
* stops counting, for when the peer authenticates.
*
* Installed in the `handleUpgrade` callback, after `ws` has attached its own `data` listener: a
* listener added earlier would switch the socket to flowing mode and lose chunks `ws` never saw.
*/
function capPreAuthBytes(ws: any, socket: any, head: Buffer): () => void {
let received = head.length;
const count = (chunk: Buffer) => {
received += chunk.length;
if (received > PRE_AUTH_WIRE_BYTES) {
socket.off('data', count);
// 1009, as every other runtime closes an oversized frame. Paused, so `ws` reads nothing more
// of it; `end` still flushes the close frame. `ws` destroys the socket at its close timeout.
ws.close(1009, 'message too big');
socket.pause();
socket.end();
}
};
socket.on('data', count);
return () => socket.off('data', count);
}
/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */
function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void {
if (!wss) {
rejectUpgrade(socket, 501, 'Not Implemented');
return;
}
wss.handleUpgrade(req, socket, head, (ws: { close(code: number, reason: string): void }) =>
ws.close(1008, MESH_CONTROL_DISABLED_REASON),
);
}
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */ /** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
function nodeWsRequest(req: http.IncomingMessage): WsRequest { function nodeWsRequest(req: http.IncomingMessage): WsRequest {
return { return {
@@ -66,10 +133,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
function nodeSocket(ws: any): WsSocket { function nodeSocket(ws: any): WsSocket {
const inbound = channel<unknown>(); const inbound = channel<unknown>();
const ac = new AbortController(); 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('message', (data: Buffer) => inbound.push(data.toString()));
ws.on('close', () => { ws.on('close', () => {
inbound.close(); inbound.close();
ac.abort(); ac.abort();
release();
}); });
ws.on('error', (err: unknown) => inbound.fail(err)); ws.on('error', (err: unknown) => inbound.fail(err));
return { return {
@@ -78,7 +156,8 @@ function nodeSocket(ws: any): WsSocket {
get isOpen() { get isOpen() {
return ws.readyState === 1; // 1 = OPEN 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) => { close: (code, reason) => {
try { try {
ws.close(code, reason); ws.close(code, reason);
@@ -97,29 +176,87 @@ export function attachWs(
bus?: Bus, bus?: Bus,
meshControl?: MeshControl, meshControl?: MeshControl,
streams?: Set<() => void>, streams?: Set<() => void>,
limits?: RequestLimits,
): void { ): void {
if (wsRoutes.length === 0 && !meshControl) return; if (wsRoutes.length === 0 && !meshControl) return;
const WebSocketServer = loadWss(); 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) => { 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.
const route = matchWsRoute(wsRoutes, path); try {
routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
if (!route) { } catch {
socket.destroy(); if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
return; else socket.destroy();
} }
});
}
if (!wss) { /** What every upgrade on one server shares. */
reject501(socket); interface UpgradeEnv {
return; 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;
}
wss.handleUpgrade(req, socket, head, (ws: any) => { /** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); 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;
// The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno,
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
// ws route table: the boot already refuses any route that claims this path.
if (path === MESH_CONTROL_PATH) {
refuseMeshUpgrade(wss, req, socket, head);
return;
}
const route = matchWsRoute(wsRoutes, path);
if (!route) {
rejectUpgrade(socket, 404, 'Not Found');
return;
}
if (!wss) {
rejectUpgrade(socket, 501, 'Not Implemented');
return;
}
wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
}); });
} }
+37 -10
View File
@@ -5,12 +5,20 @@
*/ */
import 'reflect-metadata'; import 'reflect-metadata';
/** Package version, replaced at publish time. */ /**
export const VERSION = '26.8.0-beta.0'; * Package version. Kept in step with `package.json` and `deno.json` by hand, and pinned to them by
* `test/package-metadata.test.ts`.
*
* It used to say it was "replaced at publish time", which nothing ever did — not `tsup`, not
* `stage.yml`, not `release.yml`, which only ever *reads* the version out of `package.json`. So the
* constant drifted two releases behind while the comment explained why it could not, and the only
* test touching it checked the CalVer shape, which a stale version satisfies perfectly.
*/
export const VERSION = '26.9.0-beta.2';
// Application // Application
export { createApp } from './app'; export { createApp } from './app';
export type { App, InspectLine, Explain, MeshConfig } from './app'; export type { App, AppOptions, InspectLine, Explain, ExplainNode, MeshConfig } from './app';
// Graph visualization // Graph visualization
export { toMermaid, toDOT } from './graph-viz'; export { toMermaid, toDOT } from './graph-viz';
@@ -40,8 +48,10 @@ export {
Options, Options,
Html, Html,
} from './metadata'; } from './metadata';
export type { Transport, HttpMethod } from './metadata'; export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin } from './plugin'; export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals // Transformers & error signals
export { JsonTransformer } from './transformers'; export { JsonTransformer } from './transformers';
@@ -54,31 +64,48 @@ export {
NotModified, NotModified,
ValidationError, ValidationError,
TransportMismatchError, TransportMismatchError,
HTTP_ERROR,
VALIDATION_ERROR,
isHttpError,
isValidationError,
} from './signals'; } from './signals';
export type { HttpErrorLike } from './signals';
// Bus & flow // Bus & flow
export { Bus } from './bus'; export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow'; export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators // Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec } from './params'; export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger';
// Streaming // Streaming
export { channel, isAsyncIterable } from './channel'; export { channel, isAsyncIterable } from './channel';
export type { Channel } from './channel'; export type { Channel } from './channel';
export { Rooms } from './rooms'; export { Rooms } from './rooms';
export { sseEncoder, ndjsonEncoder } from './encoders'; export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder } from './encoders'; export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation // HTTP, security & validation
export type { RequestLimits } from './http'; export type { RequestLimits } from './http';
export type { WsRequest, WsSocket } from './http/ws-core';
export type { CompressionOptions } from './http/compression';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart'; export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema'; export type { StandardSchemaV1 } from './standard-schema';
// Mesh // Mesh — experimental (`createApp({ experimental: true })`): outside the API freeze, may change in a minor.
export { connectLink } from './mesh/link'; export { connectLink } from './mesh/link';
export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildRemote, envelopeFrom } from './mesh/teacup';
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
+74
View File
@@ -0,0 +1,74 @@
// src/lifecycle.ts — the teardown registry. Knows nothing about plugins, providers, apps or HTTP;
// the doors into it live where those things do.
import type { Logger } from './logger';
/**
* Something to run before the app goes away.
*
* Takes no arguments on purpose. State lives in the closure that registered it — a provider's
* `dispose()` already holds its own connection, and a plugin's callback already holds whatever the
* plugin built. Nothing has to cross a scope, which is what makes this a registry rather than an
* event bus: a bus solves "tell someone I do not know", and this is "run the thing I registered".
*/
export type TeardownFn = () => void | Promise<void>;
/**
* Await-aware teardown, deliberately not the {@link Bus}.
*
* `Bus.on` takes a synchronous listener and `emit` swallows failures, both so that an observer can
* never break the pipeline. A teardown needs the opposite of each: it must be awaited, and its
* failure must be visible. Same word, opposite guarantees — see D1 of the design.
*
* Bounding is deliberately *not* here. `closeApp` and `closeWithDeadline` already implement a
* deadline each, and a third implementation is how the three drift into different meanings of the
* same `timeoutMs`.
*/
export class TeardownRegistry {
private readonly callbacks: TeardownFn[] = [];
private running: Promise<void> | undefined;
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
add(fn: TeardownFn): void {
this.callbacks.push(fn);
}
/** How many callbacks are registered; lets a caller skip the whole path when nothing wants it. */
get size(): number {
return this.callbacks.length;
}
/**
* Run every callback, newest first, awaiting each.
*
* **Reverse registration order is load-bearing.** Providers register as they boot, and they boot
* in topological order, so reversing registration is what gives dependants teardown before their
* dependencies: a `cache` that needs `db` closes before the `db` it is still holding.
*
* Sequential rather than parallel, for the same reason — an order only means something if it is
* waited on.
*
* A failing callback is reported and the next one still runs. One broken teardown must not strand
* the rest or leave the process up. This mirrors `Bus`'s "a subscriber cannot break the system",
* but with the visibility `Bus` lacks: `Bus` swallows silently because no logger existed when it
* was written, and one exists now.
*
* Never throws, and never runs twice — `close()` is called twice by more real applications than
* anyone expects, and a second call must not re-close what the first one closed. A second call
* made while the first is still running gets the same promise rather than an early return: a
* caller that awaits `close()` must not move on with a connection the first call has yet to close.
*/
run(logger: Logger): Promise<void> {
this.running ??= this.drain(logger);
return this.running;
}
private async drain(logger: Logger): Promise<void> {
for (let index = this.callbacks.length - 1; index >= 0; index--) {
try {
await this.callbacks[index]();
} catch (error) {
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
}
}
}
}
+154
View File
@@ -0,0 +1,154 @@
import type { EventPayload } from './bus';
/**
* The logging contract. Four levels, because four have callers: core diagnostics are all `warn`
* today, request logging adds `info` and `error`, and the graph diagnostics add `debug`. No
* `trace`, no `fatal`, no `silent` — a level nothing emits is a decision handed to the user for
* no reason.
*/
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
/** Structured context attached to a log record. Flattened into the JSON output alongside the message. */
export type LogFields = Record<string, unknown>;
/**
* What `createApp({ logger })` accepts, and what core writes every diagnostic through.
*
* Message first, fields second, so a call reads as a sentence and the structured part stays
* optional. Bridging a `pino`- or `winston`-style logger is a four-line adapter in either
* direction; core defines the shape it needs rather than adopting anyone's.
*/
export interface Logger {
debug(message: string, fields?: LogFields): void;
info(message: string, fields?: LogFields): void;
warn(message: string, fields?: LogFields): void;
error(message: string, fields?: LogFields): void;
}
/**
* Whether output should be human-readable rather than JSON.
*
* Decided once, when the logger is built, and never per call — the answer cannot change while the
* process runs, and asking on every record would put a syscall-shaped question on a path that is
* supposed to be cheap. `process` is absent on the edge, so the guard is not defensive padding:
* unattended is the correct default there, and JSON is the unattended format.
*/
function isInteractive(): boolean {
const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;
return Boolean(proc?.stdout?.isTTY);
}
const CONSOLE_METHOD: Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'> = {
debug: 'debug',
info: 'info',
warn: 'warn',
error: 'error',
};
function renderPretty(level: LogLevel, message: string, fields?: LogFields): string {
const pairs = fields
? Object.entries(fields)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
: [];
return `[green-tea] ${level.toUpperCase()} ${message}${pairs.length ? ' ' + pairs.join(' ') : ''}`;
}
function renderJson(level: LogLevel, message: string, fields?: LogFields): string {
// `name` rather than the `[green-tea]` prefix the messages used to carry inline: a log
// aggregator filters on a field, and cannot filter on a substring of prose.
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
}
/**
* Wraps a logger so a throwing one cannot go silent.
*
* `Bus.emit` isolates listener failures on purpose — an observer must never be able to break a
* request — but that guarantee has a cost when the observer is the logger itself: a user logger
* that throws would simply stop writing, with nothing to say so. Falling back to `console` keeps
* the Bus's promise without paying for it in silence.
*
* Exported because request logging is not the only thing that should survive a broken logger.
*/
export function withConsoleFallback(logger: Logger): Logger {
const guard =
(level: LogLevel) =>
(message: string, fields?: LogFields): void => {
try {
logger[level](message, fields);
} catch (error) {
console.error(
renderJson('error', 'the configured logger threw; falling back to console', {
level,
originalMessage: message,
error: error instanceof Error ? error.message : String(error),
...fields,
}),
);
}
};
return { debug: guard('debug'), info: guard('info'), warn: guard('warn'), error: guard('error') };
}
/**
* Subscribes request logging to the lifecycle stream: `info` per completed request, `error` per
* failed one. Returns an unsubscribe function, so it is as removable as it is composable — which
* is what "a composable step, not a global middleware" has to mean in practice.
*
* Reads the stream rather than being called from the request path, so there is exactly one account
* of what happened to a request. A second path would eventually disagree with the first.
*/
export function logRequests(bus: BusLike, logger: Logger): () => void {
const safe = withConsoleFallback(logger);
const offEnd = bus.on('request:end', (event) => {
safe.info(`${event.method ?? ''} ${event.route ?? event.name} ${event.status ?? ''}`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
status: event.status,
durationMs: event.durationMs,
});
});
const offFailed = bus.on('request:failed', (event) => {
safe.error(`${event.method ?? ''} ${event.route ?? event.name} failed`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
error: event.error instanceof Error ? event.error.message : event.error,
});
});
return () => {
offEnd();
offFailed();
};
}
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
interface BusLike {
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
}
/**
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
*
* Writes through `console`, which is the whole reason core can have a logging contract without a
* logging dependency — `reflect-metadata` stays the only runtime dependency, and anything richer
* (transports, sampling, rotation) is a `Logger` a user passes in.
*/
export function createDefaultLogger(pretty: boolean = isInteractive()): Logger {
const write = (level: LogLevel, message: string, fields?: LogFields): void => {
console[CONSOLE_METHOD[level]](pretty ? renderPretty(level, message, fields) : renderJson(level, message, fields));
};
return {
debug: (message, fields) => write('debug', message, fields),
info: (message, fields) => write('info', message, fields),
warn: (message, fields) => write('warn', message, fields),
error: (message, fields) => write('error', message, fields),
};
}
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff. Show more