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>
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>
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>
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>
The A/B harness had no case with compression on, so a change to the
response write path was measured only on its uncompressed branch. Add an
8 KB JSON response uncompressed, identity-negotiated, gzip and br, plus a
small response under the threshold with compression enabled.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Two Breaking entries in [Unreleased] described a new boot failure
without the step that fixes it. Found in the second pre-freeze review.
- #127, constrained route params that tie: make the constraints
disjoint, keep one route and branch in the handler, or give one its
own static segment. A plain param reported unreachable never served a
request, so delete it or narrow the constraint that shadows it. For a
WebSocket pair, declare the constrained route first.
- #126, reserved `/__mesh__/control`: move the route to another path.
Nothing replaces the reserved one, which never reached a route on
Deno, Bun or the edge.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
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>
#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>
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>