Commit Graph
252 Commits
Author SHA1 Message Date
chrnx 44c783439c fix(graph)!: enforce the node and handler return contracts instead of failing silently
provide() and run() must return an object holding every token the node
provides. A provider that returned its value bare (return client rather
than return { db: client }) booted without complaint: the token was
undefined, and the client's own properties were spread over every
request's context. That now fails, naming the node and the fix:
- providers fail the boot;
- steps fail the request;
- plugin nodes are held to the same rule for each token in provides.

A handler that returned a Fetch Response was JSON-encoded and went out
as 200 {}, with its status, headers and body lost. It now fails the
request with a TypeError that points to a plain value, @Transformer or
HttpError. Sending a Response as is can be added later without
breaking anything; taking it back would not be possible.

The check stays synchronous for a synchronous node, so a plain step
adds no microtask. Fixed health tests whose providers returned {}.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 11:22:10 -05:00
chrnx 86d6954f72 test(runtimes): close the 1c exit-gate cells for health and compression on Deno and Bun
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 31s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 34s
The CARD-22 gate audit found these runtime cells without tests:

- CARD-17 T1-T3 (booting, ok, degraded) existed only on Node. Add them
  on Deno and Bun. T1 goes through app.fetch, because serveDeno and
  serveBun boot before they bind. T2 and T3 go through a real listener
  and assert the response body, not only the status.
- CARD-16 T6 (encodings ['gzip'] with a br-only client gives identity)
  was missing on Deno and Bun.
- CARD-16 T8 on Deno and Bun lacked the handler-set content-encoding
  case and the 204 case.

A negative run of T6 against compression: true fails with 'encoded as
br', so the check can tell the two cases apart.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 10:26:30 -05:00
chrnx 870cdb25e9 fix(adapters): reject createApp({ tls }) on Deno and Bun
Only Node's listen() reads tls. serveDeno and serveBun serve through
the runtime's own listener, so an app created with tls came up as
plain HTTP without warning, for a caller who had asked for HTTPS.

createApp now marks the app with a symbol, following the MARK_EDGE
pattern. Both adapters throw on that mark before they boot or bind.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 08:53:52 -05:00
chrnx fe4827ccb3 perf(compression): send no Vary on a body under the threshold
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 22s
CI / runtimes (deno) (pull_request) Successful in 33s
A buffered body under the threshold is sent identity whatever the client
accepts, so Accept-Encoding played no part in it and RFC 9110 asks for
no Vary. A cache that stores it for everyone is right to: every client
accepts identity. Responses that are encoded, or that are identity for
a request-side reason (identity client, HEAD), and every 304 keep Vary,
as does every compressible edge response, since Cloudflare encodes
there.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 22:39:06 -05:00
chrnx b86cd605c4 perf(http): resolve ctx.ip on first read instead of on every request
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 34s
Every Bun request called server.requestIP() for ctx.ip (#116), a native
call that builds an object, whether anything read the address or not. On
Mac that measured 7-11% of a small request; recording the server in the
peer map instead costs nothing.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 14:31:20 -05:00
chrnx 133af8dfe5 perf(http): read a declared-length fetch body with arrayBuffer()
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 32s
The chunked reader added for the incremental 413 (4d1639f) cut a Bun JSON
POST by more than half: 37.6k -> 11.7k req/s on jarvis. A well-formed
Content-Length inside the limit already bounds the body, because the
runtime frames it by that header, so arrayBuffer() is safe there and native
in Bun, Deno and workerd. byteLength is still checked for a Request built in
user code whose header and body disagree. Chunked uploads keep the bounded
read.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-27 22:35:03 -05:00
chrnx 88be9b1cb2 perf(http): skip the body stream for a request without a body
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 32s
On Node every request goes through readBody, GET included. Subscribing
listeners to an empty request stream measured ~4% slower than the old
async iterator on an 8 KB GET response, in both orders on jarvis.

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:49:46 -05:00
chrnx bc04330a27 fix(params): match @header names without case (GitHub #37)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
Node's IncomingHttpHeaders and the fetch adapter's headersToRecord
both store request header names lower-cased, but resolveOne looked a
@header/@headers key up exactly as the decorator wrote it. Any name
with a capital letter, such as @header('Content-Type'), therefore
reached the handler as undefined.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:36:18 -05:00
chrnx 5536093894 fix(multipart): accept exactly maxParts parts (#118)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
busboy emits `partsLimit` once its part count reaches `limits.parts`,
not when it passes it, and parseMultipart treats that event as a
malformed body. With `maxParts: N` a body of exactly N parts was
therefore rejected with 400 and only N-1 were accepted.

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 19:29:31 -05:00
chrnx 0ba15b7862 fix(graph): report a self-dependency as the cycle it is (GitHub #43)
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
A node that needs the token it provides is a cycle of one, so say so in
the same words as every other cycle (`cycle detected: a -> a`), and name
the token and the fix:

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:42:22 -05:00
chrnx 510e9c4863 fix(container): cache the in-flight promise of an app-scoped binding (GitHub #46)
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 19s
Container.resolve marked an app-scoped binding resolved only after its
factory settled. Two resolutions that started before then both found
nothing cached and both ran the factory, so one token could open two
pools.

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:23:29 -05:00
chrnx 51fa7c1a88 fix(shutdown): treat a graceful close that throws synchronously as a rejection
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / runtimes (deno) (pull_request) Successful in 33s
closeWithDeadline called graceful() directly inside the Promise
executor. A graceful path that threw before returning its promise
escaped the executor, so the close() that serveDeno and serveBun
return rejected on the spot. The deadline timer had already been armed
and nothing cleared it, so it later fired anyway: it logged a timeout
and forced a server whose close() had already given up.

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

GitHub #47.

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

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

GitHub #45.

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 15:52:50 -05:00
chrnx dc88fdef10 Merge pull request #32 from otrumb/fix/module-mountpoint-error
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
fix(app): validate module mountpoints at runtime
2026-10-24 15:49:32 -05:00
chrnx 92d54dcc45 feat: name every type the public signatures use, before the freeze (CARD-22, D19)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 32s
D19 as amended 2026-10-24: nothing that shipped in 26.9.0-beta.2 is
removed. Every symbol D19 had listed for removal or review is in that
release, so this change only adds exports and marks scope.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 14:13:39 -05:00
chrnx 07d9b7441c fix(mesh): RPC frames wait for the send buffer too (CARD-26, #41)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 34s
CARD-26 made the WebSocket route pump await `drained()` before each pull,
but mesh RPC traffic sends outside that pump, so it never waited:

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

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

Found in the pre-freeze integrated review.

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

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

Found in the pre-freeze integrated review.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 13:55:06 -05:00
chrnx a9a4f6c6ef fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 19s
The outbound pump pulled a @Ws handler's iterator as fast as it yielded,
whatever the peer read. With a slow client, 10,000 frames of 64 KiB were
all pulled at once and sat in the send buffer: 640 MiB.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:16:43 -05:00
chrnx 713122d53a fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
The 1 MiB inbound cap from #107 applied to every WebSocket, the mesh
control channel included. An RPC carries a whole request body, so a body
inside maxBodyBytes could still overflow the cap once wrapped in an
rpc-req frame, and the teapot then closed the whole channel with 1009:
every request through that link failed 503 until it reconnected.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:16:43 -05:00
chrnx 3296189093 feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:12:48 -05:00
chrnx d32fc9f8d7 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 27s
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:09:54 -05:00
chrnx 7f9a0eef0f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00
chrnx 9ea1365b66 test(router-parity): a late teapot is served after it connects for CARD-19 (owner approval required)
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
owner-mesh-lifetime.json froze phase B2 (teapot absent at boot, then up)
at 404 for GET and POST /api/remote/ping. The table was built once at
boot, so a late teapot was never spliced in. CARD-19 (#124, D15) changes
that. B2 now answers GET 200 {"from":"teapot"} and POST 405 with
Allow: GET, HEAD, OPTIONS, the same as A1.

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:39 -05:00
chrnx ae9e5529e8 test(router-parity): HEAD on a remote GET answers 200 for CARD-20 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
owner-mesh-allow.json froze HEAD /api/x at 404 on both adapters: the
teacup forwarded HEAD to the teapot, which has no HEAD plan for the
route. CARD-20 (#125, D16) fixes that, so HEAD now answers 200 with the
GET's headers and an empty body, like a local route.

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx f0530b15bb feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:57:10 -05:00
chrnx 9977d14605 test(router-parity): reserved mesh path refused on Node for CARD-21 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
Golden update for ws-node-upgrade.json, needs owner approval (CARD-08
rule). The WS parity fixture declared @Ws('/__mesh__/control') to
capture the old adapter split: the Node listener served it (101, the
route's frame, close 1005), app.upgrade refused it (1008). Under D17
that route fails createApp, so the fixture drops it and keeps the path
in UPGRADE_PATHS. The Node row now matches the app.upgrade row: 101, no
frame, close 1008 with the shared reason.

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:50:26 -05:00
chrnx 88cbe41f72 feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket
upgrade, so any client that sent the header chose its own address, and
it never read the header for HTTP, so IP-keyed plugins saw '' there.
D21 settles both: the header counts only under trustProxy, on both
paths, with no new option.

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:47:58 -05:00
chrnx 8bf54ec168 fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:02:42 -05:00