72 Commits
Author SHA1 Message Date
chrnx d76afd7f25 docs(changelog): note the radix route index
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 25s
An internal change with no behaviour difference, recorded under
Changed with the lookup numbers from the jarvis run.

Refs #109

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

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

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

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

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

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

Refs #109

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

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

The mutation check still kills 12 of 12.

Refs #109

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

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

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

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

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

Refs #109

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

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

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

Refs #109

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

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

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

Refs #109

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

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

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

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

Refs #109

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

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

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

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

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

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

Refs #109

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

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

Refs #109

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

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

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

Refs #109

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

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

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

Refs #109

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

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

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

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

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

Refs #109

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

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

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

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

Refs #109

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

vite stays on ^6.4.3, which vitest 4 accepts.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #107

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

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

Refs #107

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

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

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

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

Closes #116

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

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

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

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

Closes #105

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

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

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

Closes #107

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

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

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

Closes #104

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

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

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

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

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

Closes #108

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

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

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

Closes #106

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 09:34:57 -05:00
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 / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 32s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (edge) (push) Successful in 14s
Release → npmjs / publish-prod (push) Has been skipped
Stage → Verdaccio / publish-stg (push) Successful in 27s
2026-09-23 01:50:39 +00:00
chrnx b0a9f3bfc9 chore(release): cut 26.9.0-beta.2
CI / dco (pull_request) Successful in 7s
CI / build (pull_request) Successful in 31s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
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
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 6s
2026-09-20 16:55:47 +00:00
chrnx 9634ec73e8 feat(runtime)!: serveDeno and serveBun boot before they bind
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 13s
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 / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 13s
Promote → GitHub / push-github (push) Successful in 7s
2026-09-18 03:53:29 +00:00
chrnx 58ba18f9f8 chore: ignore per-developer agent directories
Stage → Verdaccio / publish-stg (push) Successful in 28s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / runtimes (edge) (pull_request) Successful in 13s
.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 / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 31s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
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 / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 16m38s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
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 / build (push) Successful in 30s
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 7s
2026-09-12 21:36:14 +00:00
chrnx 25f4144a38 ci(promote): mirror develop to GitHub contrib
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 20s
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 (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-12 20:42:04 +00:00
chrnx 0ce81b08f3 test(mesh): cover the teapot dying with an RPC still in flight
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 15s
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
169 changed files with 51864 additions and 1338 deletions

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
## Environment ## Environment
- green-tea version: - green-tea version:
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers --> - Runtime and version: <!-- Node 22.12 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- OS: - OS:
<!-- <!--
+1 -1
View File
@@ -41,7 +41,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: '18' node-version: '22'
- run: npm ci - run: npm ci
- run: npm run lint - run: npm run lint
- run: npm run format:check - run: npm run format:check
+21 -5
View File
@@ -1,9 +1,17 @@
name: Promote → GitHub name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` to the public GitHub repo — develop and # Promotion. Runs on GITEA ONLY. Mirrors two branches to the public GitHub repo and nothing else:
# feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which #
# main → GitHub main the production mirror
# 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). # 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 # 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 # 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 # JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
@@ -16,7 +24,7 @@ name: Promote → GitHub
# promoting `main` — a publish nobody chose, of a commit nobody was looking at. # promoting `main` — a publish nobody chose, of a commit nobody was looking at.
on: on:
push: push:
branches: [main] branches: [main, develop]
jobs: jobs:
push-github: push-github:
@@ -26,9 +34,17 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 # full history for a clean push fetch-depth: 0 # full history for a clean push
- name: Push main 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"
git push github "HEAD:refs/heads/main" if ! git push github "HEAD:refs/heads/${target}"; then
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."
exit 1
fi
+8
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/
@@ -14,6 +21,7 @@ coverage/
# Edge (Miniflare) test bundle artifact # Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs test/edge/_worker.mjs
test/edge/_parity-worker.mjs
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs # Bun 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. # `bun test` against the node_modules npm installed, which package-lock.json already pins.
+31 -7
View File
@@ -29,12 +29,14 @@ Run the first four before proposing anything as finished. The runtime suites sta
## Two forges ## Two forges
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` automatically and release tags only by hand. 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 feature/* → develop → main → [promote.yml] → GitHub main
↑ │ ↓ │ │
lead dev │ GitHub contrib ← external PRs └─[promote.yml]┼──→ GitHub contrib ← external PRs
↑ │ │
└── carried back by hand ─┘ (a PR into develop)
│ │
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
└─── GitHub (pushed by hand): [release.yml] → npm + JSR └─── GitHub (pushed by hand): [release.yml] → npm + JSR
@@ -43,7 +45,7 @@ feature/* → develop → main → [promote.yml] → GitHub main
- **Gitea `develop`** — active development. - **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. - **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 `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.
- **`contrib`** — exists on *both* forges. Where outside contributions land. - **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. `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.
@@ -53,6 +55,28 @@ feature/* → develop → main → [promote.yml] → GitHub main
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does. **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: **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 ```bash
@@ -61,13 +85,13 @@ git diff <branch> <main> -- <suspect file> # empty means the content is alread
Merging such a branch to "recover" the commits duplicates the work and drags stale history along. 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, mirror that branch to Gitea, then open a `contrib → develop` pull request and merge it. 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 push `contrib` out of `main`'s ancestry, which then costs a force-push at reset time. Merging keeps their commits reaching `main` under their own name and hash. **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. 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.
**After every promotion, reset *both* `contrib` branches to `main`.** GitHub's is where external work lands; Gitea's is its mirror, and the easy one to forget because nothing there refuses the push. Normally this is an ordinary fast-forward, since `contrib` is already inside `main`'s history. It only needs a force-push when SHAs were rewritten on the way in — and GitHub then refuses it even for admins, so that branch's protection has to be lifted and restored around the reset. **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 unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve. 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 ## Releasing
+90 -40
View File
@@ -4,12 +4,12 @@
## Environment ## Environment
- **Date**: 2026-09-02 - **Date**: 2026-09-22
- **Commit**: 8c5855c - **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, 10s duration, 5 runs (1 warmup discarded), pipelining 1 - **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
@@ -29,74 +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 | 119,357 | 0.00 | 1.00 | 1.00 | 0.4% | 118,560–120,067 | | raw-http | 41,631 | 2.00 | 3.00 | 4.00 | 0.6% | 41,343–41,974 |
| nestjs-fastify | 98,039 | 0.00 | 1.00 | 2.00 | 1.2% | 96,073–99,680 | | nestjs-fastify | 32,419 | 3.00 | 4.00 | 6.00 | 0.5% | 32,103–32,583 |
| fastify | 89,097 | 1.00 | 1.00 | 2.00 | 0.1% | 88,864–89,207 | | fastify | 32,170 | 3.00 | 3.00 | 5.00 | 1.3% | 31,236–32,356 |
| green-tea | 87,473 | 1.00 | 2.00 | 2.00 | 0.3% | 86,903–87,607 | | green-tea | 29,777 | 3.00 | 6.00 | 7.00 | 0.4% | 29,557–29,873 |
| express | 24,677 | 3.00 | 5.00 | 8.00 | 0.2% | 24,647–24,769 | | express | 10,546 | 8.00 | 13.00 | 18.00 | 0.4% | 10,480–10,625 |
| nestjs-express | 21,879 | 4.00 | 6.00 | 9.00 | 0.2% | 21,845–21,953 | | 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 | 120,905 | 0.00 | 1.00 | 1.00 | 0.5% | 119,927–121,713 | | raw-http | 41,756 | 2.00 | 3.00 | 4.00 | 1.1% | 40,953–42,017 |
| nestjs-fastify | 91,849 | 1.00 | 1.00 | 2.00 | 0.3% | 91,825–92,599 | | fastify | 31,708 | 3.00 | 4.00 | 5.00 | 0.5% | 31,359–31,847 |
| fastify | 88,317 | 1.00 | 1.00 | 2.00 | 0.2% | 87,997–88,439 | | nestjs-fastify | 29,880 | 3.00 | 4.00 | 6.00 | 0.3% | 29,745–29,961 |
| green-tea | 86,595 | 1.00 | 2.00 | 2.00 | 0.2% | 86,368–86,880 | | green-tea | 28,706 | 3.00 | 6.00 | 7.00 | 0.6% | 28,562–29,051 |
| express | 24,200 | 3.00 | 5.00 | 8.00 | 0.2% | 24,158–24,260 | | express | 10,376 | 9.00 | 12.00 | 17.00 | 0.4% | 10,364–10,453 |
| nestjs-express | 21,182 | 4.00 | 6.00 | 9.00 | 0.7% | 21,150–21,518 | | 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 | 118,996 | 0.00 | 1.00 | 1.00 | 0.3% | 118,583–119,584 | | raw-http | 39,897 | 2.00 | 3.00 | 5.00 | 0.6% | 39,847–40,441 |
| nestjs-fastify | 89,527 | 1.00 | 2.00 | 2.00 | 1.0% | 87,572–90,028 | | fastify | 31,436 | 3.00 | 4.00 | 6.00 | 0.6% | 31,079–31,563 |
| fastify | 86,671 | 1.00 | 1.00 | 2.00 | 0.1% | 86,490–86,793 | | nestjs-fastify | 29,403 | 3.00 | 4.00 | 6.00 | 0.6% | 29,151–29,689 |
| green-tea | 80,079 | 1.00 | 2.00 | 2.00 | 0.2% | 80,026–80,375 | | green-tea | 26,839 | 3.00 | 6.00 | 8.00 | 0.1% | 26,783–26,872 |
| express | 24,325 | 3.00 | 5.00 | 8.00 | 0.2% | 24,281–24,407 | | express | 10,365 | 9.00 | 12.00 | 18.00 | 1.3% | 10,171–10,542 |
| nestjs-express | 20,872 | 4.00 | 6.00 | 9.00 | 0.2% | 20,801–20,940 | | 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 | 104,288 | 0.00 | 1.00 | 1.00 | 0.4% | 103,776–104,916 | | raw-http | 31,783 | 3.00 | 5.00 | 6.00 | 0.4% | 31,517–31,825 |
| green-tea | 70,298 | 1.00 | 2.00 | 3.00 | 1.0% | 68,972–70,607 | | green-tea | 22,005 | 4.00 | 7.00 | 9.00 | 0.7% | 21,736–22,187 |
| fastify | 65,905 | 1.00 | 2.00 | 3.00 | 0.3% | 65,725–66,367 | | fastify | 20,430 | 4.00 | 8.00 | 9.00 | 0.4% | 20,398–20,601 |
| nestjs-fastify | 63,318 | 1.00 | 2.00 | 3.00 | 0.9% | 62,454–63,747 | | nestjs-fastify | 18,597 | 4.00 | 8.00 | 11.00 | 0.2% | 18,540–18,658 |
| express | 20,297 | 4.00 | 6.00 | 10.00 | 0.5% | 20,158–20,414 | | express | 8,440 | 11.00 | 16.00 | 24.00 | 0.3% | 8,408–8,492 |
| nestjs-express | 18,788 | 5.00 | 7.00 | 10.00 | 0.3% | 18,684–18,862 | | 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 | 88,108 | | /steps/0 | 0 | 29,196 |
| /steps/3 | 3 | 79,951 | | /steps/3 | 3 | 26,564 |
| /steps/5 | 5 | 74,127 | | /steps/5 | 5 | 25,314 |
Each additional pipeline step costs roughly 2,796 req/s (-15.9% 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 ## green-tea across runtimes
| Scenario | node | deno | bun | | Scenario | node | deno | bun |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| JSON hello (overhead) | 90,976 | 153,408 | 131,674 | | JSON hello (overhead) | 30,379 | 51,888 | 46,300 |
| Route param | 88,905 | 146,368 | 126,909 | | Route param | 29,204 | 51,786 | 42,788 |
| Pipeline (3 steps) | 82,045 | 136,256 | 117,489 | | Pipeline (3 steps) | 27,208 | 50,692 | 39,644 |
| POST JSON + validation | 72,236 | 106,662 | 95,124 | | 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. 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) | 87,473 | | security:false (parity) | 29,777 |
| security:true (default) | 83,773 | | security:true (default) | 28,919 |
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.2% req/s on this box. 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
@@ -136,6 +136,56 @@ was benchmarked as it landed — the numbers are still in the code, cited below
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and 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. `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` ### 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 Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
+226
View File
@@ -6,6 +6,231 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros. npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
### Breaking
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
for Node 18's missing global `crypto` is removed with it.
- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own
default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could
make the server hold a message of any size the runtime would accept. A larger message now closes
the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`.
- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013`
(`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler
that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws`
handler that never reads `inbound` at all: on Node those frames used to be discarded, and they
now count. Raise the bound with `limits.maxWsQueue`.
### Added
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
before buffering it; Bun does so by dropping the connection, so its peer sees `1006` rather than
`1009`. Deno and workerd expose no such option, so there the message is received in full and then
refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
Bun have no connection cap, so set one at the platform or proxy there.
### Changed
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`.
It now walks a tree per method, built once from the route table, with mesh routes from teapots
in a tree of their own. This is internal and changes no behaviour: the same route wins, with the
same params, `Allow`, implicit `HEAD` and 404/405, checked against the frozen parity corpus.
`graph()`, `explain()` and `openapi()` still read the declared routes, not the tree. Median lookup
time against the old matcher (jarvis, `bench:lookup`): at 500 routes, static hit −54%, late
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
### Fixed
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
root that is itself a symlink, keep working.
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
"does not exist". The content-type still follows the requested name, not the link target.
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
while the app runs needs a restart** to take effect. A link swapped inside the root between the
check and the read can still escape; exploiting that needs write access to the served directory.
- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node
request listener was an `async` function, and `http.createServer` ignores the promise it returns,
so anything that rejected outside the region where errors convert to a response — a custom static
resolver, a handler header value Node refuses to write, a stream that fails before its first frame
— became an unhandled rejection, which Node's default mode turns into an exit. The listener now
catches it. While the response is still writable the client gets a fixed 500 with
`connection: close`, written without calling `onError` again; once output has started the socket
is destroyed instead. Either way the failure is logged through `logger.error`. No `request:end` is
emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s
promise, and the runtime answers a rejection with a 500 itself.
- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never
ran the request-path normalization HTTP runs, so a bad percent escape in a param segment
(`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request
was enough to end the process. Upgrades now go through the same normalization: a malformed escape
or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect,
and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on
upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
the socket finished opening now reaches the client instead of leaving it hanging.
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
is refused before any of the body is read, on Node too, where the request used to wait for its
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
the count rather than up front. The status is the same; only how early it comes differs.
- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch
path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as
`''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one
client could exhaust the limit for everyone, above all. Both adapters now hand the peer to
`app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first
`x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer
otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on
the fetch path and now falls back to the peer, as Node always has.
Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all
three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from
your own code has no socket to report and still answers `''` (or the forwarded hop), and so does
a `Request` copied from the one the adapter received. No signature changed. The edge adapter is
unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own
decision.
## [26.9.0-beta.2] - 2026-09-22
### Breaking
- **`serveDeno()` and `serveBun()` are async**, returning `Promise<DenoServer>` and
`Promise<BunServeResult>`. They now boot the app before they bind, which is what `listen()` has
always done.
They did not, and the documented fix was to remember to `await app.boot()` first. That made the
correct use of a core helper depend on reading a README, in a framework whose argument is that
order should not be something you have to get right. Forget it and a missing signing key is not a
failed deploy: the boot memo keeps the rejection, so the port binds, every request gets a 500 from
the runtime, and none of them reach `onError`. The server looks healthy to anything that only
checks whether it is listening.
Migration is one keyword, and the value is unchanged:
```diff
- const server = serveDeno(app, { port });
+ const server = await serveDeno(app, { port });
```
Both runtimes support top-level `await`, so a module that serves at import time needs nothing
else. `edgeHandler` is deliberately untouched: on workerd there is no startup outside a request,
so there is no earlier moment to move the failure to.
- **A plugin is a named object.** `Plugin` is now `{ name, mount(api) }`; it was `(api) => void`.
The name that `plugin:mounted` reports came from `fn.name`, which is `""` for an arrow returned
straight from a factory, `"plugin"` for a `const`, and whatever a minifier leaves behind — so the
event that exists to report which plugins mounted reported none of them by name. The name is now
the author's word, a failed `mount` is reported as `plugin "<name>" failed to mount: …` with the
original error as its `cause`, and two plugins sharing a name fail `createApp`.
Migration is mechanical:
```diff
- const jwt = (options) => ({ scope }) => { scope.add(node); };
+ const jwt = (options) => ({
+ name: options.provides ?? 'jwt',
+ mount({ scope }) { scope.add(node); },
+ });
```
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
the boot, with an error naming the provider and the replacement. A provider is a factory whose
value *is* the object it builds — a pool, a client, a `db` — and an object is not what a JSON wire
carries. What did cross was whatever half of it survived serialization, and it arrived as an
app-scope binding: the teacup resolved it once at boot and then served that value for the life of
the process, out of a cache the teapot no longer stood behind. Restarting the teapot, or changing
what it built, changed nothing on the teacup until the teacup itself restarted.
Export a `@Step` instead. It runs on the teapot, per request, and only its result comes back —
which is why the two entries below follow from this one: a remote export now holds nothing between
requests. `invalidateRemoteBindings`, the `rebind` array and the `onReconnect` callback that drove
them are gone with it. All three existed to throw away a cached app-scope value when a link came
back; there is no longer a cached value, so a reconnected link is simply usable again on the next
RPC. Internal, so nothing importable changed.
**A teapot that boots today can stop booting**, and the replacement is mechanical: the exported
`@Provider` becomes a `@Step` that returns what the provider's value carried.
- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now
`{ steps: string[], routes }`. Every export is request-scope after the change above, so the
lifetime field had one possible value left and told a reader nothing. A manifest step that is not
a string is now rejected on arrival, rather than trusted because a peer sent it.
`MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both
peers ship from this repository, and there is no deployed pair of versions for a bump to protect —
it would spend the number on nobody. A stable wire would not get that option; alpha is exactly
what the word buys, and this is the last comfortable moment to use it.
### Added
- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`,
`serveDeno()` and `serveBun()` all call it for you (see Breaking, below). Call it by hand when you
drive `app.fetch` / `app.upgrade` from your own server: those boot lazily, and the boot memo keeps
a rejection, so a bad key answers 500 on *every* request, from the runtime, without reaching
`onError`. On workerd there is no startup outside a request, so calling it moves nothing.
- **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry
`Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and
`isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a
different copy of core — a plugin package, an app that installed from npm and JSR both — now
renders with its own status instead of a 500. The exported `HttpErrorLike` type and the
`isValidationError` guard come with it. The string is the public protocol: code that imports only
types writes `Symbol.for('green-tea.http-error')` itself.
### Changed
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** Blocking was never
caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later
to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the
container is thirty seconds behind" and "the teapot does not exist" look identical for the first
thirty seconds; exhausting it now warns and starts without that teapot.
What that buys is narrower than it sounds, and worth stating exactly. A teapot that never
connected sent no manifest, so the teacup learned nothing about it — no step runners, no routes,
a graph identical to the one it would have had if that teapot were never configured. Its routes
therefore **404**, through the ordinary unmatched-route path, because nothing was ever registered
to match. And any local step or handler that needs one of its tokens **still fails the boot**,
naming the teapot that did not connect. `503` is what a teapot that connected and *later* died
answers: that link exists, its steps and routes are registered, and the dead link is what returns
the status. Never reachable and reachable-then-gone are different situations, and they read
differently on purpose.
So the change is for the teacup that does *not* depend on that teapot: it starts, rather than
refusing over a dependency it never had. It is not graceful degradation of the dependency, and
cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have
exported, and only a declaration can say. That declaration is the `expects` list in
`docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are
unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot
without spending the grace, because it is the teapot's decision rather than the network's and will
be the same decision in thirty seconds; and the missing-token error, which now says "local or
connected mesh" rather than "local or mesh", the old wording having claimed a search that never
happened.
## [26.9.0-beta.1] - 2026-09-04 ## [26.9.0-beta.1] - 2026-09-04
### Added ### Added
@@ -527,6 +752,7 @@ change before the stable release.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5, - **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md). NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
[26.9.0-beta.2]: https://github.com/Expressive-Tea/green-tea/compare/v26.9.0-beta.1...v26.9.0-beta.2
[26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1 [26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1 [26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0 [26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
+5 -5
View File
@@ -4,9 +4,9 @@ Thanks for your interest. green-tea is open source, but not anyone can push dire
## Where to send your changes ## Where to send your changes
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main` and release tags, and nothing else. Which branch you target depends on where you are. 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. **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. **From Gitea, if you have access:** follow the branch model below.
@@ -30,7 +30,7 @@ git push origin fix/close-timeout
Then open the pull request with **`contrib`** as the base branch. Then open the pull request with **`contrib`** as the base branch.
`contrib` tracks released code, so it is reset to `main` after each release. If your branch has been open across one, rebase onto the new `contrib` before pushing again. `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)
@@ -91,7 +91,7 @@ If your assistant reads repository instructions, `AGENTS.md` has the conventions
- `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. Where outside contributions land before a maintainer moves them to `develop`. - `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.)
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
## Local setup ## Local setup
Node 18 or newer, which is what `engines` requires and what CI runs. Node 22 or newer, which is what `engines` requires and what CI runs. Node 18 and 20 are end-of-life and no longer supported.
```bash ```bash
npm install npm install
+10 -6
View File
@@ -56,9 +56,9 @@ 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), `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. - **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? ## Who does the work?
@@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **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.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun drops the connection, so its peer sees `1006`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **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 })`. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. - **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.
@@ -153,7 +153,9 @@ without growing the runtime dependency tree past `reflect-metadata`:
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. 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.
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. On that harness green-tea is in the same class as Fastify and NestJS-on-Fastify, roughly 2.8× ahead of Express, and behind raw `http` with no framework at all. Within that class the shape reproduces on two very different machines: green-tea is **behind** Fastify on the JSON, routing and pipeline scenarios, and **ahead** of it on POST-plus-validation. How far behind is a property of the box rather than a constant — 2-8% on a laptop M4 Max, 7-15% on an idle desktop Ryzen — which is why the table carries its hardware and its date, and why a percentage quoted without them says little. Read [BENCHMARKS.md](./BENCHMARKS.md) rather than a sentence here: a ranking written into prose once is a claim nobody re-measures.
The question a release actually has to pass is the other one — *did the last N commits cost anything* — and comparing today's numbers against a table generated weeks ago answers it with two machines in a mood rather than two versions. `npm run bench:compare` runs both trees on one box in one sitting, alternating sides; `26.9.0-beta.1 → 26.9.0-beta.2` came out flat on every case.
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`. 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`.
@@ -282,11 +284,13 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. **Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **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 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 gained `onShutdown` this week; `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. **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 the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), 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
+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
+356
View File
@@ -0,0 +1,356 @@
/**
* 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, ...). 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, import 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> {
// Import order alternates per run (LOOKUP_IMPORT_REVERSED): which copy V8 sees first can bias an
// in-process comparison of otherwise identical code, and alternating spreads that over both sides.
const imports = process.env.LOOKUP_IMPORT_REVERSED === '1' ? [...routers].reverse() : routers;
const modules = new Map<string, RouterModule>();
for (const [label, path] of imports)
modules.set(label, (await import(pathToFileURL(resolve(path)).href)) as RouterModule);
const loaded: Loaded = routers.map(([label]) => ({ label, router: modules.get(label)! }));
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);
});
+214 -214
View File
@@ -1,11 +1,11 @@
{ {
"env": { "env": {
"date": "2026-09-02", "date": "2026-09-22",
"commit": "8c5855c", "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": {
@@ -23,80 +23,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 119357.1, "median": 41630.55,
"min": 118560, "min": 41342.55,
"max": 120066.91, "max": 41973.82,
"stddev": 484.9030139151553, "stddev": 232.79156158245826,
"cv": 0.0040636145553490976 "cv": 0.0055977118567263305
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 4
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 89096.73, "median": 32170.19,
"min": 88864, "min": 31235.64,
"max": 89207.28, "max": 32355.64,
"stddev": 111.97759400880093, "stddev": 403.36620390905324,
"cv": 0.001257219726589825 "cv": 0.012593571579786219
}, },
"p50": 1, "p50": 3,
"p99": 1, "p99": 3,
"p999": 2 "p999": 5
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24677.1, "median": 10545.82,
"min": 24646.55, "min": 10480.37,
"max": 24768.73, "max": 10625.1,
"stddev": 43.02015834466458, "stddev": 47.02831087759791,
"cv": 0.0017417832565876405 "cv": 0.004456044641032285
}, },
"p50": 3, "p50": 8,
"p99": 5, "p99": 13,
"p999": 8 "p999": 18
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 87473.46, "median": 29776.73,
"min": 86903.28, "min": 29557.1,
"max": 87607.28, "max": 29872.73,
"stddev": 280.84365746087286, "stddev": 120.92248317000461,
"cv": 0.0032155347907296527 "cv": 0.004066812850878315
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 6,
"p999": 2 "p999": 7
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 21878.55, "median": 9679.64,
"min": 21845.1, "min": 9566.91,
"max": 21952.73, "max": 9738.55,
"stddev": 41.00873789816055, "stddev": 58.2951632985104,
"cv": 0.0018731606009975037 "cv": 0.006025529205104781
}, },
"p50": 4, "p50": 9,
"p99": 6, "p99": 15,
"p999": 9 "p999": 21
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 98039.28, "median": 32418.91,
"min": 96072.73, "min": 32103.28,
"max": 99680, "max": 32582.55,
"stddev": 1215.4038343760499, "stddev": 159.574135748874,
"cv": 0.012396669934655963 "cv": 0.004929287112917938
}, },
"p50": 0, "p50": 3,
"p99": 1, "p99": 4,
"p999": 2 "p999": 6
} }
] ]
}, },
@@ -107,80 +107,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 120904.73, "median": 41755.64,
"min": 119927.28, "min": 40952.73,
"max": 121713.46, "max": 42017.46,
"stddev": 658.0250991747977, "stddev": 439.72294183496837,
"cv": 0.005441723483024015 "cv": 0.010587809774433589
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 4
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 88317.1, "median": 31708.37,
"min": 87997.1, "min": 31359.28,
"max": 88439.28, "max": 31846.55,
"stddev": 182.99174422907566, "stddev": 168.73300179869975,
"cv": 0.00207430857941761 "cv": 0.005328784944282288
}, },
"p50": 1, "p50": 3,
"p99": 1, "p99": 4,
"p999": 2 "p999": 5
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24200, "median": 10375.64,
"min": 24157.82, "min": 10364,
"max": 24259.64, "max": 10452.73,
"stddev": 39.43298619176589, "stddev": 37.668132419858544,
"cv": 0.0016290899720752198 "cv": 0.003621859193349617
}, },
"p50": 3, "p50": 9,
"p99": 5, "p99": 12,
"p999": 8 "p999": 17
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 86594.91, "median": 28706.19,
"min": 86368, "min": 28562.19,
"max": 86880, "max": 29050.91,
"stddev": 179.11650003279965, "stddev": 166.92265315408858,
"cv": 0.002068552609808656 "cv": 0.005803163694455583
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 6,
"p999": 2 "p999": 7
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 21181.82, "median": 9257.1,
"min": 21149.82, "min": 9244,
"max": 21517.82, "max": 9285.46,
"stddev": 139.0670808494951, "stddev": 16.97885461390117,
"cv": 0.006540068168697097 "cv": 0.0018327336012062287
}, },
"p50": 4, "p50": 10,
"p99": 6, "p99": 15,
"p999": 9 "p999": 21
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 91848.73, "median": 29880,
"min": 91825.46, "min": 29744.73,
"max": 92599.28, "max": 29961.46,
"stddev": 296.55679952413783, "stddev": 90.38256681462417,
"cv": 0.00322222064035544 "cv": 0.003027383166346
}, },
"p50": 1, "p50": 3,
"p99": 1, "p99": 4,
"p999": 2 "p999": 6
} }
] ]
}, },
@@ -192,80 +192,80 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 118996.37, "median": 39896.73,
"min": 118583.28, "min": 39847.28,
"max": 119584, "max": 40440.73,
"stddev": 341.82644850274596, "stddev": 235.6558649726337,
"cv": 0.002872466494470492 "cv": 0.0058846766178520865
}, },
"p50": 0, "p50": 2,
"p99": 1, "p99": 3,
"p999": 1 "p999": 5
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86670.55, "median": 31436.37,
"min": 86490.19, "min": 31078.55,
"max": 86792.73, "max": 31562.91,
"stddev": 97.03476704769095, "stddev": 185.21052212010017,
"cv": 0.0011197471063834074 "cv": 0.005909263441314207
}, },
"p50": 1, "p50": 3,
"p99": 1, "p99": 4,
"p999": 2 "p999": 6
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24325.1, "median": 10365.46,
"min": 24281.46, "min": 10170.55,
"max": 24406.55, "max": 10542.19,
"stddev": 50.44878456414985, "stddev": 129.83340146510884,
"cv": 0.002073096921615235 "cv": 0.01252603707960138
}, },
"p50": 3, "p50": 9,
"p99": 5, "p99": 12,
"p999": 8 "p999": 18
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 80078.55, "median": 26838.55,
"min": 80026.19, "min": 26783.28,
"max": 80375.28, "max": 26872,
"stddev": 126.5427427235537, "stddev": 35.930271582608675,
"cv": 0.00157915416330658 "cv": 0.0013390899572667937
}, },
"p50": 1, "p50": 3,
"p99": 2, "p99": 6,
"p999": 2 "p999": 8
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20872, "median": 9256.37,
"min": 20800.73, "min": 9187.28,
"max": 20940.37, "max": 9302.19,
"stddev": 44.78034640330492, "stddev": 42.180541200890175,
"cv": 0.0021458031999967474 "cv": 0.0045584972844857205
}, },
"p50": 4, "p50": 10,
"p99": 6, "p99": 15,
"p999": 9 "p999": 22
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 89527.28, "median": 29402.91,
"min": 87572.37, "min": 29151.28,
"max": 90027.64, "max": 29689.46,
"stddev": 867.875358507201, "stddev": 189.99449229911926,
"cv": 0.009726340137622384 "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": 104288, "median": 31783.28,
"min": 103776, "min": 31517.1,
"max": 104916.37, "max": 31824.73,
"stddev": 371.6125197245094, "stddev": 111.5598838292694,
"cv": 0.0035614220793380035 "cv": 0.003516116881358333
}, },
"p50": 0, "p50": 3,
"p99": 1, "p99": 5,
"p999": 1 "p999": 6
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 65905.46, "median": 20429.82,
"min": 65725.1, "min": 20397.82,
"max": 66366.55, "max": 20601.46,
"stddev": 217.1439762369652, "stddev": 73.12471046096515,
"cv": 0.0032914527300013986 "cv": 0.0035727493036941836
}, },
"p50": 1, "p50": 4,
"p99": 2, "p99": 8,
"p999": 3 "p999": 9
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 20297.46, "median": 8440.37,
"min": 20157.82, "min": 8407.64,
"max": 20413.82, "max": 8492,
"stddev": 99.50819415505447, "stddev": 29.52737333390846,
"cv": 0.004902635960088364 "cv": 0.003496408589959768
}, },
"p50": 4, "p50": 11,
"p99": 6, "p99": 16,
"p999": 10 "p999": 24
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 70298.19, "median": 22005.1,
"min": 68971.64, "min": 21736,
"max": 70606.55, "max": 22186.91,
"stddev": 704.8749988359651, "stddev": 149.1731413626461,
"cv": 0.01008804689681251 "cv": 0.006790967759795645
}, },
"p50": 1, "p50": 4,
"p99": 2, "p99": 7,
"p999": 3 "p999": 9
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 18787.64, "median": 7666.37,
"min": 18684.37, "min": 7645.28,
"max": 18861.82, "max": 7703.46,
"stddev": 57.13389375843402, "stddev": 20.418688106732038,
"cv": 0.0030419312672842124 "cv": 0.002662071942974812
}, },
"p50": 5, "p50": 12,
"p99": 7, "p99": 18,
"p999": 10 "p999": 26
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 63317.82, "median": 18596.8,
"min": 62453.82, "min": 18540.37,
"max": 63746.91, "max": 18658.19,
"stddev": 543.811870536126, "stddev": 37.943211988443956,
"cv": 0.00860786685722159 "cv": 0.0020404741150848267
}, },
"p50": 1, "p50": 4,
"p99": 2, "p99": 8,
"p999": 3 "p999": 11
} }
] ]
} }
@@ -358,89 +358,89 @@
{ {
"path": "/steps/0", "path": "/steps/0",
"steps": 0, "steps": 0,
"reqSec": 88107.64 "reqSec": 29196.37
}, },
{ {
"path": "/steps/3", "path": "/steps/3",
"steps": 3, "steps": 3,
"reqSec": 79950.55 "reqSec": 26563.64
}, },
{ {
"path": "/steps/5", "path": "/steps/5",
"steps": 5, "steps": 5,
"reqSec": 74126.55 "reqSec": 25314.19
} }
], ],
"secureCost": [ "secureCost": [
{ {
"label": "security:false (parity)", "label": "security:false (parity)",
"reqSec": 87473.46 "reqSec": 29776.73
}, },
{ {
"label": "security:true (default)", "label": "security:true (default)",
"reqSec": 83773.1 "reqSec": 28918.55
} }
], ],
"runtimes": [ "runtimes": [
{ {
"runtime": "node", "runtime": "node",
"scenario": "JSON hello (overhead)", "scenario": "JSON hello (overhead)",
"reqSec": 90976 "reqSec": 30378.91
}, },
{ {
"runtime": "node", "runtime": "node",
"scenario": "Route param", "scenario": "Route param",
"reqSec": 88904.73 "reqSec": 29203.64
}, },
{ {
"runtime": "node", "runtime": "node",
"scenario": "Pipeline (3 steps)", "scenario": "Pipeline (3 steps)",
"reqSec": 82045.1 "reqSec": 27208
}, },
{ {
"runtime": "node", "runtime": "node",
"scenario": "POST JSON + validation", "scenario": "POST JSON + validation",
"reqSec": 72235.64 "reqSec": 22608.73
}, },
{ {
"runtime": "deno", "runtime": "deno",
"scenario": "JSON hello (overhead)", "scenario": "JSON hello (overhead)",
"reqSec": 153408 "reqSec": 51888
}, },
{ {
"runtime": "deno", "runtime": "deno",
"scenario": "Route param", "scenario": "Route param",
"reqSec": 146368 "reqSec": 51785.6
}, },
{ {
"runtime": "deno", "runtime": "deno",
"scenario": "Pipeline (3 steps)", "scenario": "Pipeline (3 steps)",
"reqSec": 136256 "reqSec": 50692.37
}, },
{ {
"runtime": "deno", "runtime": "deno",
"scenario": "POST JSON + validation", "scenario": "POST JSON + validation",
"reqSec": 106661.82 "reqSec": 35742.55
}, },
{ {
"runtime": "bun", "runtime": "bun",
"scenario": "JSON hello (overhead)", "scenario": "JSON hello (overhead)",
"reqSec": 131674.19 "reqSec": 46299.64
}, },
{ {
"runtime": "bun", "runtime": "bun",
"scenario": "Route param", "scenario": "Route param",
"reqSec": 126909.1 "reqSec": 42788.37
}, },
{ {
"runtime": "bun", "runtime": "bun",
"scenario": "Pipeline (3 steps)", "scenario": "Pipeline (3 steps)",
"reqSec": 117489.46 "reqSec": 39643.64
}, },
{ {
"runtime": "bun", "runtime": "bun",
"scenario": "POST JSON + validation", "scenario": "POST JSON + validation",
"reqSec": 95124.37 "reqSec": 31960
} }
] ]
} }
+4 -1
View File
@@ -212,7 +212,10 @@ async function main(): Promise<void> {
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(),
+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}`) });
+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": ["."]
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@green-tea/core", "name": "@green-tea/core",
"version": "26.9.0-beta.1", "version": "26.9.0-beta.2",
"license": "MIT", "license": "MIT",
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's // 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 // `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
Generated
+6 -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": {
@@ -56,7 +56,9 @@
"uuid": "11.1.1" "uuid": "11.1.1"
} }
}, },
"undici": "7.29.0" "undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
} }
} }
} }
@@ -64,6 +64,13 @@ instead of a boot manifest.
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was (`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
wrong, not a reason to write a second one. wrong, not a reason to write a second one.
**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped
exporting providers — with nothing cached between requests, there is nothing left to invalidate.
This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the
*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the
seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts.
## Tasks ## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without 1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
@@ -85,6 +85,12 @@ not a wait for `timeoutMs`.
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse 3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name. `compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect. 4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
**Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the
remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback went with that — there is no cached value left to invalidate, so a
reconnected link is simply usable again on the next RPC. The rest of this plan shipped as
written; only this step has no counterpart in the code.
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`. 5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
Reconnect defaults **on**. Validate at boot like the other mesh options. Reconnect defaults **on**. Validate at boot like the other mesh options.
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message 6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
@@ -0,0 +1,710 @@
# A mesh that exports steps, not providers
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or
> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking.
**Status:** planned, 2026-09-06
**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`,
mesh tests on all runtimes, `README.md`, `CHANGELOG.md`
**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a
protocol bump because of it.
**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error,
and a teapot that is unreachable at boot no longer stops the teacup from starting.
## The problem
`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot
cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses
any class instance, so an exported provider can only ever return plain data. What survives is the
worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope**
binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the
process. It is a cache the teapot no longer stands behind, wearing the word "provider".
A step is the shape that actually works across the mesh. It runs per request, the teacup sends the
envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to
the token. Transparent to the caller, and nothing is held.
Two things follow from that, and they are the whole of this plan:
1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative
already exists and is spelled `@Step({ export: true })`.
2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value
has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is
away costs a `503` on the requests that need it, and the app starts.
## Decisions
**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a
warning would leave a running app whose token resolves locally and looks exported. The error names
the replacement, so the message is a fix and not a complaint.
**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in
`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`,
both peers ship from this repo, and a bump would spend the number on a version nobody deployed.
`MESH_PROTOCOL_VERSION` stays `1`.
**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the
design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The
loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the
manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots
into a graph with no `authorization` node, which is strictly worse than today. So the budget stays;
exhausting it now warns and contributes nothing, instead of failing the boot.
**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a
protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and
they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at
3am that says nothing about a secret. Only *unreachable* becomes non-fatal.
**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away
and a local step declares `needs: ['authorization']`, `topoSort` throws
`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to
remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and
`503` forever. The message gains the teapots that did not connect, so the cause is on the screen.
**D6 — The `expects` / degrade plan survives; its D6 does not.**
`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may
legitimately be absent", and it is already steps-only. But its D6 reuses
`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded
step swaps a runner, not a container binding. Note it there rather than leave a dangling reference.
## File structure
| File | Change |
| --- | --- |
| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row |
| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` |
| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` |
| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error |
| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal |
| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` |
| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 |
## A note on the line numbers
Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol —
`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph`
— and treat the numbers as hints.
---
## Task 1: Forbid exporting a provider
The prohibition lands first and alone, because every later task assumes it. Nothing on the wire
changes yet.
**Files**
- Modify: `src/app/index.ts:440` (`collectProviders`)
- Test: `test/mesh/failure.test.ts`
- [ ] **Step 1: Write the failing test**
```ts
// test/mesh/failure.test.ts
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Module } from '../../src/index';
describe('provider export', () => {
it('refuses to boot when a provider is exported over the mesh', async () => {
@Provider({ provides: 'db', needs: [], export: true } as any)
class Db {
provide() {
return { db: { query: () => [] } };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class AppModule {}
expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow(
/provider 'db' cannot be exported/i,
);
});
});
```
- [ ] **Step 2: Run it and watch it fail**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: FAIL — no error is thrown, the app builds.
- [ ] **Step 3: Throw in `collectProviders`**
Replace `src/app/index.ts:440`:
```ts
if (meta.export) registry.exportedProviders.push(meta.provides);
```
with:
```ts
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
// resolved once and cached for the life of the process. A step is the shape that travels:
// it runs per request, on the teapot, and only its result comes back.
if (meta.export)
throw new Error(
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
```
- [ ] **Step 4: Run it and watch it pass**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: PASS.
- [ ] **Step 5: Fix every test that exported a provider**
```bash
npx vitest run test/mesh/
```
Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`.
Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`,
`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/
git commit -m "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."
```
---
## Task 2: A manifest of steps and routes
**Files**
- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`)
- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent)
- Modify: `src/mesh/teacup.ts` (`buildRemote`)
- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison)
- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts`
**Interfaces**
- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }`
- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest`
- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }`
- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/protocol.test.ts
it('encodes a manifest of step names', () => {
const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }));
expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] });
});
it('rejects a manifest whose steps are not an array', () => {
expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow(
/steps and routes must be arrays/,
);
});
```
```ts
// test/mesh/teapot.test.ts
it('builds a manifest from step tokens and routes', () => {
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
steps: ['auth'],
routes: [{ method: 'GET', pattern: '/u/:id' }],
});
});
```
```ts
// test/mesh/teacup.test.ts
it('turns every manifest step into a lazy remote node', async () => {
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
const { steps, routes } = buildRemote(link);
expect(routes).toEqual([]);
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
});
```
- [ ] **Step 2: Run them and watch them fail**
```bash
npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts
```
Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`.
- [ ] **Step 3: Change the protocol**
In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface:
```ts
/**
* A mesh server's advertised steps and routes.
*
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
* lazy — the token exists in the teacup's graph, and running it is an RPC.
*/
export interface Manifest {
steps: string[];
routes: RouteEntry[];
}
```
In the `Frame` union, replace the `manifest` member:
```ts
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
```
And its `SHAPE` row:
```ts
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
},
```
Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still
carry a `Date` or a `Map`.
- [ ] **Step 4: Change `buildManifest`**
In `src/mesh/teapot.ts`, replace the function at `:43-56`:
```ts
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
return { steps: [...args.steps], routes: args.routes };
}
```
Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends
`steps: manifest.steps` in place of `scopes: manifest.scopes`.
The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3
— a task must leave the tree typechecking, and splitting a signature from its only call site across
two commits leaves a broken commit in history:
```ts
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field.
- [ ] **Step 5: Change `buildRemote`**
In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`):
```ts
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
name: token,
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
}));
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method,
pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
}));
return { steps, routes };
}
```
The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and
`resolveScope` on the teapot side resolves both the same way.
- [ ] **Step 6: Update the refuse policy in `link.ts`**
Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it:
a returned manifest must still contain every step token the link contributed at boot, and every
route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect
plan).
- [ ] **Step 7: Typecheck, then run the mesh suite**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl`
call site was missed.
- [ ] **Step 8: Commit**
```bash
git add src/mesh/ test/mesh/
git commit -m "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."
```
---
## Task 3: The teacup stops splicing providers
**Files**
- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`)
- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`)
- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`)
- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`)
- Test: `test/mesh/integration.test.ts`
- [ ] **Step 1: Write the failing test**
This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })`
(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made
that fixture fail at boot, so converting it is not optional — and converting it is the regression
guard, because a step re-runs where the provider was cached:
```ts
// test/mesh/integration.test.ts — replaces the @Provider fixture at :6
let configCalls = 0;
@Step({ provides: 'config', needs: [], export: true })
class Config {
run() {
configCalls += 1;
return { config: { region: 'mx', call: configCalls } };
}
}
```
and add, alongside the existing `/local/who` assertion:
```ts
it('re-runs the RPC on every request rather than caching a boot value', async () => {
// same teapot/teacup pair the '/local/who' test stands up
expect((await hit('/api/local/who')).config.call).toBe(1);
expect((await hit('/api/local/who')).config.call).toBe(2);
});
```
- [ ] **Step 2: Run it — it should already pass, and that is the point**
```bash
npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC'
```
Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable
through provider export, which Task 1 made impossible — once `config` is a step it lands in the
request-scope bucket and already re-runs. The guard exists so that removing the splice in the next
steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it.
- [ ] **Step 3: Delete `exportedProviders`**
Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In
`buildMeshControl` (`:1078-1088`):
```ts
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
// ...
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
- [ ] **Step 4: Delete the remote-provider splice**
In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls
`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block
(`:846-856`). Destructure only what is left:
```ts
const { steps, routes } = buildRemote(link);
```
Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter
from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and
nowhere else in the function.
The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between
requests, so a reconnected link is simply usable again on the next RPC.
- [ ] **Step 5: Run the full suite and the typechecker**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS, and no unused-symbol errors.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/mesh/
git commit -m "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."
```
---
## Task 4: An unreachable teapot does not stop the boot
**Files**
- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`)
- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`)
- Modify: `src/graph.ts:54` (the missing-dependency message)
- Test: `test/mesh/boot-retry.test.ts`
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/boot-retry.test.ts
it('boots when a teapot is unreachable and nothing local needs it', async () => {
const app = createApp({
modules: [LocalOnlyModule], // declares no needs on a remote token
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).resolves.toBeUndefined();
});
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
const app = createApp({
modules: [NeedsAuthModule], // a step with needs: ['auth']
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
});
it('still fails the boot when the teapot refuses the secret', async () => {
// stand up a teapot with secret 'right', connect with 'wrong'
await expect(app.ready()).rejects.toThrow(/refused/i);
});
```
- [ ] **Step 2: Run them and watch the first two fail**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message
(it says `missing dependency: auth` with no mention of the teapot), the third passes already.
- [ ] **Step 3: Make budget exhaustion non-fatal**
In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the
permanent-refusal `throw` (D4). Change the return type to `Promise<Link | undefined>` and replace
the exhaustion branch:
```ts
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// proxied route now, so an absent teapot costs a 503 on the requests that need it — and a
// teacup that refuses to start takes down the half of itself that never needed the teapot.
if (remaining <= 0) {
logger.warn(
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it; its steps and routes will 503`,
);
return undefined;
}
```
In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url:
```ts
const link = await connectUntilDeadline(/* … */);
if (!link) {
absent.push(teapot.url);
continue;
}
```
Return `absent` alongside `remoteRoutes` and `meshLinks`.
- [ ] **Step 4: Name the absent teapots in the missing-dependency error**
`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note
instead of mesh knowledge — note the capital S, and that `seedKeys` stays second:
```ts
// src/graph.ts:46
export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] {
```
and at the throw (`src/graph.ts:54`):
```ts
throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`);
```
The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its
signature rather than reaching for a module-level variable:
```ts
// src/app/index.ts:654 — finalizeGraph gains a trailing optional param
function finalizeGraph(
registry: Registry,
logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: (key: string) => string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
```
`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`:
```ts
// Without this the error is `missing dependency: auth needed by getUser` and says nothing about
// the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = absent.length
? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}`
: undefined;
```
The note is unconditional on the key rather than per-token on purpose: the teacup does not know
which teapot *would* have owned a token it never received a manifest for, and guessing would put a
wrong url in an error. Listing the ones that were away is true and enough.
- [ ] **Step 5: Run them and watch them pass**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: PASS, all three.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts
git commit -m "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."
```
---
## Task 5: The other runtimes
`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and
`src/app/index.ts` — exactly the code AGENTS.md says to run them for.
**Files**
- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`,
`test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts`
- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`
- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step**
```bash
grep -rn "export: true" test/deno test/bun test/interop test/edge
```
- [ ] **Step 2: Run each runtime suite**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a
mismatch here means one side was missed.
- [ ] **Step 3: Commit**
```bash
git add test/
git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge"
```
---
## Task 6: Say it in the docs
**Files**
- Modify: `README.md` (mesh section)
- Modify: `CHANGELOG.md` (`[Unreleased]`)
- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6)
- [ ] **Step 1: README**
In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails
at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`;
a missing token still fails the boot, and that is deliberate.
- [ ] **Step 2: CHANGELOG**
Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag
ships, never earlier.
```markdown
### Changed
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
at boot. 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 and cached for the life of the
process. Export a `@Step` instead — it runs on the teapot per request and returns its result.
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The
`bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without
that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still
fails the boot, and the error names the teapots that did not connect.
- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump,
which alpha permits and a stable version would not.
```
- [ ] **Step 3: Note the broken seam in the degrade plan**
Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a
runner, not a container binding.
- [ ] **Step 4: The full gate**
```bash
npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check
npm run test:deno && npm run test:bun && npm run test:edge
```
- [ ] **Step 5: Commit**
```bash
git add README.md CHANGELOG.md docs/plans/
git commit -m "docs(mesh): steps and routes are what a teapot exports"
```
---
## Size
Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new
subsystem, no new configuration, no background loop. The risk is not in the code but in the wire —
both peers change at once, which alpha allows and which the runtime suites are there to prove.
## Branch
From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes.
```bash
git fetch origin && git checkout -b feat/mesh-steps-only origin/develop
```
+8 -5
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 = {
name: 'step-logger',
mount(api) {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`)); 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' } });
+391 -529
View File
File diff suppressed because it is too large. Load diff
+11 -6
View File
@@ -1,6 +1,6 @@
{ {
"name": "@green-tea/core", "name": "@green-tea/core",
"version": "26.9.0-beta.1", "version": "26.9.0-beta.2",
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.", "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 <projects@expressive-tea.io>", "author": "green-tea contributors <projects@expressive-tea.io>",
@@ -26,7 +26,7 @@
"node" "node"
], ],
"engines": { "engines": {
"node": ">=18" "node": ">=22"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@@ -103,6 +103,9 @@
"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:compare": "tsx bench/compare.ts",
"bench:lookup": "tsx bench/lookup.ts",
"parity:mutants": "tsx test/router-parity/mutants.ts",
"parity:mutants:index": "tsx test/router-index-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"
}, },
@@ -128,7 +131,9 @@
"uuid": "11.1.1" "uuid": "11.1.1"
} }
}, },
"undici": "7.29.0" "undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.5", "@eslint/js": "^9.39.5",
@@ -140,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",
@@ -148,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",
@@ -158,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"
} }
} }
+142 -76
View File
@@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http'; import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web'; import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core'; import {
boundInbound,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
matchWsRoute,
runWsConnection,
trackUntil,
type WsRequest,
type WsSocket,
} from '../http/ws-core';
import { isAsyncIterable } from '../channel'; import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -39,7 +49,7 @@ import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router'; import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
@@ -59,7 +69,6 @@ interface Registry {
*/ */
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>; providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
routePlans: RoutePlan[]; routePlans: RoutePlan[];
exportedProviders: string[];
exportedSteps: string[]; exportedSteps: string[];
exportedRoutes: RouteEntry[]; exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner, framework?: boolean): void; setRunner(name: string, runner: Runner, framework?: boolean): void;
@@ -196,6 +205,8 @@ export function createApp(opts: {
); );
} }
validateWsLimits(opts.limits);
const bus = new Bus(); const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger(); const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger); if (opts.logRequests) logRequests(bus, logger);
@@ -222,8 +233,8 @@ export function createApp(opts: {
let remoteRoutes: RouteDef[] = []; let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
const finalize = (): void => { const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
booted = true; booted = true;
}; };
@@ -239,10 +250,15 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time. // can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => { const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) { if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container); const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
remoteRoutes = spliced.remoteRoutes; remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks); meshLinks.push(...spliced.meshLinks);
finalize(); // Without this the error is `missing dependency: auth needed by getUser` and says nothing
// about the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = spliced.absent.length
? ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}`
: undefined;
finalize(meshNote);
} }
meshControl = buildMeshControl(opts.mesh, registry, { meshControl = buildMeshControl(opts.mesh, registry, {
@@ -314,7 +330,7 @@ export function createApp(opts: {
devRoutes, devRoutes,
() => remoteRoutes, () => remoteRoutes,
); );
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
const listen = async (port: number): Promise<http.Server> => { const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps; const deps = pipelineDeps;
@@ -383,11 +399,12 @@ export function createApp(opts: {
return wrapped; return wrapped;
}; };
return { const app: App = {
listen, listen,
close, close,
handleSignals, handleSignals,
ready, ready,
boot: bootApp,
fetch: fetchFn, fetch: fetchFn,
upgrade: upgradeFn, upgrade: upgradeFn,
inspect, inspect,
@@ -400,6 +417,10 @@ export function createApp(opts: {
bus, bus,
logger, logger,
}; };
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
});
} }
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */ /** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
@@ -424,7 +445,6 @@ function emptyRegistry(): Registry {
providerMeta: new Map(), providerMeta: new Map(),
providerInstances: new Map(), providerInstances: new Map(),
routePlans: [], routePlans: [],
exportedProviders: [],
exportedSteps: [], exportedSteps: [],
exportedRoutes: [], exportedRoutes: [],
setRunner, setRunner,
@@ -437,7 +457,16 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
const meta = getProviderMeta(ProviderClass)!; const meta = getProviderMeta(ProviderClass)!;
registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
registry.providerMeta.set(meta.provides, { optional: meta.optional }); registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides); // A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
// resolved once and cached for the life of the process. A step is the shape that travels:
// it runs per request, on the teapot, and only its result comes back.
if (meta.export)
throw new Error(
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
const instance: any = new ProviderClass(); const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance); registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx)); registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
@@ -588,8 +617,19 @@ function buildTeardownRegistry(
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void { function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = []; const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) }; const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
// The name is the plugin's identity in `plugin:mounted` and in a mount failure, so two of them
// make both ambiguous. Two instances of one plugin are legitimate — they differ by `provides`,
// and the convention derives the name from it (.specs/2026-09-15, rule 2).
const seen = new Set<string>();
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn)); for (const plugin of plugins ?? []) {
if (seen.has(plugin.name)) {
throw new Error(`two plugins are named "${plugin.name}" — pass a different \`provides\` to one of them`);
}
seen.add(plugin.name);
mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
}
for (const scopeNode of extraSteps) { for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' }; const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -655,9 +695,10 @@ function finalizeGraph(
registry: Registry, registry: Registry,
logger: Logger, logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN, warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry; const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
const orderedSteps = ordered.filter((node) => stepNodes.includes(node)); const orderedSteps = ordered.filter((node) => stepNodes.includes(node));
const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins) const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins)
@@ -682,12 +723,24 @@ function finalizeGraph(
} }
} }
assertNeedsSatisfiable(routePlans, providerNodes, stepNodes); assertNeedsSatisfiable(routePlans, providerNodes, stepNodes, missingNote);
return { orderedProviders, orderedSteps }; return { orderedProviders, orderedSteps };
} }
/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */ /**
function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void { * Throws if any route needs a key that nothing provides, suggesting the nearest match.
*
* `missingNote` arrives only from a mesh boot, and only when a teapot did not connect. It changes
* what the message can honestly claim: "local or connected mesh" instead of "local or mesh", since
* the exports of an absent teapot were never searched — and it appends which teapots those were,
* which is the actual cause every time it is the cause.
*/
function assertNeedsSatisfiable(
routePlans: RoutePlan[],
providerNodes: GraphNode[],
stepNodes: GraphNode[],
missingNote?: string,
): void {
const producedKeys = new Set<string>([ const producedKeys = new Set<string>([
...providerNodes.flatMap((node) => node.provides), ...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides), ...stepNodes.flatMap((node) => node.provides),
@@ -713,8 +766,13 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
} }
const hint = nearest(need, allowed); const hint = nearest(need, allowed);
// "local or mesh" claims the mesh was consulted and came up empty — true only when every
// teapot connected. When one didn't, say "connected mesh" instead so the message doesn't
// assert a search that never happened, and let missingNote name which teapots were away.
const scope = missingNote ? 'local or connected mesh' : 'local or mesh';
throw new Error( throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, `handler '${plan.handlerName}' needs '${need}' but nothing (${scope}) provides it` +
`${hint ? ` — did you mean '${hint}'?` : ''}${missingNote ?? ''}`,
); );
} }
} }
@@ -725,20 +783,29 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
* *
* The grace exists because "the container is thirty seconds behind" and "the teapot does not * The grace exists because "the container is thirty seconds behind" and "the teapot does not
* exist" look identical for the first thirty seconds, and only one of them should stop a deploy. * exist" look identical for the first thirty seconds, and only one of them should stop a deploy.
* When the deadline passes it still throws: a provider the graph depends on is not optional, and
* booting without it would only move the failure to the first request, where it becomes a caller's
* 503 instead of the deploy's error.
* *
* Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator * Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator
* watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever * watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever
* collects lifecycle events rather than only to whoever is reading a terminal. * collects lifecycle events rather than only to whoever is reading a terminal.
*
* Exhausting the budget returns `undefined` rather than throwing (D4 keeps the one exception: a
* permanent refusal still does). Every export a teapot makes is lazy now — a request-scope step or
* a proxied route — so nothing needed this link resolved by boot, and a teacup that refuses to
* start takes down the half of itself that never needed the teapot.
*
* Returning `undefined` is not the same as degrading it. The caller registers nothing for a link it
* never got, because a teapot that did not connect sent no manifest and so nobody knows what it
* would have exported. Its routes 404 like any unregistered path, and a local node that needs one
* of its tokens still fails the boot in finalize(), named. Serving 503 for those tokens instead
* needs an `expects` declaration — see docs/plans/2026-08-18-mesh-degrade-plan.md, still planned.
*/ */
async function connectUntilDeadline( async function connectUntilDeadline(
mesh: MeshConfig, mesh: MeshConfig,
bus: Bus, bus: Bus,
logger: Logger, logger: Logger,
url: string,
attempt: () => Promise<Link>, attempt: () => Promise<Link>,
): Promise<Link> { ): Promise<Link | undefined> {
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000; const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
const deadline = Date.now() + budgetMs; const deadline = Date.now() + budgetMs;
let delay = 500; let delay = 500;
@@ -755,20 +822,29 @@ async function connectUntilDeadline(
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the // thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
// identical error, so it fails now. // identical error, so it fails now.
if (isPermanentRefusal(error)) { if (isPermanentRefusal(error)) {
logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`); logger.error(`mesh: teapot ${url} refused this peer, which retrying cannot fix — ${(error as Error).message}`);
throw error; throw error;
} }
// Rethrown as-is rather than wrapped: connectLink already says whether this was a refused // The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// handshake, a version mismatch or a timeout, and each sends you somewhere different. // proxied route now, so nothing needed this link resolved by boot, and a teacup that refuses
// to start takes down the half of itself that never needed the teapot. What starting does NOT
// do is degrade the dependency: an absent teapot sent no manifest, so it contributes no nodes
// at all — its routes 404 and a local `needs` on its tokens still fails in finalize().
if (remaining <= 0) { if (remaining <= 0) {
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`); logger.warn(
throw error; `mesh: teapot ${url} unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it. No manifest was ever exchanged, ` +
`so none of its steps or routes are in this graph: its routes 404 like any path that ` +
`was never registered, and the boot still fails if anything local needs one of its ` +
`tokens. This line is what a later 404 on one of its routes points back to.`,
);
return undefined;
} }
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error }); bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
logger.warn( logger.warn(
`mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`, `mesh: teapot ${url} unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`,
); );
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining)))); await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
delay = Math.min(delay * 2, 5_000); delay = Math.min(delay * 2, 5_000);
@@ -796,38 +872,22 @@ function warnIfCleartext(url: string, logger: Logger): void {
); );
} }
/** /** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
*
* Named and separate rather than inlined in the reconnect handler: this is the seam a future
* `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice.
*
* Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a
* network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection.
*/
function invalidateRemoteBindings(rebind: Array<() => void>): void {
for (const bind of rebind) bind();
}
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
async function spliceRemoteScopes( async function spliceRemoteScopes(
mesh: MeshConfig, mesh: MeshConfig,
bus: Bus, bus: Bus,
registry: Registry, registry: Registry,
logger: Logger, logger: Logger,
container: Container, ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
const remoteRoutes: RouteDef[] = []; const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
try { try {
for (const teapot of mesh.teapots ?? []) { for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger); warnIfCleartext(teapot.url, logger);
// Deferred so the reconnect callback can name this link's provider tokens, which are only const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
// known once its manifest arrives — the callback is registered before the link can drop.
const rebind: Array<() => void> = [];
const link = await connectUntilDeadline(mesh, bus, logger, () =>
connectLink({ connectLink({
url: teapot.url, url: teapot.url,
secret: teapot.secret, secret: teapot.secret,
@@ -835,25 +895,20 @@ async function spliceRemoteScopes(
heartbeatMs: mesh.heartbeatMs, heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect, reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange, onManifestChange: mesh.onManifestChange,
onReconnect: () => invalidateRemoteBindings(rebind),
logger, logger,
bus, bus,
}), }),
); );
meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
for (const provider of providers) { if (!link) {
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin }); absent.push(teapot.url);
registry.providerMeta.set(provider.name, { optional: false }); continue;
registry.setRunner(provider.name, provider.run);
// A remote app-scope value is resolved once at boot and frozen into the container, so it
// would keep answering from a cache the teapot no longer stands behind. Re-registering
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
} }
meshLinks.push(link);
const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
for (const step of steps) { for (const step of steps) {
registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin }); registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin });
registry.setRunner(step.name, step.run); registry.setRunner(step.name, step.run);
@@ -897,7 +952,9 @@ async function spliceRemoteScopes(
); );
} }
remoteRoutes.push({ // Marked so the router files it in the remote tree; precedence is unchanged by the split.
remoteRoutes.push(
markRemoteRoute({
method: route.method, method: route.method,
pattern: route.pattern, pattern: route.pattern,
transport: 'buffer', transport: 'buffer',
@@ -914,7 +971,8 @@ async function spliceRemoteScopes(
url: req.url, url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId }, correlation: { requestId: req.requestId, traceId: req.traceId },
}), }),
}); }),
);
} }
} }
} catch (err) { } catch (err) {
@@ -922,7 +980,7 @@ async function spliceRemoteScopes(
throw err; throw err;
} }
return { remoteRoutes, meshLinks }; return { remoteRoutes, meshLinks, absent };
} }
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -1075,8 +1133,8 @@ function buildMeshControl(
registry: Registry, registry: Registry,
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps }, deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
): MeshControl | undefined { ): MeshControl | undefined {
const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry; const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length; const hasExports = exportedSteps.length || exportedRoutes.length;
if (hasExports && !mesh?.secret) { if (hasExports && !mesh?.secret) {
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel'); throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
@@ -1085,7 +1143,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined; if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps; const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError, logger } = deps.deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it // context is intentionally `any`: providers and steps merge arbitrary keys into it
@@ -1236,22 +1294,30 @@ function buildAppUpgrade(
streams: Set<() => void>, streams: Set<() => void>,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined, getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
): (request: WsRequest, socket: WsSocket) => Promise<void> { ): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined; let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => { return async (request: WsRequest, socket: WsSocket): Promise<void> => {
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no // Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
// subscriber is dropped, so anything the peer sends while providers are still booting would be // with no subscriber is dropped, so anything the peer sends while providers are still booting
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang // would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// until timeout against a teapot whose providers happened to boot slowly. // hang until timeout against a teapot whose providers happened to boot slowly.
const frames = socket.inbound[Symbol.asyncIterator](); const ready = boundInbound(socket, limits);
const ready: WsSocket = Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
}) as WsSocket;
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
const path = request.url.split('?')[0]; let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
// otherwise reject out of the matcher and close with 1011, a server-error code for a client error.
try {
path = normalizeRequestPath(request.url.split('?')[0]);
} catch {
ready.close(1008, 'invalid request path');
return;
}
const meshControl = getMeshControl(); const meshControl = getMeshControl();
// The reserved mesh path, checked before route matching: this is what lets a teapot export // The reserved mesh path, checked before route matching: this is what lets a teapot export
@@ -1450,8 +1516,8 @@ function closeApp(
timeoutMs, timeoutMs,
}); });
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections() // closeAllConnections() and closeIdleConnections() below both arrived in Node 18.2;
// below — `engines` in package.json only guarantees >=18, so this matters. // `engines` guarantees >=22, so both are always present.
server.closeAllConnections(); server.closeAllConnections();
finish(); finish();
}, drainBudget); }, drainBudget);
+27 -5
View File
@@ -59,6 +59,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. */
@@ -136,12 +152,18 @@ export interface MeshConfig {
* so 30s). Attempts use the same backoff as reconnection. * 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 * 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. A teapot that is * has not settled — should not fail a deploy, and this is the grace for that. When the deadline
* genuinely absent still fails the boot when the deadline passes, because a provider the graph * passes the teacup warns and starts anyway: every export is a step or a proxied route, so
* depends on is not optional: booting without it would only move the failure to the first * nothing needed that link resolved by boot.
* request, where it is somebody else's 503 instead of your deploy's error.
* *
* `0` restores the old behaviour of a single attempt. * 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.
*
* `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; bootTimeoutMs?: number;
} }
+24 -2
View File
@@ -1,9 +1,10 @@
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, type WsSocket, type WsRequest } from './http/ws-core';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown'; 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.
@@ -15,6 +16,7 @@ interface BunServerWebSocket {
terminate?(): void; terminate?(): void;
} }
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;
@@ -74,8 +76,20 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
* (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 * Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy. * 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): BunServeResult { export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
// 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({ const server = Bun.serve({
...options, ...options,
fetch(request, server) { fetch(request, server) {
@@ -88,9 +102,17 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
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.
setPeer(request, server.requestIP(request)?.address ?? '');
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. It drops the connection without a close frame, so the peer sees 1006 rather
// than 1009 — verified on Bun 1.3, and the price of not buffering the message at all.
// `app.upgrade` checks the same bound again on the decoded text.
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;
+31 -2
View File
@@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
} }
/**
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
* because each tsup entry carries its own copy of this module.
*/
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
export interface ChannelSink<T> {
push(value: T): void;
end(): void;
fail(err: unknown): void;
}
/** A channel that can be tapped; every channel built by {@link channel} is one. */
export interface TappableChannel<T> extends Channel<T> {
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
}
interface Sub<T> { interface Sub<T> {
iterator: AsyncIterator<T>; iterator: AsyncIterator<T>;
push(value: T, cap: number): void; push(value: T, cap: number): void;
@@ -84,9 +104,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * 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 +137,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);
},
}; };
} }
+19 -3
View File
@@ -1,9 +1,10 @@
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 { closeWithDeadline } from './http/shutdown'; 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;
} }
@@ -51,8 +52,20 @@ declare const Deno: {
* 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 * Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy. * 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): DenoServer { export async function serveDeno(app: App, options?: DenoServeOptions): Promise<DenoServer> {
// 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 // 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 // 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. // server — it is chained into ours rather than replaced, so neither party loses its control.
@@ -70,6 +83,9 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
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);
}); });
+2 -2
View File
@@ -43,7 +43,7 @@ export interface GraphNode {
} }
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ /** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): 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) producedBy.set(key, node);
@@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
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) && !producedBy.has(key)) {
throw new Error(`missing dependency: ${key} needed by ${node.name}`); throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
} }
} }
} }
+14 -6
View File
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
/** /**
* Reads the raw request body, enforcing `limit`. * Reads the raw request body, enforcing `limit`.
* *
* The adapter owns this and nothing else about the body, because enforcement is the one place the * The adapter owns this and nothing else about the body, because getting the bytes is the one place
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a * the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check * Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer * limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer * possible — measuring afterwards would force the reader to buffer without bound first.
* without bound first.
* *
* The failure branch is opaque on purpose: Node answers an over-limit request with * 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. * `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
@@ -41,6 +40,15 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
*/ */
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>; export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/**
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
* and the running total still enforces the limit on whatever actually arrives.
*/
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */ /** 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 }; type ParseResult = { body: unknown } | { error: string; status?: number };
+5 -21
View File
@@ -9,31 +9,15 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/** /**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import. * `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
* *
* The web-standard global stays the primary path, and that is deliberate rather than stylistic: * Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a * Node 18 floor.
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
*
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release.
*
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
*/ */
const randomUUID: () => string = (() => { const randomUUID = (): string => crypto.randomUUID();
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
/** /**
* A runtime-neutral inbound request. * A runtime-neutral inbound request.
+27
View File
@@ -0,0 +1,27 @@
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
// Internal: not exported from the package.
//
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
// bare `app.fetch` from user code has always seen.
//
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
// with no shared chunk, so each carries its own copy of this one: a module-private map in
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
// that loads core both as ESM and as CommonJS has the same split.
const KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, ip: string): void {
if (ip) peers.set(request, ip);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
+5
View File
@@ -1,8 +1,13 @@
import type http from 'http'; import 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 async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
// A declared length over the limit is refused without waiting for the first chunk, which could
// otherwise sit until the request timeout. The fetch adapter makes the same check.
if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large');
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let total = 0; let total = 0;
+301 -53
View File
@@ -325,65 +325,305 @@ function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
return 0; return 0;
} }
/** One route with its pattern already compiled. Built once per table, ordered within its method. */ /**
interface IndexedRoute { * One route at a terminal of the index.
*
* `rank` is the route's place in its method's specificity order — exactly the order the linear
* matcher sorted its bucket into: `moreSpecific` first, declaration order on ties. Lower wins. The
* tree only decides which routes *can* match; this number alone decides which one *does*, so the
* shape of the tree can never override the global ranking (two overlapping constraints, a catch-all
* at one depth against a param at another, an equal-rank tie).
*/
interface Terminal {
def: RouteDef; def: RouteDef;
compiled: CompiledPattern; compiled: CompiledPattern;
rank: number;
/** Position in the route array the index was built from. Breaks a tie between the two trees. */
order: number;
/** Every segment static: the route has no params to collect. */
allStatic: boolean;
}
/** A `:param` edge. Plain params share one edge; constrained ones share an edge per constraint source. */
interface ParamEdge {
constraintSource: string | undefined;
constraint: RegExp | undefined;
node: RadixNode;
}
// ponytail: a segment trie — one edge per whole path segment, no compression of single-child static
// chains. Lookup cost already follows path depth, not route count; compressing would save a few map
// hops on long static prefixes and costs a split/merge routine nobody has measured a need for.
interface RadixNode {
statics: Map<string, RadixNode>;
params: ParamEdge[];
/** Routes whose last segment ends at this node, by rank. */
exact: Terminal[];
/** Catch-all routes whose fixed prefix ends at this node, by rank. They match zero or more segments. */
catchAll: Terminal[];
/** Lowest rank anywhere below this node: a branch that cannot beat the best match so far is skipped. */
min: number;
}
/** One method's routes: the tree, plus its all-static routes by exact path. */
interface MethodTree {
root: RadixNode;
/**
* All-static routes keyed by their normalized pattern, by rank. A hit here is the tree's best
* match for that path: any other non-catch-all route matching it has as many segments, none of
* them more specific than static, and every catch-all ranks below every exact route. So a static
* request is answered without splitting the path. A miss proves nothing and falls through to the
* walk, as does a path spelled differently from its pattern (`/a/`, `/a//b` on a direct call).
*/
exactPaths: Map<string, Terminal[]>;
} }
/** /**
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array * The lookup index for one route array: a tree per HTTP method, local and remote kept apart.
* they were built from. *
* Mesh-spliced remote routes get their own trees so they can later be rebuilt alone when peers come
* and go. Precedence stays the single list's: both trees answer, the more specific match wins, and
* a tie goes to the earlier declaration — a local one, since local routes come first.
*/
interface RouteIndex {
/** Length of the array at build time; a cached index for an array that has since grown or shrunk is rebuilt. */
size: number;
local: Map<string, MethodTree>;
/** Absent for an app without mesh routes, which then does a single lookup. */
remote: Map<string, MethodTree> | undefined;
/** Every method with at least one route, in either tree. */
methods: string[];
}
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
const remoteRouteDefs = new WeakSet<RouteDef>();
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def);
return def;
}
/**
* Route indexes keyed by the identity of the array they were built from.
* *
* A server hands the same array to every request, so this is built once and collected with the * A server hands the same array to every request, so this is built once and collected with the
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a * table it describes. Both callers (`buildAppFetch` and `listen()`) assemble that array after boot,
* different array and gets its own index, so nothing has to remember to invalidate anything. * from local, remote and dev routes, and never touch it again. A table assembled fresh is a
* different array and gets its own index.
*/ */
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>(); const routeIndexCache = new WeakMap<RouteDef[], RouteIndex>();
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> { function newNode(): RadixNode {
const cached = routeIndexCache.get(routes); return { statics: new Map(), params: [], exact: [], catchAll: [], min: Infinity };
if (cached) return cached; }
const byMethod = new Map<string, IndexedRoute[]>(); function childFor(node: RadixNode, segment: Exclude<CompiledSegment, { kind: 'catchAll' }>): RadixNode {
if (segment.kind === 'static') {
for (const def of routes) { let next = node.statics.get(segment.value);
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) }; if (!next) node.statics.set(segment.value, (next = newNode()));
const bucket = byMethod.get(def.method); return next;
if (bucket) bucket.push(entry);
else byMethod.set(def.method, [entry]);
} }
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns let edge = node.params.find((candidate) => candidate.constraintSource === segment.constraintSource);
// keep registration order — which is exactly what the old scan did by refusing to replace its
// best on a tie.
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
routeIndexCache.set(routes, byMethod); if (!edge) {
return byMethod; edge = { constraintSource: segment.constraintSource, constraint: segment.constraint, node: newNode() };
node.params.push(edge);
}
return edge.node;
} }
/** Files one terminal. Insertion runs in rank order, so every list stays sorted and `min` is set once. */
function insert(tree: MethodTree, terminal: Terminal): void {
let node = tree.root;
if (node.min === Infinity) node.min = terminal.rank;
for (const segment of terminal.compiled.segments) {
if (segment.kind === 'catchAll') {
node.catchAll.push(terminal);
return;
}
node = childFor(node, segment);
if (node.min === Infinity) node.min = terminal.rank;
}
node.exact.push(terminal);
if (terminal.allStatic) {
const key = terminal.compiled.normalized;
const same = tree.exactPaths.get(key);
if (same) same.push(terminal);
else tree.exactPaths.set(key, [terminal]);
}
}
/** Builds one tree per method from `(route, array position)` pairs, ranked as the linear matcher sorted them. */
function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
const byMethod = new Map<string, Terminal[]>();
for (const { def, order } of entries) {
const compiled = compilePattern(def.pattern);
const allStatic = compiled.segments.every((segment) => segment.kind === 'static');
const terminal: Terminal = { def, compiled, rank: 0, order, allStatic };
const bucket = byMethod.get(def.method);
if (bucket) bucket.push(terminal);
else byMethod.set(def.method, [terminal]);
}
const trees = new Map<string, MethodTree>();
for (const [method, bucket] of byMethod) {
// `sort` is stable, so equal patterns keep registration order.
bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
const tree: MethodTree = { root: newNode(), exactPaths: new Map() };
bucket.forEach((terminal, rank) => insert(tree, Object.assign(terminal, { rank })));
trees.set(method, tree);
}
return trees;
}
function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached;
const local: Array<{ def: RouteDef; order: number }> = [];
const remote: Array<{ def: RouteDef; order: number }> = [];
routes.forEach((def, order) => (remoteRouteDefs.has(def) ? remote : local).push({ def, order }));
const index: RouteIndex = {
size: routes.length,
local: buildTrees(local),
remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))],
};
routeIndexCache.set(routes, index);
return index;
}
/**
* One request's lookup state, shared by every tree it searches: the path, its segments (split only
* if a walk needs them), decoded values memoized by position, and the current search's filter and
* best terminal. One object per call rather than one per tree keeps the small-table cost down.
*/
interface Search {
path: string;
segs: string[] | undefined;
decoded: Array<string | undefined>;
accept: ((def: RouteDef) => boolean) | undefined;
best: Terminal | undefined;
}
/** Placeholder until a walk splits the path; nothing reads or writes it before then. */
const NO_DECODED: Array<string | undefined> = [];
function newSearch(path: string): Search {
return { path, segs: undefined, decoded: NO_DECODED, accept: undefined, best: undefined };
}
function segmentsOf(search: Search): string[] {
if (search.segs) return search.segs;
const segs = splitPath(search.path);
search.segs = segs;
search.decoded = new Array(segs.length);
return segs;
}
/** Takes the best-ranked acceptable terminal of a rank-ordered list, if it beats the best so far. */
function offer(search: Search, terminals: Terminal[]): void {
for (let i = 0; i < terminals.length; i++) {
const terminal = terminals[i];
if (search.best && terminal.rank >= search.best.rank) return;
if (search.accept && !search.accept(terminal.def)) continue;
search.best = terminal;
return;
}
}
/**
* 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.
*
* 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(node: RadixNode, search: Search, segs: string[], depth: number): void {
if (search.best && node.min >= search.best.rank) return;
if (depth === segs.length) {
if (node.exact.length) offer(search, node.exact);
} else {
const segment = segs[depth];
const next = node.statics.size ? node.statics.get(segment) : undefined;
if (next) walk(next, search, segs, depth + 1);
const params = node.params;
for (let i = 0; i < params.length; i++) {
const edge = params[i];
const value = (search.decoded[depth] ??= decodeSegment(segment));
if (edge.constraint && !edge.constraint.test(value)) continue;
walk(edge.node, search, segs, depth + 1);
}
}
if (node.catchAll.length) offer(search, node.catchAll);
}
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), 0);
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. * Finds the most specific route matching both method and path; ties keep registration order.
* *
* The ranking is settled when the table is built, not per request: the answer cannot change between * The ranking is settled when the index is built, not per request. What is left here is a walk down
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific` * the method's tree that visits only the branches the path can follow.
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
* table. What is left here is a walk that stops at the first match.
*/ */
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
const candidates = routeIndex(routes).get(method); const search = newSearch(path);
if (!candidates) return undefined; const hit = findRoute(routeIndex(routes), method, search);
return hit && { params: paramsOf(hit, search), def: hit.def };
const pathSegs = splitPath(path);
const decoded: Array<string | undefined> = new Array(pathSegs.length);
for (const { def, compiled } of candidates) {
const params = matchCompiled(compiled, pathSegs, decoded);
if (params) return { params, def };
}
return undefined;
} }
/** 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. */
@@ -392,29 +632,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 pathSegs = splitPath(path); 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 (!matchCompiled(compilePattern(route.pattern), pathSegs)) 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');
+43 -3
View File
@@ -18,6 +18,7 @@ import {
} from './core'; } from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
interface HandlerConfig { interface HandlerConfig {
@@ -78,7 +79,7 @@ export function createHttpServer(
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;
} }
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => { // `http.createServer` ignores the promise a listener returns, so a rejection that escapes `serve`
// would be an `unhandledRejection` — and under Node's default mode, the end of the process.
// Caught here, at the one place every request passes through (#108).
return (req: http.IncomingMessage, res: http.ServerResponse): void => {
serve(req, res).catch((err: unknown) => failSafe(res, err, opts?.logger));
};
async function serve(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
// Install the security-header patch BEFORE any routing/response so every path // 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);
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
res.writeHead(result.outcome.status, result.outcome.headers); res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body); res.end(result.outcome.body);
}; }
}
/**
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
* runs because something already failed past the point where errors convert to a response, and user
* code that may be the thing failing is the wrong place to send it. Must never throw — nothing
* catches it.
*
* Writable: a fixed 500 with `connection: close`, still through the patched `writeHead`, so the
* security headers land. Output already started, or the client gone: there is no honest response
* left to send, so the socket is destroyed and the client sees a truncated reply rather than a
* complete-looking one. No `request:end` is emitted — observers do not alter the response, and the
* core never completed this request.
*/
function failSafe(res: http.ServerResponse, err: unknown, logger: Logger | undefined): void {
try {
logger?.error('request listener failed', { err: err instanceof Error ? err.message : String(err) });
} catch {
/* a broken logger must not stop the response below */
}
if (res.headersSent || res.destroyed || !res.writable) {
res.destroy();
return;
}
try {
res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
res.end('{"error":"Internal Server Error"}');
} catch {
res.destroy();
}
} }
/** /**
+25
View File
@@ -16,6 +16,31 @@ export interface RequestLimits {
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`). Bun then drops the connection without a close frame, so on Bun the peer
* sees `1006` instead of `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. */
+66 -18
View File
@@ -11,7 +11,8 @@ import {
type Preflight, type Preflight,
} from './core'; } from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body'; import { peerOf } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
@@ -97,9 +98,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
/** /**
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer. * The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
* *
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body * Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* or not at all, so the limit can only be checked once the bytes are already in memory. That * the whole body or not at all and so could only check the limit once every byte was in memory.
* difference is exactly why the limit is passed in rather than applied by the shared core. * Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
*/ */
function readFetchBytes( function readFetchBytes(
source: unknown, source: unknown,
@@ -110,8 +111,54 @@ function readFetchBytes(
// Not `async`: a bodiless request answers without allocating a promise at all. // Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined }; if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => { // A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
if (arrayBuffer.byteLength > limit) { // effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
request.body.cancel().catch(() => {});
return tooLarge(request, opts);
}
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
return readBounded(request.body.getReader(), limit).then((bytes) =>
bytes === null ? tooLarge(request, opts) : { bytes },
);
}
/**
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
* propagates exactly as a rejected `arrayBuffer()` used to.
*
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
* The answer is the same 413 either way; only how early it comes differs.
*/
async function readBounded(
reader: ReadableStreamDefaultReader<Uint8Array>,
limit: number,
): Promise<Buffer | undefined | null> {
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
reader.cancel().catch(() => {});
return null;
}
chunks.push(value);
}
return total === 0 ? undefined : Buffer.concat(chunks, total);
}
/** The over-limit answer, shared by the declared-length check and the stream count. */
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and // 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. // a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url); const url = new URL(request.url);
@@ -121,10 +168,6 @@ function readFetchBytes(
headers: headersToRecord(request.headers), headers: headersToRecord(request.headers),
}; };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) }; return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
} }
/** /**
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
return new Response(body, { status: result.outcome.status, headers }); return new Response(body, { status: result.outcome.status, headers });
} }
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim();
}
/** /**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it * describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
@@ -244,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
source: request, source: request,
secure, secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the // 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 // proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
// there's no socket peer address to fall back to on the fetch path, so the untrusted case // Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// is simply ''. // `app.fetch` has none, so there the answer is still ''.
ip: opts?.trustProxy ip: forwardedFor(headers, opts) || peerOf(request),
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
}, },
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request. // one call per request.
+19 -5
View File
@@ -1,4 +1,4 @@
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 type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
*/ */
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()). */
@@ -69,7 +70,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);
},
});
} }
/** /**
@@ -79,7 +91,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
*/ */
export function neutralSocket( export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void }, host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>, inbound: Channel<unknown>,
ac: AbortController, ac: AbortController,
): WsSocket { ): WsSocket {
return { return {
@@ -112,8 +124,10 @@ export function neutralSocket(
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
+215 -1
View File
@@ -1,8 +1,9 @@
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { correlateRequest } from './core'; 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 {
@@ -22,6 +23,219 @@ export interface WsSocket {
terminate(): void; terminate(): void;
} }
/** 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;
}
/** 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.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
): 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() } },
}) 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 readonly maxBytes: number,
private readonly maxQueue: number,
) {
this.first = this.add();
}
/**
* 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. */
export function matchWsRoute( export function matchWsRoute(
wsRoutes: WsRouteDef[], wsRoutes: WsRouteDef[],
+64 -14
View File
@@ -1,8 +1,17 @@
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,
wsMessageBytes,
type WsSocket,
type WsRequest,
} from './ws-core';
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
import { normalizeRequestPath } from './router';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
/** 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. */
@@ -16,9 +25,9 @@ function loadWss(): any | 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,11 +40,12 @@ 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;
} }
@@ -45,7 +55,7 @@ function handleMeshUpgrade(
// 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 neutral = boundInbound(nodeSocket(ws), limits);
void trackUntil(neutral, meshControl.handle(neutral), streams); void trackUntil(neutral, meshControl.handle(neutral), streams);
}); });
@@ -97,29 +107,69 @@ 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;
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.
try {
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
} catch {
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
else socket.destroy();
}
});
}
/** What every upgrade on one server shares. */
interface UpgradeEnv {
wss: any;
wsRoutes: WsRouteDef[];
bus?: Bus;
meshControl?: MeshControl;
streams?: Set<() => void>;
limits?: RequestLimits;
}
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
const { wss, 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(wss, meshControl, path, req, socket, head, streams, limits)) return;
const route = matchWsRoute(wsRoutes, path); const route = matchWsRoute(wsRoutes, path);
if (!route) { if (!route) {
socket.destroy(); rejectUpgrade(socket, 404, 'Not Found');
return; return;
} }
if (!wss) { if (!wss) {
reject501(socket); rejectUpgrade(socket, 501, 'Not Implemented');
return; return;
} }
wss.handleUpgrade(req, socket, head, (ws: any) => { wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
});
}); });
} }
+15 -2
View File
@@ -5,8 +5,16 @@
*/ */
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';
@@ -56,7 +64,12 @@ 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';
+28 -16
View File
@@ -218,7 +218,7 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs // `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
// the graph is refused after this point, and announcing a connection we are about to hang up on // the graph is refused after this point, and announcing a connection we are about to hang up on
// would tell an operator the opposite of what happened. // would tell an operator the opposite of what happened.
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat }); hs.resolve({ socket: hs.socket, manifest: { steps: frame.steps, routes: frame.routes }, heartbeat });
} }
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */ /** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
@@ -323,9 +323,9 @@ function openSession(args: SessionArgs): Promise<Session> {
}); });
} }
/** A scope token and its lifetime, flattened to the string the refusal check compares. */ /** A manifest's step tokens, flattened to the set the refusal check compares. */
function scopeKeys(manifest: Manifest): Set<string> { function stepKeys(manifest: Manifest): Set<string> {
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`)); return new Set(manifest.steps);
} }
/** /**
@@ -345,12 +345,12 @@ function routeKeys(manifest: Manifest): Set<string> {
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it. * missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
*/ */
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] { export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const scopes = scopeKeys(returned); const steps = stepKeys(returned);
const routes = routeKeys(returned); const routes = routeKeys(returned);
const missing: string[] = []; const missing: string[] = [];
for (const scope of booted.scopes) { for (const step of booted.steps) {
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`); if (!steps.has(step)) missing.push(`step '${step}'`);
} }
for (const route of booted.routes) { for (const route of booted.routes) {
@@ -393,8 +393,6 @@ export function connectLink(args: {
reconnect?: boolean | ReconnectOptions; reconnect?: boolean | ReconnectOptions;
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */ /** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy; onManifestChange?: ManifestPolicy;
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
onReconnect?: () => void;
logger?: Logger; logger?: Logger;
}): Promise<Link> { }): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000; const timeoutMs = args.timeoutMs ?? 30_000;
@@ -407,7 +405,7 @@ export function connectLink(args: {
const link: Link = { const link: Link = {
// replaced with the real manifest before this object escapes; a reconnect never changes it, // replaced with the real manifest before this object escapes; a reconnect never changes it,
// because the graph is fixed at boot and only the *boot* manifest describes what it holds. // because the graph is fixed at boot and only the *boot* manifest describes what it holds.
manifest: { scopes: [], routes: [] }, manifest: { steps: [], routes: [] },
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs), rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
close: () => { close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
@@ -453,7 +451,7 @@ export function connectLink(args: {
}; };
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */ /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => { const adopt = (session: Session): boolean => {
const missing = missingFromManifest(link.manifest, session.manifest); const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) { if (missing.length > 0) {
@@ -478,7 +476,6 @@ export function connectLink(args: {
refusalLogged = ''; refusalLogged = '';
state.socket = session.socket; state.socket = session.socket;
args.bus?.emit('mesh:connect', { name: args.url }); args.bus?.emit('mesh:connect', { name: args.url });
if (reconnected) args.onReconnect?.();
return true; return true;
}; };
@@ -494,7 +491,7 @@ export function connectLink(args: {
return; return;
} }
if (!adopt(session, attempt, true)) scheduleRetry(attempt); if (!adopt(session)) scheduleRetry(attempt);
} catch { } catch {
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection // openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead. // that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
@@ -502,10 +499,25 @@ export function connectLink(args: {
} }
}; };
return openSession(sessionArgs(() => endSession(0))).then((session) => { return openSession(sessionArgs(() => endSession(0))).then(
(session) => {
link.manifest = session.manifest; link.manifest = session.manifest;
adopt(session, 0, false); adopt(session);
return link; return link;
}); },
(error) => {
// The first connect failed, so this `Link` never escaped — nobody holds it and nobody can
// ever call `close()` on it. But `openSession`'s abort listener has already run `onEnd`,
// which scheduled a retry: left alone, that supervisor reconnects forever to a handle no
// caller has, and `closeLinks` cannot reach it because the link was never pushed to
// `meshLinks`. Boot already retries above this (`connectUntilDeadline`), so a second
// supervisor underneath it is pure leak — every failed attempt used to leave one behind.
// Reconnection for a link that *did* connect is untouched: this path runs only on the
// initial rejection, and a session that drops later still goes through `endSession`.
state.closed = true;
clearTimeout(state.retry);
throw error;
},
);
} }
+29 -9
View File
@@ -18,6 +18,14 @@
* *
* Bumping per change would make the number mean "work happened" rather than "we are * Bumping per change would make the number mean "work happened" rather than "we are
* incompatible", which is the one thing it is here to say. * incompatible", which is the one thing it is here to say.
*
* **One exception has been taken, and its terms are the point.** The manifest's `scopes` field was
* renamed to `steps` at v1 — a rename, which the first rule above would otherwise cover — without a
* bump. It was allowed because there is no deployed pair the rename could split: mesh is alpha,
* every app using it is gated behind `experimental: true`, and both peers ship out of this one
* repo, so a teacup and a teapot are always on the same version. Each of those three has to hold
* for the exception to; the first mesh release that drops `experimental` retires it, and a rename
* after that earns a bump like any other.
*/ */
export const MESH_PROTOCOL_VERSION = 1; export const MESH_PROTOCOL_VERSION = 1;
@@ -43,19 +51,21 @@ export interface RequestEnvelope {
correlation?: { requestId?: string; traceId?: string }; correlation?: { requestId?: string; traceId?: string };
} }
/** Manifest entry for an exported scope token and its lifetime. */
export interface ScopeEntry {
token: string;
scope: 'app' | 'request';
}
/** Manifest entry for an exported route. */ /** Manifest entry for an exported route. */
export interface RouteEntry { export interface RouteEntry {
method: string; method: string;
pattern: string; pattern: string;
} }
/** A mesh server's advertised scopes and routes. */
/**
* A mesh server's advertised steps and routes.
*
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
* lazy — the token exists in the teacup's graph, and running it is an RPC.
*/
export interface Manifest { export interface Manifest {
scopes: ScopeEntry[]; steps: string[];
routes: RouteEntry[]; routes: RouteEntry[];
} }
@@ -68,7 +78,7 @@ export interface Manifest {
*/ */
export type Frame = export type Frame =
| { type: 'hello'; v: number; secret: string } | { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
| { type: 'rpc-res'; id: string; ok: true; result: unknown } | { type: 'rpc-res'; id: string; ok: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } } | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
@@ -78,6 +88,9 @@ export type Frame =
const isString = (value: unknown): value is string => typeof value === 'string'; const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number'; const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null; const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
/** A manifest route entry: both fields reach `compilePattern`, so both must really be strings. */
const isRouteEntry = (value: unknown): boolean =>
isObject(value) && isString((value as RouteEntry).method) && isString((value as RouteEntry).pattern);
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */ /** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void; type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
@@ -94,7 +107,14 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
}, },
manifest: (frame, bad) => { manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version'); if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays'); if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
// Array.isArray above already guarantees this, but TS does not carry that narrowing through a
// `never`-typed callback parameter — the cast is safe, not a bypass.
if (!(frame.steps as unknown[]).every(isString)) bad('every step must be a string');
// Checked for the same reason steps are: past `decode` a route entry goes straight to
// `compilePattern`, where a non-string `pattern` dies as a boot `TypeError` about a peer's
// frame — a failure that reads like a green-tea bug rather than a malformed manifest.
if (!(frame.routes as unknown[]).every(isRouteEntry)) bad('every route must have a string method and pattern');
}, },
'rpc-req': (frame, bad) => { 'rpc-req': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string'); if (!isString(frame.id)) bad('id must be a string');
+8 -17
View File
@@ -37,27 +37,18 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
}; };
} }
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */ /** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
export function buildRemote(link: Link): { export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
providers: RemoteScopeNode[]; const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
steps: RemoteScopeNode[]; name: token,
routes: RemoteRoute[]; run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
} { }));
const providers: RemoteScopeNode[] = [];
const steps: RemoteScopeNode[] = [];
for (const scope of link.manifest.scopes) {
const node: RemoteScopeNode = {
name: scope.token,
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
};
(scope.scope === 'app' ? providers : steps).push(node);
}
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({ const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method, method: route.method,
pattern: route.pattern, pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape, handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
})); }));
return { providers, steps, routes };
return { steps, routes };
} }
+5 -15
View File
@@ -42,19 +42,9 @@ const HANDSHAKE_TIMEOUT_MS = 10_000;
*/ */
const MAX_FRAME_CHARS = 4_000_000; const MAX_FRAME_CHARS = 4_000_000;
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */ /** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
providers: string[]; // exported provider tokens (app-scope) return { steps: [...args.steps], routes: args.routes };
steps: string[]; // exported step tokens (request-scope)
routes: RouteEntry[]; // exported buffered routes
}): Manifest {
return {
scopes: [
...args.providers.map((token) => ({ token, scope: 'app' as const })),
...args.steps.map((token) => ({ token, scope: 'request' as const })),
],
routes: args.routes,
};
} }
function safeEqual(left: string, right: string): boolean { function safeEqual(left: string, right: string): boolean {
@@ -115,7 +105,7 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
encode({ encode({
type: 'manifest', type: 'manifest',
v: MESH_PROTOCOL_VERSION, v: MESH_PROTOCOL_VERSION,
scopes: deps.manifest.scopes, steps: deps.manifest.steps,
routes: deps.manifest.routes, routes: deps.manifest.routes,
}), }),
); );
@@ -244,7 +234,7 @@ export function createMeshControl(deps: MeshControlDeps): {
path: string; path: string;
handle: (socket: WsSocket) => Promise<void>; handle: (socket: WsSocket) => Promise<void>;
} { } {
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedScopes = new Set(deps.manifest.steps);
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return { return {
+11 -7
View File
@@ -15,6 +15,12 @@ export interface ProviderMeta {
provides: string; provides: string;
needs: string[]; needs: string[];
optional: boolean; optional: boolean;
/**
* Always refused. `@Provider`'s options no longer declare `export`, so TypeScript rejects it at
* the decorator and this can only be true for a JavaScript caller. It is still recorded so that
* caller reaches `collectProviders`' boot error, which names the provider and the replacement,
* rather than having the option silently ignored.
*/
export: boolean; export: boolean;
} }
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */ /** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
@@ -58,18 +64,16 @@ const K = {
}; };
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ /** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
export function Provider(opts: { export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
provides: string;
needs?: string[];
optional?: boolean;
export?: boolean;
}): ClassDecorator {
return (target) => { return (target) => {
const meta: ProviderMeta = { const meta: ProviderMeta = {
provides: opts.provides, provides: opts.provides,
needs: opts.needs ?? [], needs: opts.needs ?? [],
optional: opts.optional ?? false, optional: opts.optional ?? false,
export: opts.export ?? false, // Read through a cast because the options type deliberately does not offer `export`: only a
// `@Step` or a route is exportable, and the option's only behaviour was to throw at boot.
// A JavaScript caller can still pass it, and recording it is what routes them to that error.
export: (opts as { export?: boolean }).export ?? false,
}; };
Reflect.defineMetadata(K.provider, meta, target); Reflect.defineMetadata(K.provider, meta, target);
}; };
+22 -4
View File
@@ -37,8 +37,18 @@ export interface PluginApi {
*/ */
onShutdown(fn: TeardownFn): void; onShutdown(fn: TeardownFn): void;
} }
/** A plugin: a function that wires itself up through the provided PluginApi. */ /**
export type Plugin = (api: PluginApi) => void; * A plugin: a named object that wires itself up through the provided PluginApi.
*
* The name is a field rather than `fn.name` because `fn.name` cannot be relied on: an arrow
* returned straight from a factory has `""`, `const plugin = …` reports `"plugin"`, and a minifier
* rewrites both. The name is what `plugin:mounted` reports and what a failed mount is blamed on, so
* it has to be the author's word, not the bundler's.
*/
export interface Plugin {
readonly name: string;
mount(api: PluginApi): void;
}
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */ /** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void { export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
@@ -53,6 +63,14 @@ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdow
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still // before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown. // caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown }; const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' }); try {
plugin.mount(api);
} catch (error) {
// Without the name this surfaces as somebody else's stack trace: mounting happens inside
// createApp, so the application sees a throw from a line it never wrote.
throw new Error(`plugin "${plugin.name}" failed to mount: ${(error as Error).message}`, { cause: error });
}
bus.emit('plugin:mounted', { name: plugin.name });
} }
+35 -3
View File
@@ -1,11 +1,36 @@
import type { StandardIssue } from './standard-schema'; import type { StandardIssue } from './standard-schema';
/**
* Brands, so an error is recognised across two copies of core — an app that installed one from npm
* and a plugin that brought another from JSR, or two npm versions npm could not dedupe.
* `instanceof` cannot do that: each copy has its own class identity.
*
* `Symbol.for` is registry-wide, so both copies resolve the same symbol. The *string* is the public
* protocol (`.specs/2026-09-15-plugin-ecosystem-design.md`, 1.2): a plugin that imports only types
* cannot import this constant, so it writes `Symbol.for('green-tea.http-error')` itself.
*
* `unique symbol` is required by TypeScript for a computed class field, and `Symbol.for` on a `const`
* satisfies it.
*/
export const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
export const VALIDATION_ERROR: unique symbol = Symbol.for('green-tea.validation-error');
/** The shape core reads off a branded error. Anything carrying the brand should satisfy it. */
export interface HttpErrorLike {
status: number;
message: string;
body?: unknown;
headers?: Record<string, string>;
}
/** /**
* Error carrying an HTTP status code and optional response body. Base of all signals. * Error carrying an HTTP status code and optional response body. Base of all signals.
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers` * A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
* rather than requiring a special case in the error renderer. * rather than requiring a special case in the error renderer.
*/ */
export class HttpError extends Error { export class HttpError extends Error {
readonly [HTTP_ERROR] = true;
constructor( constructor(
readonly status: number, readonly status: number,
message?: string, message?: string,
@@ -47,6 +72,8 @@ export class Redirect extends HttpError {
/** 422 raised when request input fails Standard Schema validation. */ /** 422 raised when request input fails Standard Schema validation. */
export class ValidationError extends HttpError { export class ValidationError extends HttpError {
readonly [VALIDATION_ERROR] = true;
constructor( constructor(
public issues: StandardIssue[], public issues: StandardIssue[],
public source: string, public source: string,
@@ -68,7 +95,12 @@ export class TransportMismatchError extends HttpError {
} }
} }
/** Type guard: true if `error` is an {@link HttpError}. */ /** Type guard: true if `error` carries the HTTP-error brand — this copy's or another's. */
export function isHttpError(error: unknown): error is HttpError { export function isHttpError(error: unknown): error is HttpErrorLike {
return error instanceof HttpError; return typeof error === 'object' && error !== null && HTTP_ERROR in error;
}
/** Type guard: true if `error` carries the validation brand. */
export function isValidationError(error: unknown): error is ValidationError {
return typeof error === 'object' && error !== null && VALIDATION_ERROR in error;
} }
+2 -2
View File
@@ -1,4 +1,4 @@
import { isHttpError, ValidationError } from './signals'; import { isHttpError, isValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
import type { Logger } from './logger'; import type { Logger } from './logger';
@@ -35,7 +35,7 @@ export const JsonTransformer: TransformerFn = (value) => ({
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`. * An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
*/ */
export function errorToResponse(error: unknown): ErrorResponse { export function errorToResponse(error: unknown): ErrorResponse {
if (error instanceof ValidationError) { if (isValidationError(error)) {
return { return {
status: 422, status: 422,
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
+49 -6
View File
@@ -86,9 +86,40 @@ export interface StaticHit {
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */ /** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>; export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
const real = await fs.promises.realpath(path);
return real === root || real.startsWith(root + sep) ? real : undefined;
}
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
async function readConfined(
fs: typeof import('node:fs'),
nodePath: typeof import('node:path'),
root: string,
full: string,
): Promise<StaticHit | undefined> {
let real = await confine(fs, nodePath.sep, root, full);
if (!real) return undefined;
const isDir = (await fs.promises.stat(real)).isDirectory();
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
if (!real) return undefined;
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
// on every path component, which Node, Deno and Bun do not offer portably.
const body = await fs.promises.readFile(real);
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
const target = isDir ? nodePath.join(full, 'index.html') : full;
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
}
/** /**
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at * Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss. * boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss,
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
*/ */
export function buildStaticResolver(root: string | true): StaticResolver { export function buildStaticResolver(root: string | true): StaticResolver {
let fs: typeof import('node:fs'); let fs: typeof import('node:fs');
@@ -105,6 +136,18 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root); const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
// The root's real path, resolved once on the first request rather than at build time, so a missing
// `public/` at boot is still not fatal — it just makes every request a miss, as before. Containment
// compares real paths, so the root must be real too: a symlinked `public/` would otherwise fail every
// check. Cached for the life of the app: re-pointing a root symlink at runtime needs a restart. A failed
// lookup is not cached, so a root created after boot starts serving, as it did before.
let realRoot: Promise<string | undefined> | undefined;
const resolveRoot = () =>
(realRoot ??= fs.promises.realpath(abs).catch(() => {
realRoot = undefined;
return undefined;
}));
return async (urlPath) => { return async (urlPath) => {
let rel: string; let rel: string;
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
const rootReal = await resolveRoot();
if (!rootReal) return undefined;
try { try {
const stat = await fs.promises.stat(full); return await readConfined(fs, nodePath, rootReal, full);
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
const body = await fs.promises.readFile(target);
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
} catch { } catch {
return undefined; return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
} }
}; };
} }
+59
View File
@@ -0,0 +1,59 @@
// test/app-boot.test.ts
import { describe, expect, it, vi } from 'vitest';
import { createApp, Get, Module, Route, needs } from '../src/index';
import type { Plugin } from '../src/index';
@Route('/')
class Ctl {
@Get('/x')
x(@needs('thing') thing: string) {
return { thing };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const plugin = (run: () => Promise<Record<string, unknown>>): Plugin => ({
name: 'thing',
mount({ scope }) {
scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run });
},
});
describe('app.boot()', () => {
it('surfaces a failing provider instead of leaving it for the first request', async () => {
const app = createApp({ modules: [M], plugins: [plugin(async () => { throw new Error('bad key'); })] });
await expect(app.boot()).rejects.toThrow(/bad key/);
});
it('runs provider factories exactly once, and serves afterwards', async () => {
const run = vi.fn(async () => ({ thing: 'ok' }));
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await app.boot();
await app.boot();
const response = await app.fetch(new Request('http://x/x'));
expect(run).toHaveBeenCalledTimes(1);
expect(await response.json()).toEqual({ thing: 'ok' });
});
// The memo keeps the rejection, which is exactly why a failed boot answers 500 for the life of
// the process instead of retrying. It is the documented behaviour, so it gets a test rather than
// a sentence: if it ever starts retrying, the guide in Task 7 becomes wrong.
it('keeps a failed boot failed', async () => {
const run = vi.fn(async () => {
throw new Error('bad key');
});
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.fetch(new Request('http://x/x'))).rejects.toThrow(/bad key/);
expect(run).toHaveBeenCalledTimes(1);
});
});
+28 -2
View File
@@ -12,7 +12,16 @@ class Rt {
})(); })();
} }
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Route('/room')
class Room {
@Ws('/:name')
join(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt, Room] })
class M {} class M {}
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
@@ -66,9 +75,12 @@ describe('app.upgrade', () => {
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => { it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
const seen: string[] = []; const seen: string[] = [];
const logger = (api: any) => { const logger = {
name: 'ws-step-logger',
mount: (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`)); api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`)); api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
},
}; };
const wsApp = createApp({ modules: [Tagged], plugins: [logger] }); const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
const { socket, inbound, sent } = fakeSocket(); const { socket, inbound, sent } = fakeSocket();
@@ -93,4 +105,18 @@ describe('app.upgrade', () => {
await app.upgrade(req, socket); await app.upgrade(req, socket);
expect(closedCode).toBe(1008); expect(closedCode).toBe(1008);
}); });
it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])(
'closes 1008 on the malformed path %s instead of rejecting (#104)',
async (url) => {
const { socket } = fakeSocket();
let closed: [number | undefined, string | undefined] | undefined;
socket.close = (c, r) => {
closed = [c, r];
};
const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' };
await app.upgrade(req, socket);
expect(closed).toEqual([1008, 'invalid request path']);
},
);
}); });
+14 -5
View File
@@ -56,7 +56,10 @@ test('ready() is a no-op on a non-mesh app, so one protocol works for both', asy
test('a logger plugin observes step:enter without mutating the chain', async () => { test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = []; const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)); const logger = {
name: 'step-logger',
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
};
const app = createApp({ modules: [ApiModule], plugins: [logger] }); const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0); const server = await app.listen(0);
const port = (server.address() as any).port; const port = (server.address() as any).port;
@@ -256,7 +259,9 @@ describe('per-route subgraph slicing', () => {
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => { it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add. // NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = []; const ran: string[] = [];
const observer = (api: any) => const observer = {
name: 'side-effect-observer',
mount: (api: any) =>
api.scope.add({ api.scope.add({
kind: 'step', kind: 'step',
name: 'obs', name: 'obs',
@@ -266,7 +271,8 @@ describe('per-route subgraph slicing', () => {
ran.push('obs'); ran.push('obs');
return {}; return {};
}, },
}); }),
};
@Route('/') @Route('/')
class Ctl { class Ctl {
@Get('/free') free() { @Get('/free') free() {
@@ -285,7 +291,9 @@ describe('per-route subgraph slicing', () => {
it('an always-run observer step receives its declared needs even when the route does not need them', async () => { it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any; let seen: any;
const observer = (api: any) => const observer = {
name: 'audit-observer',
mount: (api: any) =>
api.scope.add({ api.scope.add({
kind: 'step', kind: 'step',
name: 'audit', name: 'audit',
@@ -295,7 +303,8 @@ describe('per-route subgraph slicing', () => {
seen = ctx.user; seen = ctx.user;
return {}; return {};
}, },
}); }),
};
@Step({ provides: 'user', needs: [] }) @Step({ provides: 'user', needs: [] })
class Auth { class Auth {
run() { run() {
+87
View File
@@ -0,0 +1,87 @@
// #105 on the real Bun runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveBun`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(source.pulled).toBe(0);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
expect(res.status).toBe(413);
expect(source.pulled).toBeLessThanOrEqual(5);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
expect(at.status).toBe(200);
expect(await at.json()).toEqual({ length: LIMIT });
expect(over.status).toBe(413);
await app.close();
});
test('T11 serveBun: the same statuses over a real socket', async () => {
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
const base = `http://127.0.0.1:${server.port}`;
// A fresh connection per request. Bun's *client* reuses a kept-alive socket after a response that
// arrived before the server read the request body, and its next request on that socket comes back
// 400 or 431. Node's fetch against the same Bun server does not (Bun 1.3.14), so it is the client
// that misbehaves, not `serveBun`.
const send = (body: BodyInit, headers?: Record<string, string>) =>
fetch(post(`${base}/small`, body, headers), { keepalive: false } as RequestInit);
try {
expect((await send(new Uint8Array(2 * SMALL))).status).toBe(413);
expect((await send(countingStream(10, 300).stream)).status).toBe(413);
expect((await send('x'.repeat(SMALL), { 'content-type': 'text/plain' })).status).toBe(200);
expect((await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' })).status).toBe(413);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+8 -8
View File
@@ -8,14 +8,14 @@
// Run with: npm run test:bun // Run with: npm run test:bun
import 'reflect-metadata'; import 'reflect-metadata';
import { test, expect } from 'bun:test'; import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts'; import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { runtime: 'bun' } }; return { config: { runtime: 'bun' } };
} }
} }
@@ -25,7 +25,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
@@ -48,9 +48,9 @@ function freePort(): number {
} }
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */ /** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
function startTeapot(port: number) { async function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveBun(app, { port }); const server = await serveBun(app, { port });
return { return {
stop: async () => { stop: async () => {
@@ -64,7 +64,7 @@ const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => { test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
const port = freePort(); const port = freePort();
let teapot = startTeapot(port); let teapot = await startTeapot(port);
const teacup = createApp({ const teacup = createApp({
modules: [TeacupModule], modules: [TeacupModule],
@@ -88,7 +88,7 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
const down = await teacup.fetch(new Request('http://x/api/local/who')); const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503); expect(down.status).toBe(503);
teapot = startTeapot(port); teapot = await startTeapot(port);
await settle(400); await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } })); const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
+8 -8
View File
@@ -1,4 +1,4 @@
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming // Real Bun integration test for mesh: a teapot exporting its steps and a teacup consuming
// them, both under the actual Bun runtime, driven entirely through serveBun. // them, both under the actual Bun runtime, driven entirely through serveBun.
// //
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler // Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
@@ -8,14 +8,14 @@
// Run with: npm run test:bun // Run with: npm run test:bun
import 'reflect-metadata'; import 'reflect-metadata';
import { test, expect } from 'bun:test'; import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts'; import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { region: 'mx', runtime: 'bun' } }; return { config: { region: 'mx', runtime: 'bun' } };
} }
} }
@@ -25,7 +25,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
@@ -42,14 +42,14 @@ const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => { test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 }); const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({ const teacup = createApp({
modules: [TeacupModule], modules: [TeacupModule],
experimental: true, experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] }, mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
}); });
const cServer = serveBun(teacup, { port: 0 }); const cServer = await serveBun(teacup, { port: 0 });
try { try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } }); const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
@@ -67,7 +67,7 @@ test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () =>
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => { test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 }); const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({ const teacup = createApp({
modules: [TeacupModule], modules: [TeacupModule],
+63
View File
@@ -0,0 +1,63 @@
// #116 on the real Bun runtime: `serveBun` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createServer } from 'node:net';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveBun(createApp({ modules: [M], trustProxy: opts.trustProxy }), { hostname, port: 0 });
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${server.port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
const ipv6Available = await new Promise<boolean>((resolve) => {
const probe = createServer();
probe.once('error', () => resolve(false));
probe.listen(0, '::1', () => probe.close(() => resolve(true)));
});
test('T2 serveBun: ctx.ip is the socket peer address', async () => {
expect(await ipVia('127.0.0.1')).toBe('127.0.0.1');
});
// Skipped, not failed: the host has no IPv6 loopback to connect over.
test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun reports it', async () => {
expect(await ipVia('::1')).toBe('::1');
});
test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
expect(ip).toBe('203.0.113.7');
});
test('T5 serveBun: trustProxy without x-forwarded-for falls back to the peer', async () => {
expect(await ipVia('127.0.0.1', { trustProxy: true })).toBe('127.0.0.1');
});
test('T6 serveBun: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
expect(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } })).toBe('127.0.0.1');
});
+22
View File
@@ -0,0 +1,22 @@
// The frozen router-parity differential under the real Bun runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = (name: string) => Bun.file(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)).json();
test('router parity on Bun: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
expect(report.mismatches).toEqual([]);
expect(report.sets.length).toBe(5);
});
test('router parity on Bun: app.fetch cases', async () => {
const report = await runAppDifferential(load);
expect(report.mismatches).toEqual([]);
});
+34 -6
View File
@@ -6,7 +6,7 @@
// Run with: npm run test:bun (or: bun test test/bun/) // Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata'; import 'reflect-metadata';
import { test, expect } from 'bun:test'; import { test, expect } from 'bun:test';
import { createApp, Route, Get, Module } from '../../src/index.ts'; import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts'; import { serveBun } from '../../src/bun.ts';
@Route('/') @Route('/')
@@ -25,7 +25,7 @@ class Ctl {
class M {} class M {}
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => { test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 }); const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {}); fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
await Bun.sleep(50); // let the request actually reach the handler await Bun.sleep(50); // let the request actually reach the handler
@@ -40,7 +40,7 @@ test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', a
}); });
test('serveBun close() drains an in-flight request rather than cutting it', async () => { test('serveBun close() drains an in-flight request rather than cutting it', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 }); const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json()); const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
@@ -57,15 +57,43 @@ test('serveBun close() runs registered teardown', async () => {
const app = createApp({ const app = createApp({
modules: [M], modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }], hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => { plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await Bun.sleep(10); await Bun.sleep(10);
closed.push('plugin'); closed.push('plugin');
})], }),
}],
}); });
const server = serveBun(app, { port: 0 }); const server = await serveBun(app, { port: 0 });
await server.close({ timeoutMs: 2000 }); await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first. // Reverse registration order: the plugin registered after the hook, so it tears down first.
expect(closed).toEqual(['plugin', 'hook']); expect(closed).toEqual(['plugin', 'hook']);
}); });
// The boot gate, which is why serveBun is async. Before it, a provider that threw was memoized as a
// rejection and answered 500 to every request from the runtime, never reaching onError — so the
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
@Provider({ provides: 'key' })
class BadKey {
provide(): never {
throw new Error('no such key file');
}
}
@Route('/')
class NeedsKey {
@Get('/signed')
signed(@needs('key') key: string) {
return { key };
}
}
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
class KeyModule {}
test('serveBun rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
});
+51
View File
@@ -0,0 +1,51 @@
// Static-file confinement (#106) under the real Bun runtime, which reaches `realpath` through its
// `node:fs` compat — a third implementation of symlink resolution, so not something to assume from
// the Node suite.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createApp } from '../../src/index.ts';
const base = mkdtempSync(join(tmpdir(), 'gt-static-bun-'));
const root = join(base, 'root');
mkdirSync(join(root, 'sub'), { recursive: true });
writeFileSync(join(root, 'a.txt'), 'in root');
writeFileSync(join(root, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
symlinkSync('a.txt', join(root, 'in-link'));
symlinkSync('../secret.txt', join(root, 'out-link'));
symlinkSync('../nope.txt', join(root, 'dangling'));
symlinkSync('root', join(base, 'root-alias'));
const app = createApp({ modules: [], static: root });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
test('static on Bun: a link to a file outside the root is a miss', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
test('static on Bun: a link to a file inside the root is served', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
test('static on Bun: a dangling link is a 404, not a rejection', async () => {
expect((await get('/dangling')).status).toBe(404);
});
test('static on Bun: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
+91 -1
View File
@@ -20,13 +20,29 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
class M {} class M {}
test('serveBun: HTTP + WebSocket round-trip', async () => { test('serveBun: HTTP + WebSocket round-trip', async () => {
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
const server = serveBun(app, { port: 0 }); const server = await serveBun(app, { port: 0 });
const port = server.port; const port = server.port;
try { try {
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
@@ -47,3 +63,77 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
server.stop(true); server.stop(true);
} }
}); });
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
expect(closed).toEqual({ code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
expect(httpRes.status).toBe(200);
} finally {
server.stop(true);
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Its
// uWebSockets core drops the TCP connection without a close frame, so the peer sees `1006`, not
// the `1009` Node, Deno and the edge send. Asserted rather than papered over: it is the documented
// Bun difference, and a Bun upgrade that starts sending 1009 should fail here and be noticed.
test('serveBun: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
expect(over.close?.code).toBe(1006);
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
} finally {
server.stop(true);
}
});
test('serveBun: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
expect(atLimit.replies.length).toBe(1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
expect(over.close?.code).toBe(1006);
} finally {
server.stop(true);
}
});
+4 -1
View File
@@ -22,8 +22,11 @@ describe('reaching the bus', () => {
const fromOutside: string[] = []; const fromOutside: string[] = [];
const fromPlugin: string[] = []; const fromPlugin: string[] = [];
const observer: Plugin = (api) => { const observer: Plugin = {
name: 'bus-observer',
mount(api) {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? '')); api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
+4 -1
View File
@@ -32,7 +32,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
// `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity // `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
// it returns is exactly what `createApp` returns when `handleSignals` is left off. // it returns is exactly what `createApp` returns when `handleSignals` is left off.
const handleSignals = <T,>(closer: T): T => closer; const handleSignals = <T,>(closer: T): T => closer;
serveDeno({ upgrade, handleSignals } as unknown as App); // `serveDeno` boots before it binds, so the stub needs the gate even though this test never
// exercises it.
const boot = vi.fn().mockResolvedValue(undefined);
await serveDeno({ upgrade, handleSignals, boot } as unknown as App);
const info = { const info = {
get remoteAddr() { get remoteAddr() {
if (upgraded) throw new TypeError('Request closed'); if (upgraded) throw new TypeError('Request closed');
+95
View File
@@ -0,0 +1,95 @@
// #105 on the real Deno runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveDeno`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
Deno.test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
assertEquals(res.status, 413);
assertEquals(source.pulled, 0);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
assertEquals(res.status, 413);
if (source.pulled > 5) throw new Error(`pulled ${source.pulled} chunks — the read did not stop at the limit`);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
assertEquals(at.status, 200);
assertEquals(await at.json(), { length: LIMIT });
assertEquals(over.status, 413);
await over.body?.cancel();
await app.close();
});
Deno.test('T11 serveDeno: the same statuses over a real socket', async () => {
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
try {
const send = (body: BodyInit, headers?: Record<string, string>) => fetch(post(`${base}/small`, body, headers));
const declared = await send(new Uint8Array(2 * SMALL));
assertEquals(declared.status, 413);
await declared.body?.cancel();
const streamed = await send(countingStream(10, 300).stream);
assertEquals(streamed.status, 413);
await streamed.body?.cancel();
const at = await send('x'.repeat(SMALL), { 'content-type': 'text/plain' });
assertEquals(at.status, 200);
await at.body?.cancel();
const over = await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' });
assertEquals(over.status, 413);
await over.body?.cancel();
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+1 -1
View File
@@ -22,7 +22,7 @@ class TeapotModule {}
async function startTeapot() { async function startTeapot() {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
let port = 0; let port = 0;
const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) }); const server = await serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
await new Promise((r) => setTimeout(r, 50)); await new Promise((r) => setTimeout(r, 50));
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } }; return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
+7 -7
View File
@@ -10,14 +10,14 @@
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer) // Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
import 'npm:reflect-metadata'; import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
const NODE_PEER = 'test/interop/_node-peer.ts'; const NODE_PEER = 'test/interop/_node-peer.ts';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { region: 'mx', runtime: 'deno' } }; return { config: { region: 'mx', runtime: 'deno' } };
} }
} }
@@ -27,7 +27,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
@@ -112,7 +112,7 @@ Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
try { try {
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(res.status, 200); assertEquals(res.status, 200);
// the config came from the Node process: proof the scope crossed the runtime boundary // the config came from the Node process: proof the remote step crossed the runtime boundary
assertEquals(await res.json(), { assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'node' }, config: { region: 'mx', runtime: 'node' },
auth: { token: 'abc' }, auth: { token: 'abc' },
@@ -127,7 +127,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
let port = 0; let port = 0;
const { serveDeno } = await import('../../src/deno.ts'); const { serveDeno } = await import('../../src/deno.ts');
const server = serveDeno(teapot, { const server = await serveDeno(teapot, {
port: 0, port: 0,
onListen: (addr) => { onListen: (addr) => {
port = addr.port; port = addr.port;
@@ -140,7 +140,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
try { try {
const result = await firstJsonLine(node); const result = await firstJsonLine(node);
assertEquals(result.ok, true); assertEquals(result.ok, true);
// the Node peer resolved a scope served by Deno's app.upgrade control channel // the Node peer ran a step served by Deno's app.upgrade control channel
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' }); assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
assertEquals(result.body.auth, { token: 'abc' }); assertEquals(result.body.auth, { token: 'abc' });
} finally { } finally {
+5 -5
View File
@@ -7,14 +7,14 @@
// Run with: npm run test:deno // Run with: npm run test:deno
import 'npm:reflect-metadata'; import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert'; import { assertEquals } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts'; import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { runtime: 'deno' } }; return { config: { runtime: 'deno' } };
} }
} }
@@ -24,7 +24,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
@@ -49,7 +49,7 @@ function freePort(): number {
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */ /** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
async function startTeapot(port: number) { async function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveDeno(app, { port }); const server = await serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50)); await new Promise((r) => setTimeout(r, 50));
return { return {
+6 -6
View File
@@ -1,4 +1,4 @@
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming // Real Deno integration test for mesh: a teapot exporting its steps and a teacup consuming
// them, both under the actual Deno runtime, driven entirely through serveDeno. // them, both under the actual Deno runtime, driven entirely through serveDeno.
// //
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers, // This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
@@ -13,14 +13,14 @@
// including Node-only modules this test never executes. tsc covers those. // including Node-only modules this test never executes. tsc covers those.
import 'npm:reflect-metadata'; import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts'; import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { region: 'mx', runtime: 'deno' } }; return { config: { region: 'mx', runtime: 'deno' } };
} }
} }
@@ -30,7 +30,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
@@ -46,7 +46,7 @@ class TeacupModule {}
/** Starts an app on Deno and resolves once its port is known. */ /** Starts an app on Deno and resolves once its port is known. */
async function serve(app: ReturnType<typeof createApp>) { async function serve(app: ReturnType<typeof createApp>) {
let port = 0; let port = 0;
const server = serveDeno(app, { const server = await serveDeno(app, {
port: 0, port: 0,
onListen: (addr) => { onListen: (addr) => {
port = addr.port; port = addr.port;
+73
View File
@@ -0,0 +1,73 @@
// #116 on the real Deno runtime: `serveDeno` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveDeno(createApp({ modules: [M], trustProxy: opts.trustProxy }), {
hostname,
port: 0,
onListen: () => {},
});
const port = (server as unknown as { addr: { port: number } }).addr.port;
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
function ipv6Available(): boolean {
try {
Deno.listen({ hostname: '::1', port: 0 }).close();
return true;
} catch {
return false;
}
}
Deno.test('T1 serveDeno: ctx.ip is the socket peer address', async () => {
assertEquals(await ipVia('127.0.0.1'), '127.0.0.1');
});
Deno.test({
name: 'T3 serveDeno: an IPv6 peer is passed through as Deno reports it',
ignore: !ipv6Available(), // skipped, not failed: the host has no IPv6 loopback to connect over
fn: async () => {
assertEquals(await ipVia('::1'), '::1');
},
});
Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
assertEquals(ip, '203.0.113.7');
});
Deno.test('T5 serveDeno: trustProxy without x-forwarded-for falls back to the peer', async () => {
assertEquals(await ipVia('127.0.0.1', { trustProxy: true }), '127.0.0.1');
});
Deno.test('T6 serveDeno: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
assertEquals(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } }), '127.0.0.1');
});
+23
View File
@@ -0,0 +1,23 @@
// The frozen router-parity differential under the real Deno runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = async (name: string) =>
JSON.parse(await Deno.readTextFile(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)));
Deno.test('router parity on Deno: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
assertEquals(report.mismatches, []);
assertEquals(report.sets.length, 5);
});
Deno.test('router parity on Deno: app.fetch cases', async () => {
const report = await runAppDifferential(load);
assertEquals(report.mismatches, []);
});
+44 -7
View File
@@ -5,7 +5,7 @@
// //
// Run with: npm run test:deno // Run with: npm run test:deno
import 'reflect-metadata'; import 'reflect-metadata';
import { createApp, Route, Get, Module } from '../../src/index.ts'; import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts'; import { serveDeno } from '../../src/deno.ts';
@Route('/') @Route('/')
@@ -30,7 +30,7 @@ const portOf = (server: { addr?: { port: number } }): number => server.addr!.por
// the uncaught BadResource that aborting a draining server produces. The test runner fails on // the uncaught BadResource that aborting a draining server produces. The test runner fails on
// that error even when the assertions pass, so a green run here is the real assertion. // that error even when the assertions pass, so a green run here is the real assertion.
Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => { Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => {
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {}); fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
@@ -45,7 +45,7 @@ Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without for
}); });
Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => { Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => {
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} }); const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json()); const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json());
await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close
@@ -58,7 +58,7 @@ Deno.test('serveDeno close() drains an in-flight request rather than cutting it'
Deno.test('a caller-supplied signal still aborts the server', async () => { Deno.test('a caller-supplied signal still aborts the server', async () => {
const ac = new AbortController(); const ac = new AbortController();
const server = serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} }); const server = await serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} });
ac.abort(); ac.abort();
await server.finished; // hangs here if chaining the caller's signal into ours dropped it await server.finished; // hangs here if chaining the caller's signal into ours dropped it
@@ -72,15 +72,52 @@ Deno.test('serveDeno close() runs registered teardown', async () => {
const app = createApp({ const app = createApp({
modules: [M], modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }], hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => { plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 10));
closed.push('plugin'); closed.push('plugin');
})], }),
}],
}); });
const server = serveDeno(app, { port: 0 }); const server = await serveDeno(app, { port: 0 });
await server.close({ timeoutMs: 2000 }); await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first. // Reverse registration order: the plugin registered after the hook, so it tears down first.
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`); if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
}); });
// The boot gate, which is why serveDeno is async. Before it, a provider that threw was memoized as
// a rejection and answered 500 to every request from the runtime, never reaching onError — so the
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
@Provider({ provides: 'key' })
class BadKey {
provide(): never {
throw new Error('no such key file');
}
}
@Route('/')
class NeedsKey {
@Get('/signed')
signed(@needs('key') key: string) {
return { key };
}
}
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
class KeyModule {}
Deno.test('serveDeno rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
let message = '';
try {
await serveDeno(app, { port: 0, onListen: () => {} });
} catch (error) {
message = (error as Error).message;
}
if (!message.includes('no such key file')) {
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
}
});
+37
View File
@@ -74,3 +74,40 @@ Deno.test('multipart resolves the busboy peer dependency instead of reporting it
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' }); assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close(); await app.close();
}); });
// #106 on Deno, which reaches `realpath` through its `node:fs` compat. Committed symlinks rather than
// a temp tree, for the same `--allow-write` reason as above; `secret.txt` sits beside the root.
const linked = 'test/fixtures/static';
Deno.test('static: a link to a file outside the root is a miss', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/out-link'));
assertEquals(res.status, 404);
assertEquals((await res.text()).includes('TOP SECRET'), false);
await app.close();
});
Deno.test('static: a link to a file inside the root is served', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/in-link'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'in root');
await app.close();
});
Deno.test('static: a dangling link is a 404, not a rejection', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
assertEquals((await app.fetch(new Request('http://x/dangling'))).status, 404);
await app.close();
});
Deno.test('static: a root that is itself a symlink still serves its files', async () => {
const app = createApp({ modules: [], static: `${linked}/root-alias` });
const a = await app.fetch(new Request('http://x/a.txt'));
assertEquals(a.status, 200);
assertEquals(await a.text(), 'in root');
const sub = await app.fetch(new Request('http://x/sub/'));
assertEquals(sub.status, 200);
assertEquals(await sub.text(), '<h1>Sub</h1>');
await app.close();
});
+113 -1
View File
@@ -28,6 +28,22 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
@@ -37,7 +53,7 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
let port = 0; let port = 0;
const server = serveDeno(app, { const server = await serveDeno(app, {
port: 0, port: 0,
onListen: (addr) => { onListen: (addr) => {
port = addr.port; port = addr.port;
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
await server.shutdown(); await server.shutdown();
} }
}); });
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
assertEquals(closed, { code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
assertEquals(httpRes.status, 200);
await httpRes.body?.cancel();
} finally {
await server.shutdown();
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: on Deno the runtime receives the whole message before user code sees it, so the size
// bound is checked after receipt — the close code is the same as on Node and Bun.
Deno.test('serveDeno: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
assertEquals(atLimit.replies, [`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
assertEquals(over.close, { code: 1009, reason: 'message too large' });
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
assertEquals(full.close, { code: 1013, reason: 'inbound queue full' });
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
assertEquals(atLimit.replies.length, 1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
assertEquals(over.close?.code, 1009);
} finally {
await server.shutdown();
}
});
+32
View File
@@ -0,0 +1,32 @@
// Worker entry that runs the frozen router-parity differential inside workerd: every matcher case
// through the oracle and the live router, and the app.fetch cases, against the same frozen files the
// Node suite uses. The frozen JSON is bundled in, since a worker has no file system. Driven by
// test/edge/run.ts; see test/router-parity/README.md.
import { runDifferential } from '../router-parity/differential';
import { runAppDifferential } from '../router-parity/app-fixture';
import matcherHand from '../router-parity/frozen/matcher-hand.json';
import matcherOwner from '../router-parity/frozen/matcher-owner.json';
import matcherGenerated from '../router-parity/frozen/matcher-generated.json';
import matcherGeneratedV2 from '../router-parity/frozen/matcher-generated-v2.json';
import matcherWs from '../router-parity/frozen/matcher-ws.json';
import appFetch from '../router-parity/frozen/app-fetch.json';
import ownerAppAllow from '../router-parity/frozen/owner-app-allow.json';
const FROZEN: Record<string, unknown> = {
'matcher-hand': matcherHand,
'matcher-owner': matcherOwner,
'matcher-generated': matcherGenerated,
'matcher-generated-v2': matcherGeneratedV2,
'matcher-ws': matcherWs,
'app-fetch': appFetch,
'owner-app-allow': ownerAppAllow,
};
export default {
fetch: async (): Promise<Response> => {
const load = (name: string) => FROZEN[name];
const matcher = await runDifferential(load);
const app = await runAppDifferential(load);
return Response.json({ matcher, app });
},
};
+132 -3
View File
@@ -66,6 +66,33 @@ async function main() {
assert.equal(httpRes.status, 200); assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true }); assert.deepEqual(await httpRes.json(), { ok: true });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
const res = await mf.dispatchFetch('http://localhost/rt/body', {
method: 'POST',
headers: { 'content-type': 'text/plain' },
body,
duplex: 'half',
} as Parameters<typeof mf.dispatchFetch>[1]);
await res.arrayBuffer();
return res.status;
};
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
let sent = 0;
return new ReadableStream({
pull(controller) {
if (sent++ === count) controller.close();
else controller.enqueue(new Uint8Array(size).fill(0x61));
},
});
};
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
// WebSocket // WebSocket
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', { const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' }, headers: { Upgrade: 'websocket' },
@@ -84,13 +111,115 @@ async function main() {
}); });
assert.equal(got, 'echo:hi'); assert.equal(got, 'echo:hi');
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS'); // #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
headers: { Upgrade: 'websocket' },
});
const bad = badRes.webSocket;
assert.ok(bad, 'expected a client webSocket on the 101 response');
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
bad.addEventListener('close', (e: { code: number; reason: string }) =>
resolve({ code: e.code, reason: e.reason }),
),
);
bad.accept();
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
// #107: workerd delivers the whole message before user code sees it, so the size bound is
// checked after receipt; the close codes match Node and Deno.
const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames);
assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]);
assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' });
assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, {
code: 1013,
reason: 'inbound queue full',
});
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
} finally { } finally {
await mf.dispose(); await mf.dispose();
} }
} }
main().catch((err) => { const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs';
/**
* The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling
* as the main worker; the worker runs every case itself and answers with its mismatch report.
*/
async function parity() {
await build({
entryPoints: ['test/edge/parity-worker.ts'],
bundle: true,
format: 'esm',
outfile: PARITY_BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: PARITY_BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
const res = await mf.dispatchFetch('http://localhost/');
const report = (await res.json()) as {
matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] };
app: { requests: number; mismatches: string[] };
};
assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd');
assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd');
const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0);
console.log(
`edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`,
);
} finally {
await mf.dispose();
}
}
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
const ws = res.webSocket;
assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`);
const replies: string[] = [];
const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, ms);
ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data)));
ws.addEventListener('close', (e: { code: number; reason: string }) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
});
});
ws.accept();
for (const frame of frames) ws.send(frame);
return result;
}
main()
.then(parity)
.catch((err) => {
console.error(err); console.error(err);
process.exit(1); process.exit(1);
}); });
+32 -2
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test. // Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven // Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts). // identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index'; import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
import { edgeHandler } from '../../src/edge'; import { edgeHandler } from '../../src/edge';
@Route('/rt') @Route('/rt')
@@ -11,17 +11,47 @@ class Rt {
return { ok: true }; return { ok: true };
} }
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer.
@Post('/body', { maxBodyBytes: 1000 })
body(@body() b: unknown) {
return { length: String(b).length };
}
@Ws('/echo') @Ws('/echo')
echo(@ctx() { inbound }: any) { echo(@ctx() { inbound }: any) {
return (async function* () { return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
class M {} class M {}
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
export default { fetch: edgeHandler(app) }; export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
};
+155 -1
View File
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
import { countingStream } from './helpers/counting-stream';
import { setPeer } from '../src/http/peer';
@Provider({ provides: 'store' }) @Provider({ provides: 'store' })
class Store { class Store {
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
); );
expect(await res.json()).toEqual({ ip: '' }); expect(await res.json()).toEqual({ ip: '' });
}); });
// #116: the Deno and Bun adapters now hand `buildFetch` the socket peer. A bare `app.fetch` from
// user code has none to hand, so it must keep answering exactly what it did before.
it('T7: bare app.fetch without peer metadata is unchanged', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
expect(await (await untrusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(await (await trusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(
await (
await trusting.fetch(new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9' } }))
).json(),
).toEqual({ ip: '9.9.9.9' });
});
it('the peer an adapter recorded reaches ctx.ip, and trustProxy without XFF falls back to it', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
const spoofed = new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '1.2.3.4' } });
const plain = new Request('http://x/ip/whoami');
setPeer(spoofed, '127.0.0.1');
setPeer(plain, '::1');
expect(await (await untrusting.fetch(spoofed)).json()).toEqual({ ip: '127.0.0.1' });
expect(await (await trusting.fetch(plain)).json()).toEqual({ ip: '::1' });
});
// The published CommonJS build bundles `index`, `deno` and `bun` as separate files, each with its
// own copy of every module they share, so `serveBun` from `@green-tea/core/bun` and `app.fetch`
// from `@green-tea/core` do not run the same `peer.ts`. A store private to the module would be two
// stores, and the peer recorded by one would never be found by the other.
it('a second copy of the peer module sees the peer the first one recorded', async () => {
const request = new Request('http://x/');
setPeer(request, '192.0.2.1'); // through the copy this file imported
vi.resetModules();
const copy = await import('../src/http/peer');
expect(copy.setPeer).not.toBe(setPeer); // really a second instance of the module
expect(copy.peerOf(request)).toBe('192.0.2.1');
});
it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => {
const original = new Request('http://x/ip/whoami');
setPeer(original, '127.0.0.1');
const res = await createApp({ modules: [IpModule] }).fetch(new Request(original));
expect(await res.json()).toEqual({ ip: '' });
});
}); });
describe('app.fetch on a mesh app', () => { describe('app.fetch on a mesh app', () => {
@@ -145,3 +198,104 @@ describe('app.fetch on a mesh app', () => {
} }
}); });
}); });
// #105: the limit is enforced while the body is read, not after it has been buffered. A status code
// cannot tell the two apart — both answer 413 — so the counting stream is what these assert on.
@Route('/limits')
class LimitsCtl {
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
@Post('/small', { maxBodyBytes: 10 }) small(@body() b: any) {
return { got: b };
}
@Post('/large', { maxBodyBytes: 2_000_000 }) large(@body() b: any) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [LimitsCtl] })
class LimitsModule {}
const post = (path: string, body: RequestInit['body'], headers: Record<string, string> = {}) =>
new Request(`http://x${path}`, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
describe('app.fetch bounded body reads (#105)', () => {
const limitsApp = createApp({ modules: [LimitsModule] }); // server limit: the 1 MB default
it('T1: a declared content-length over the limit is refused without reading the body', async () => {
const body = countingStream(10, 300_000);
const res = await limitsApp.fetch(post('/limits/echo', body.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(body.pulled).toBe(0);
expect(body.cancelled).toBe(true);
});
it('T3: a streamed body stops at the chunk that crosses the limit, and the reader is cancelled', async () => {
const body = countingStream(10, 300_000); // 3 MB, no content-length
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
// 4 read, the 4th crossing 1 MB, plus at most one the stream queued ahead of the reader.
expect(body.pulled).toBeLessThanOrEqual(5);
expect(body.cancelled).toBe(true);
});
it('T4: a body of exactly the limit is accepted', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 8) });
expect(Buffer.byteLength(json)).toBe(1_000_000);
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(200);
expect(((await res.json()) as any).got.s).toHaveLength(1_000_000 - 8);
});
it('T5: one byte over the limit is refused', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 7) });
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(413);
});
it('T5: one byte over the limit is refused when streamed without a content-length', async () => {
const body = countingStream(1, 1_000_001);
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
});
it('T8: a route limit below the server limit wins', async () => {
const res = await limitsApp.fetch(post('/limits/small', 'x'.repeat(11), { 'content-type': 'text/plain' }));
expect(res.status).toBe(413);
});
it('T9: a route limit above the server limit wins', async () => {
const res = await limitsApp.fetch(
post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }),
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 1_500_000 });
});
it('a malformed content-length is ignored, and the stream count enforces the limit', async () => {
const body = countingStream(1, 20);
const res = await limitsApp.fetch(post('/limits/small', body.stream, { 'content-length': 'nope' }));
expect(res.status).toBe(413);
});
it('T10: a bodiless request is answered without reading anything', async () => {
const res = await limitsApp.fetch(new Request('http://x/limits/echo', { method: 'POST' }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({});
});
});
+1
View File
@@ -0,0 +1 @@
root
+1
View File
@@ -0,0 +1 @@
in root
+1
View File
@@ -0,0 +1 @@
../nope.txt
+1
View File
@@ -0,0 +1 @@
a.txt
+1
View File
@@ -0,0 +1 @@
../secret.txt
+1
View File
@@ -0,0 +1 @@
<h1>Sub</h1>
+1
View File
@@ -0,0 +1 @@
TOP SECRET
+44
View File
@@ -0,0 +1,44 @@
// A request body that records how much of it was consumed. Web APIs only, so the Node, Deno and Bun
// suites share it: the regression it guards (#105) is "read the whole body before checking the
// limit", which no status code can show on its own — a 413 looks the same either way.
export interface CountingStream {
stream: ReadableStream<Uint8Array>;
/** Chunks the consumer has pulled so far. */
readonly pulled: number;
/** Whether the consumer cancelled the stream. */
readonly cancelled: boolean;
}
/** `count` chunks of `size` bytes each, handed out one per pull. */
export function countingStream(count: number, size: number): CountingStream {
let pulled = 0;
let cancelled = false;
const stream = new ReadableStream<Uint8Array>({
// Pull-based, and only on demand: with a high-water mark of 0 the stream does not pre-fill its
// queue, so `pulled` counts what the consumer asked for. The default of 1 pulls a chunk at
// construction, before anyone reads, and would make "nothing was read" unprovable.
pull(controller) {
if (pulled === count) {
controller.close();
return;
}
pulled++;
controller.enqueue(new Uint8Array(size).fill(0x61));
},
cancel() {
cancelled = true;
},
}, { highWaterMark: 0 });
return {
stream,
get pulled() {
return pulled;
},
get cancelled() {
return cancelled;
},
};
}
+26
View File
@@ -123,6 +123,32 @@ describe('request hardening', () => {
server.close(); server.close();
}); });
// #105: a declared length over the limit is answered before any of the body is sent. Without the
// header check, the reader waits for a first chunk that this client never sends — and times out.
it('T2: rejects a declared content-length over the limit before reading any body', async () => {
let ran = false;
const server = createHttpServer(
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
);
await new Promise<void>((r) => server.listen(0, r));
const socket = net.connect((server.address() as any).port, '127.0.0.1');
await once(socket, 'connect');
socket.write('POST /echo HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\n\r\n'); // headers only
let raw = '';
socket.setEncoding('utf8');
socket.on('data', (chunk: string) => (raw += chunk));
await once(socket, 'end');
expect(raw).toMatch(/^HTTP\/1\.1 413 /);
expect(raw.toLowerCase()).toContain('connection: close');
expect(ran).toBe(false);
socket.destroy();
server.close();
}, 2000);
it('sets the configured server timeouts and connection limit', async () => { it('sets the configured server timeouts and connection limit', async () => {
const server = createHttpServer([], [], undefined, undefined, const server = createHttpServer([], [], undefined, undefined,
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } }); { limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
+4 -4
View File
@@ -10,13 +10,13 @@
// teapot -> exports scopes, prints {"port":N}, serves until killed // teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}} // teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}}
import 'reflect-metadata'; import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = process.env.MESH_SECRET ?? 's3cr3t'; const SECRET = process.env.MESH_SECRET ?? 's3cr3t';
@Provider({ provides: 'config', export: true }) @Step({ provides: 'config', needs: [], export: true })
class Config { class Config {
provide() { run() {
return { config: { region: 'mx', runtime: 'node' } }; return { config: { region: 'mx', runtime: 'node' } };
} }
} }
@@ -26,7 +26,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
} }
} }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) @Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {} class TeapotModule {}
@Route('/local') @Route('/local')
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more