mergeInjectedHeaders rebuilt a lowercased Set of the injected header keys on
every response: an array from Object.keys, a mapped array from toLowerCase, and
a Set from that. Three allocations to answer a question the object already
answers.
The lowercasing was the redundant part. Every key `injected` can hold is written
as a lowercase literal in src/security.ts — buildSecurityHeaders and resolveCors
are its only sources — so the mapped array was a copy of the keys it started
with.
hasOwnProperty rather than `in`: a handler may legitimately send a header named
constructor or toString, and `in` would find those on Object.prototype and drop
them silently.
146.4ns to 55.9ns in isolation; -3.2% end to end over five interleaved rounds,
with all five pairs favouring the change.
Third of three fixes from the same profile, and all three are one pattern:
work done unconditionally for a case that rarely or never applies — validating
encoding that is almost never malformed, parsing a query string that is not
there, lowercasing keys that already were.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.
92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.
Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.
Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
normalizeRequestPath ran on every request and validated percent-encoding by
splitting the path and calling decodeURIComponent on each segment, discarding
every result — matching is done on the raw path. Two array allocations and one
decodeURIComponent per segment, per request, to prove that a string nobody
decodes could be decoded.
Measured in isolation: 95.8ns for /hello, 342.7ns for a six-segment route. The
guard costs 15.7ns and 6.7ns for the same two paths.
Same validation. decodeURIComponent throws on the first malformed % sequence
wherever it appears, so one call on the whole string catches what per-segment
calls caught, and %2F inside a segment decodes fine either way. Only the throw
was ever used. The existing tests for malformed encoding and repeated slashes
pass unchanged.
Found by sweeping all 178 commits between fe1831a and the observability work
after the regenerated benchmark showed green-tea down ~20% since July while
raw-http, fastify and nestjs-fastify reproduced their July numbers within 1.4%
on the same run. The sweep put a +11.8% step at 9a61ba8 "complete HEAD and
OPTIONS semantics", which is where this function entered the request path.
Effect: -6.2% in-process request latency, from twelve interleaved measurements
whose ranges do not overlap (OLD 4.253-4.425us, FIX 4.035-4.151us). A first
attempt measured with-then-without and produced the opposite sign, so the
interleaving is load-bearing, not ceremony. Expect roughly 2% over a real
socket, which is below that harness's own noise floor.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.
handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.
route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.
logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.
The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.
Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Benchmarked the alternatives rather than leaving the question open. Every
supported runtime already batches entropy behind randomUUID, so the intuitive
replacements lose: Math.random() twice into base36 is 3.5x slower at 265ns
because the string work dominates, an unbatched getRandomValues is 472ns, and
a uint32 pool through toString(36) is 114ns.
The only cross-runtime improvement is a hand-rolled entropy pool with a hex
lookup table at 50ns, which saves 26ns — 0.26% of a real 10.19us request. Not
worth owning an entropy pool for. Buffer.toString('hex') matches it but is
Node-only, which this file cannot be.
Table left in the code so the next person does not re-run it.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The `first` helper was declared inside correlateRequest, so it was allocated on
every request. It captures nothing, so module scope is where it always
belonged.
Measured at 0.16us against a ~4.4us in-process request — 45% of the entire
remaining observability overhead, from one line. Total overhead is now +0.24us
rather than +0.44us, which against the 10.19us of a real socketed request is
~2.4%.
Ablation of what is left, so the next person does not repeat it: randomUUID is
0.16us of the 0.24 and the other 0.08 is the header read, the extra properties
and three hasListeners lookups. Building the correlation literal per request
costs nothing measurable — V8 keeps it on the stack — so do not go optimising
that one.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The correlation work regressed the in-process hot path from 4.52us to 5.43us
per request, ~20%. The design predicted 0.25% per step and was wrong by more
than an order of magnitude, so recording what the measurement actually said:
spreading correlation into payloads ~197ns <- the cost
crypto.randomUUID() ~170ns in place
try/catch inside the step loop ~2.6ns <- not the cost
emit() cannot avoid the first: its argument is already built by the time it is
called. Only the caller can decline to build it, so Bus.hasListeners lets it,
and runSteps hoists the check out of the loop since listeners are registered at
boot. An application subscribing to nothing now pays a branch instead of four
payloads and three clock reads for an audience of nobody.
That recovers half. 4.96us remains against 4.52us — ~10% in process, ~4.5%
against the 10.19us of a real socketed request. Two ways to shave the rest were
measured and both rejected in comments: a lazy requestId is defeated by the
first spread, and a boot-prefix counter is 5x cheaper but trades the standard
identifier shape for ~1.7%. Neither earns its complexity yet.
The remaining cost is the feature, not an accident: correlation only exists if
something carries it.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Tasks 1-3 of the observability plan. The Bus already had 19 emission points;
what it lacked was any way to tell which request an event belonged to, which
made the whole stream unusable under concurrency.
Every per-request event now carries requestId, traceId, route, method and
transport, and request:step:leave carries durationMs — a field that has been
declared in EventPayload since the beginning with nothing ever writing it.
Identity is derived in the adapters rather than in handle(), because both read
and size-check the body first: a 413 is answered without handle() ever seeing
the request, so generating there would leave exactly the failures an operator
most wants to correlate with nothing to correlate them by. An incoming
x-request-id is adopted rather than replaced, and traceparent is carried
verbatim — core implements no propagation spec.
Timing takes N+1 readings for N steps, since one step's end is the next one's
start. Measured at 25.2ns per step against a ~10.19us request.
request:step:error now names the step that actually failed. It reported
name: 'pipeline' before, discarding the one fact it exists to carry, because it
was emitted from the outer catch where that is all that is known. The outer
catch emits request:failed instead: one marks the span, the other the trace.
route carries the matched pattern and never the concrete path. Labelling a
metric on raw URLs gives unbounded cardinality and takes down the metrics
backend rather than the app, so it is a contract, with a test.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Closes#15, taking the second of the two answers it framed: app.close() stays
Node-only, and each transport that owns a handle offers the same close({
timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun
because they serve through app.fetch and never through listen(), and only the
transport can drain what it accepted. The warning there now names the
replacement instead of pointing at this issue.
The runtimes do not agree, and the code says so rather than averaging them:
Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves
between them like Node's closeAllConnections().
Deno cannot. Its two levers are mutually exclusive — aborting the serve signal
while shutdown() is pending throws BadResource from Deno's own listener,
uncaught and fatal under deno test. Measured on 2.9: abort alone is clean,
abort after shutdown is not. So on Deno the deadline bounds how long close()
waits, not when connections die, and both the type and the timeout warning say
that outright. Silently accepting an option that does less is the failure mode
AGENTS.md rules out.
closeWithDeadline is shared so the two cannot drift into different meanings of
the same timeoutMs, and it resolves on its own timer rather than awaiting the
force call — Bun's stop(true) was measured waiting out a handler with a pending
timer, which is exactly the unbounded wait the deadline exists to prevent.
serveDeno now owns the AbortController it serves with, chaining any caller
signal into it so neither party loses control; a test covers that. The Bun
ambient said stop() returns void, which was simply wrong.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
A Node Buffer is a Uint8Array at runtime, but its declared backing store is
ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only
ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This
is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went
unnoticed because every implementation is forgiving about it at runtime.
Re-views rather than copies: this is the buffered-response path, and a copy
per response would cost real throughput on the runtimes that have no other
adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands
back a window into a shared 8 KB pool, and dropping them returns the whole
pool. A direct test covers that; the static-serving one covers the integration.
The type is derived from Response's own constructor because BodyInit is not a
global under lib es2020 plus @types/node, though Response itself is.
Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Three bugs, found by writing the tests for the status codes.
A teapot with a live control channel could never shut down. Control connections
were never registered with the stream registry, so server.close() sat waiting on
a connected teacup that had no reason to hang up, and app.close() never resolved.
Every other long-lived socket was already tracked; the control channel was the
one that skipped it.
A downed teapot answered 500 — after 30 seconds. sendRpc queued the frame on a
closed socket and waited out the full timeout for a verdict already known. It now
rejects immediately with 503: a dead upstream is not "this service broke", and the
status is what tells a caller it may retry and an operator where to look. An RPC
that times out on a *live* link is 504 — a slow teapot and a gone one are
different stories.
Heartbeat: each teacup pings its teapots (`mesh.heartbeatMs`, default 15s) and
closes a link after two unanswered rounds. This is what catches a half-open
connection, where the socket looks open with nobody home — otherwise a teacup only
learns on the next request. Ping/pong are mesh frames rather than WebSocket
protocol pings because Deno's and Bun's platform WebSocket does not expose
ws.ping(), so a protocol-level heartbeat could not work everywhere mesh runs.
Added to v1 while the wire still has no deployed peers; later it would be a
version bump that refuses every old peer.
The heartbeat's first close code was 1011, which silently did nothing: a *client*
may only send 1000 or 3000-4999, so it threw `invalid code` — and our neutral
close swallows throws, so the link stayed open while looking closed. 4011 mirrors
1011's meaning inside the application range.
Reconnect (and reconciling app-scope values, which survive their teapot from
cache) stays out — it is a post-beta spec of its own.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Two halves of the same "mesh off Node" gap; they touch the same file and landed
together.
Control channel (Task 6): meshControl existed only inside listen(), passed to
createHttpServer, so a teapot could only export its scopes from Node. app.upgrade
— the path serveDeno/serveBun drive — had never heard of it, which would have left
"mesh on three runtimes" meaning consume-only. It is now built in the boot gate
(it captures the finalized ordered nodes, so it cannot exist before finalize) and
the reserved path is routed from app.upgrade. Task 3 already made handle() take a
neutral WsSocket and upgrade holds one, so this is a direct call, not a second
implementation. handle() returns the connection's lifetime like runWsConnection,
so upgrade awaits it instead of returning while the peer is still talking. An app
with nothing exported refuses the reserved path explicitly rather than falling
through to "no matching ws route".
Link lifecycle (Task 7): links were reaped by server.on('close'), reachable only
through listen(), so a mesh app booted through app.fetch had links and no server
and leaked every teapot connection at `if (!server) return`. close() now closes
them first either way; that aborts each socket, which rejects its in-flight RPCs.
Also fixes a race the new tests exposed: upgrade awaited the boot *before* handing
the socket to a consumer, but `channel` is fan-out, so frames arriving during the
boot were dropped with no subscriber attached. For the control channel that is
`hello` itself — against a teapot with slow providers the handshake would hang
until timeout. Inbound is now subscribed synchronously on entry and the buffered
iterator handed down, closing the same gap for regular @Ws routes.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Tasks 6, 7
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
connectLink constructed `require('ws')` directly and drove its EventEmitter API,
which is why a teacup could only run on Node. It now goes through the neutral
WsSocket like every other consumer, over whichever client the runtime provides:
the platform global (Deno, Bun, Node >= 22) or the `ws` peer for Node 18-21,
which has no global. `ws` stays optional and is only reached for when the global
is absent.
One bridge covers both because `ws` also implements the browser-compatible event
API and delivers text frames as `event.data` strings — probed against the real
package rather than taken on faith.
Both implementations are exercised in one run: `ws` is always in the matrix, so
the Node 18-21 path cannot rot unseen on CI that only runs a modern Node, which
is how a fallback quietly stops working. connectLink takes an optional Ctor to
make that possible; it doubles as a bring-your-own-WebSocket hook for runtimes
we do not ship an adapter for.
Verified the edge bundle is unaffected: `require('ws')` tree-shakes out of the
workerd build entirely.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 4
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The mesh control channel was the last consumer speaking the `ws` EventEmitter
API directly: http/ws.ts handed meshControl.handle a raw socket, while every
@Ws route already went through nodeSocket() to get a neutral WsSocket. Mesh did
not lack an abstraction — it skipped the one the codebase already had.
handle() now takes a WsSocket and consumes `inbound`, so both feeds work: Node
via the existing nodeSocket, and Deno/Bun via app.upgrade, where the socket is
already neutral. That is what unblocks mounting the control channel off Node.
RPCs are still dispatched without awaiting. The old `ws.on('message')` listener
overlapped them, and the peer's id-keyed pending map exists for exactly that —
awaiting inside the receive loop would have silently serialized every mesh call.
A test now pins the overlap.
The unused `http` import in http/types.ts fell out with MeshControl's req
parameter: nothing in that module is Node-shaped any more.
Node behaviour is unchanged — the teapot↔teacup integration tests pass
untouched. teapot.test.ts drives handle() directly, so its fake moved from a raw
EventEmitter to a fake WsSocket.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 3
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
- OpenApiRoute.transport was typed `string`, so the compiler could not check the
transport branching at all. Type it Transport and key the documented 200 off a
Record, so a new transport fails the build instead of silently going undocumented.
- pickEncoder fell through to ndjson for unknown transports; make the mapping
exhaustive so a new transport cannot inherit the wrong wire format by accident.
- HttpError carries optional headers, removing the instanceof Redirect special case
that coupled the error renderer to one subclass. Custom errors needing headers
(retry-after, etag) no longer require touching transformers.
- Drop the module-global connSeq in mesh/link: `pending` is already per-connection,
so a per-link counter suffices and connection ids stop depending on test order.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
toWsRequest, the neutral-socket wrapper and the upgrade error guard were
copy-pasted across all three runtime adapters, comments included. A change to
the upgrade close code meant remembering to touch three files.
Extract the shared parts to http/ws-adapter (kept separate from ws-core: that
module runs a connection, this one builds one from a host runtime's socket).
Bun keeps its own socket wrapper — its events land on a server-level handler
rather than the socket, so the lifecycle genuinely differs.
Verified against real runtimes: deno test, bun test, workerd via miniflare.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Also fixes buildWsRoutes (app/index.ts) to read the pre-derived
protocol/ip off the neutral WsRequest instead of req.socket, which no
longer exists now that WsOpenCtx.req is WsRequest — without this every
real @Ws route throws on open() and the connection hangs.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The Web-Standards fetch adapter read x-forwarded-for unconditionally to
seed ctx.ip, unlike Node's deriveIp which only honours it when
trustProxy is enabled. A client could spoof ctx.ip on any handler
relying on it. Mirror deriveIp's first-hop semantics and only trust
the header when trustProxy is set; otherwise ctx.ip is ''.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Add a Node-vs-app.fetch parity suite that drives GET/POST/404/CORS-preflight/SSE
through both the real Node server and app.fetch and asserts identical status,
headers, and body. It caught a real divergence: buildFetch's preflight branch
returned only the CORS-specific headers, skipping the security headers
(x-content-type-options, x-frame-options, referrer-policy, x-dns-prefetch-control)
that the Node adapter's writeHead patch applies to every response including the
204 preflight. Fix buildFetch to merge `injected` into the preflight response the
same way, so both paths agree.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
app.fetch's 413/400/501 body-acquisition failures were returned without
the injected security/CORS headers Node's writeHead patch always
applies, breaking byte-identical parity with the listen() path. Extract
computeInjected() (shared by handle() and buildFetch()) and merge it
into every error response, not just handle()'s outcomes.
Also, buildAppFetch captured `booted` by value at createApp() time, so
mesh apps (whose finalize() is deferred into listen()) had app.fetch
permanently throw even after a successful listen(). Read booted live
via a getter, mirroring explain()/graph()/inspect(), and lazily
build/cache the fetch handler on first call after boot.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Three capabilities that share the same request/route metadata:
- **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })`
overrides the server-wide `limits` for one route (falls back to the
global default), mirroring the existing per-route `duplicates`.
- **Custom error rendering** — `createApp({ onError })` takes over how any
error becomes a response (HTML, RFC 7807, content-negotiated), covering
the whole surface: handler/step throws, 404, 405, 413, 400. Returns a
response or undefined to fall back to the default JSON. Also wires the
previously-unused `HttpError` `body` field so `throw new HttpError(409,
'conflict', { code })` renders a structured payload. Default behavior is
unchanged when no hook is set.
- **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a
structural spec (paths, methods, path/query/header params, request-body
presence, systematic error responses); opt-in `GET /__openapi__` via
`devOpenapi`. Body/response schemas stay generic (Standard Schema exposes
no JSON Schema) — the full `@Produce` mode is post-beta.
Docs: new error-handling and OpenAPI guides, plus reference updates.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).
On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:
- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
catch-all, not registration order), and 405 + Allow when a path exists
under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
`mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>