The frozen CARD-08 goldens already hold graph(), explain(), openapi() and
the mesh teacup. This adds what they do not cover, with expectations
captured from the pre-radix code at ed47836 in a detached checkout:
- explain()/inspect() on a pattern shared by several methods with a
non-GET declared first, and a concrete path that is not a declaration;
- /__graph__ and /__openapi__ on app.fetch, a Node listener and a mesh
teacup, and their agreement with the direct API;
- a structural check that graph/explain/inspect/openapi never call the
router lookup, return the same output before and after the index is
built, and keep declaration order where the index ranks differently.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The walk stack is shared across lookups. A malformed % escape threw out
of decodeSegment with frames still pushed, so repeated direct matcher
calls on such paths retained them. Truncate both arrays back to the
entry length in a finally block, and check it with a test.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Same four mutants (no-backtrack, catch-all-needs-segment,
prune-bound-off-by-one, zero-catch-all-after-static-dead-end), patched
at their new sites in the stack-based walk. 21/21 still killed.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The lookup walk recursed once per path segment, so a valid deep route
such as 4,999 static segments followed by /:x threw RangeError where the
linear matcher matched. Walk on an explicit stack instead, visiting
frames in the same order, and cover the case through buildFetch.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The owner approved editing this one file under test/router-parity/ so
the PR ends with a single mutant check. The original search texts
targeted lines of the linear scan that CARD-07 removed, so the script
refused to run against the new router. The parity tests, oracle,
frozen JSON and manifest are untouched.
The twelve original mutants keep their names and the bug each models;
six apply their original edit, six are rewritten against the index.
Nine new mutants cover risks the index introduced: the static-route
map ignoring the method or shadowing an earlier route, an off-by-one
pruning bound, the empty-collection skip pruning a real match, a
local/remote tie going remote, Allow and implicit HEAD from the local
tree only, the stale-index guard removed, and a zero-segment
catch-all skipped where the path ends on a static continuation.
The suite now also runs test/router-index.test.ts, which covers the
local/remote split and index lifetime the corpus cannot reach. Each
edit must match exactly once and must change the file; a failed edit
restores the copy before the run aborts. The script still ends with
git diff --exit-code src.
Removes test/router-index-mutants.ts and parity:mutants:index, which
this replaces.
Refs #109
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The walk takes the static branch first, so for `GET /a/:rest*` and
`GET /:x/b` it reaches the catch-all on `/a/b` before the exact param
route that outranks it. The corpus has no such pair, and a pruning
bound off by one went unnoticed there. Checked against the oracle in
both declaration orders.
Refs #109
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
'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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`BENCHMARKS.md` answered "how does this compare to fastify" and nothing answered "did the
last two months cost anything". Those are different questions and the second one is the
one a release has to pass, so it needed its own tool rather than a second reading of the
first one's table.
`npm run bench:compare` runs two worktrees of this repository against each other on one
box in one sitting, alternating which side goes first each round so drift lands on both
rather than on whichever ran second. It shares one `node_modules` and one byte-identical
server file, which holds everything except `src/` constant — and is only sound while
`package.json` has not moved between the revisions, which the header says out loud.
Three things it refuses to do quietly, each of which it did once before being taught not
to:
- A run whose connections all errored reports 0 req/s, and a median absorbs that without
complaint. Non-2xx, errors and timeouts now fail the case, and so does a zero. Not on
the warmup, which exists to absorb exactly the cold-start noise a fresh server produces.
- A range-overlap check flags a row as directional, and its own documentation says to
treat that as "measure it again", never as a result. Three samples of two overlapping
distributions separate by chance often enough to have produced a regression report that
five rounds then erased.
- `cors.origins` invocations are counted rather than timed. The benchmark's predicate is a
`Set` lookup, so calls saved are invisible in req/s — but the option takes a function so
it can be a lookup, and there the same saving is a network round trip.
**The runtime servers finally run.** `bench/servers/green-tea-deno.ts` and `-bun.ts` were
written in July and referenced by nothing — not the runner, not a script, not CI. The
runner only knew how to launch Node, so both sat there looking like coverage the table did
not have. Launchers are per runtime now and they get their own section, kept out of the
cross-framework tables because a green-tea-on-Bun row beside fastify-on-Node reads as a
comparison nobody made.
`green-tea-node.ts` is new and loads `dist/` like its Deno and Bun counterparts. The
runtimes table exists to vary the runtime, and a Node row reading `src/` through tsx would
have varied the load form at the same time.
A route-table-width dimension, because every matcher cost scales with how many candidates
a request walks past and the tables here use six routes. Three separate matcher findings
measured as noise before this existed, which said nothing about them and everything about
the instrument.
Finally, `run.ts` preserves whatever sits below a marker instead of overwriting the file
whole. The tables answer what is true today; the notes below them carry which release moved
a number and what the move bought, and regenerating used to delete that silently.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Route matching scanned every method-matching route on every request and ranked the
candidates as it went, calling `moreSpecific` — two `compilePattern` lookups each — per
candidate. Both the scan and the ranking scale with the size of the route table, and the
answer they compute cannot change between requests: the table is assembled once, after the
graph is prepared, and handed to the adapter unchanged.
So the ranking moves to where the table is built. Routes are compiled, bucketed by method
and sorted most-specific-first, and matching walks until the first match and returns it.
`sort` is stable, so patterns of equal specificity keep registration order — which is what
the old scan produced by refusing to replace its best on a tie.
Measured on a request to a parameterised route registered last, against the same tree
without these changes, medians of five and seven rounds:
6 routes no change (every row overlaps)
50 routes +3.3%, +3.5% across two runs
200 routes +14.9%, +12.0% — twelve rounds, not one crossing sample
The shape is the point rather than any single number: the saving is proportional to how
many candidates a request walks past, so it is invisible on a small table by construction.
That is also why it went unnoticed. The benchmark had no route-table-width dimension until
this commit added one, so every matcher change measured as noise no matter how real.
Two smaller savings on the same path. `decodeSegment` now skips `decodeURIComponent` when
the segment holds no `%`, the same gate `normalizeRequestPath` already applies to the whole
path for the same reason. And decoding memoizes per request rather than per candidate: a
scan reaching the same parameter position on several routes used to decode the same string
once per route, and position is all decoding depends on.
`allStatic` is deleted. It short-circuited the scan on an all-literal match, which sorting
subsumes — such a pattern now sorts first and wins by position.
The index is keyed by the identity of the route array, so it is built once and collected
with the table it describes. A table assembled fresh — mesh splicing a teapot's exports in
at boot — is a different array and gets its own index, so no caller has to invalidate
anything.
`matchRoute precedence` already covered the ordering this rewrite had to preserve, and it
passes unchanged. Two cases were missing and are added: that equal specificity keeps
registration order, which is the property the stable sort now carries, and that a parameter
decodes to the same value however many candidates the scan walks. Both pass against the
previous implementation too — they describe behaviour that already existed, which is what
makes them evidence the rewrite preserved it rather than evidence of the change.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
`src/http/core.ts` documented the design as "`stream:open`/`stream:close` already describe
the connection, and now carry the same `requestId`". They carried `{ name }` and nothing
else, on all three emitters, and `Bus.emit` forwards a payload verbatim — so there was
nowhere else it could have been arriving from. The comment described an intent that was
never carried out.
The split it describes is right: a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so ending the request span at the
handler's return keeps hour-long SSE connections out of the same latency distribution as
2ms replies. But the split only works if the two can be **joined**, and `requestId` is the
join key — it is what `EventPayload` defines itself as. Without it an exporter could not
say which request opened the connection still holding a slot, and `traceId`, carried
verbatim so an exporter can hand it to OTLP, never reached the longest-lived thing the
server does.
`route` comes along for a second reason. The contract this beta settled says label on
`route`, never on `name` — and `route` was absent from precisely the events a stream gauge
is built from, leaving a correct consumer with nothing to label. On a stream event `name`
is always the route pattern rather than the concrete path, so the two are the same value
here; both are emitted because the rule a consumer follows is written against `route`.
A WebSocket upgrade correlates itself. It is an HTTP request with headers like any other,
so `runWsConnection` derives its own correlation and adopts a gateway's `x-request-id`
rather than opening a second identity for a connection that already has one. Deriving it
in the one place a ws connection is set up is what keeps it one identity per connection
instead of one per emitter, and it also carries `transport: 'ws'`, which nothing on that
path previously distinguished.
Verified non-vacuous: reverting `src/` fails exactly the six new correlation assertions
across the three emitters and leaves the thirteen lifecycle ones green.
Closes#84
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
`pipeStream` emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame.
`asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and
`app.fetch()` on Node — emitted nothing and called `controller.error(err)`.
Both halves of that were silent. A consumer counting `stream:error` saw zero on three of
the four runtimes while the streams were failing normally, and the client got a truncated
body with no explanation, which from the outside is indistinguishable from a clean end of
stream. The observability guide documents these three events without qualification; on
three runtimes they did not exist.
The error path now frames rather than breaks. Enqueue `encodeError`'s frame, then close
cleanly — the Node behaviour, and the better one: an SSE consumer that received an `error`
event knows what happened, where a transport-level failure looks exactly like the
connection dropping. `controller.error` is kept for an encoder with no error frame to
offer, because then breaking the stream is the only signal left.
`stream:close` is latched. A `cancel` can land after the body already ended, and the three
exits — done, error, cancel — must not each emit their own.
The test drives both adapters from one route table rather than asserting them in separate
blocks, since a table that describes one and then the other is how the two drifted in the
first place. Verified non-vacuous: reverting `src/http/web.ts` fails all four fetch rows
and leaves the three Node ones green, which is the split that says the test is measuring
the adapter and not the framework.
The `sse()` injection test from the previous commit went back to `app.fetch`. It had been
written against `listen()` only because the fetch path swallowed the error — that was a
workaround for this bug, and it is no longer needed.
Closes#83
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
`sseEncoder` wrote one field. With no `id:` on the wire the browser had nothing to put in
`Last-Event-ID`, so every automatic reconnect rebuilt the route's iterable from its start
and lost the gap in silence — a healthy-looking stream that had simply skipped events.
Half of this already worked and it was worth checking before designing anything: the
request envelope has always carried every header, so a handler could already read
`@header('last-event-id')`. It just always arrived empty, because we never gave the
browser an id to send.
`sse(data, { id, event, retry })` tags a stream item; `sseEncoder` writes the fields ahead
of `data:`. An app that never calls it sees byte-identical output. `event:` and `retry:`
come along because the envelope carries them for free and neither was reachable before.
**green-tea stores nothing.** No buffer, no retention window, no replay. The framework
carries the marker in both directions and the handler decides what the gap means, because
only the source knows: a paged log re-reads from an offset, a live sensor has no past
worth delivering. Framework-managed replay would need a stream identity that survives a
disconnect — which does not exist, since every request builds a fresh iterable — plus a
retention policy no default can get right and an in-process buffer that breaks the moment
there are two instances. This commit is also the prerequisite for any of that: whatever
replay might land later keys on these ids.
An id with a newline is rejected, not stripped. An id is exactly the value most likely to
be derived from a request — a cursor, a page token — and the SSE format is line-based, so
one newline lets a caller append arbitrary fields to somebody else's stream. Stripping
would resume from the wrong place invisibly, which is the failure this whole feature
exists to close, so it throws where the stream can report it.
`ndjsonEncoder` unwraps the payload and drops the fields: a `negotiate` route yields the
same items to both encoders, and NDJSON has no frame to carry them and no resumption
protocol to use them.
Verified non-vacuous: reverting just the two `encode` functions fails the six framing and
round-trip assertions and leaves the validation ones passing, which is the right split.
Closes#46
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>