Commit Graph
44 Commits
Author SHA1 Message Date
chrnx 4896ee86d2 fix(jsr): resolve require from source, not from tsup's banner
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.

The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.

Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.

Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.

Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.

Closes #69.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:50:42 -05:00
chrnx bb0b01cf26 fix(cors): deny the origin when the origins predicate throws
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 29s
`CorsOptions.origins` accepts a predicate, and it runs on the request path above the
region where errors convert to a response. A predicate that threw became a rejected
promise nobody awaited, and Node's default for that is to exit — so one cross-origin
GET took the process down, with `onError` never reaching it.

The trigger is a browser: `originAllowed` only runs when an `Origin` header is present,
so the crash is reachable by any cross-origin client and by no test that forgets the
header, which is how it survived a green suite.

Guard the call at `originAllowed`, the single point all four call sites funnel through
(the Node handler, `computeInjected` on both adapters, and the preflight path). A
predicate that throws denies the origin: a lookup that failed has not said yes, and a
broken allowlist must never widen into an open one. The failure is reported through the
app logger rather than swallowed — `HttpOptions` already carries one.

The published behaviour changes for a throwing predicate only. Every other origin shape
is untouched, and the security headers still land on the response.

Amends one test from the `maxConcurrentRequests` contribution, which asserted the old
crash as its baseline while proving the gate does not leak a slot. It still proves that,
against a transient failure that is now answered rather than fatal.

Closes #72.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:39:11 -05:00
hgshreyas ff94e55496 feat: cap concurrent requests across runtimes
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 29s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-31 08:53:14 -05:00
hgshreyas 82e1678dea fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-30 12:55:20 -05:00
chrnx 9b5347aa75 fix(observability): correlate requests on Node 18, where there is no global crypto
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 28s
`engines` promises `>=18`. The global `crypto` arrived unflagged in Node 19.
Between those two facts, `correlateRequest` compiled cleanly against an ambient
`declare const crypto` and then threw `ReferenceError: crypto is not defined` on
the first request of every Node 18 process — which is to say the observability
work made the framework unusable on its own stated floor.

Nothing local could see it. Every developer machine here runs 20 or 22, and
Deno, Bun and workerd all expose the global. CI's Node 18 job caught it on the
promotion pull request, which is the entire reason that job is pinned to the
floor rather than to the current release.

The global stays the primary path, because it is why this file does not simply
import node:crypto: it is the runtime-neutral core, and node:crypto is not
available to all four runtimes. The fallback is reached only where the global is
absent, so workerd never evaluates the require, and the ESM build has a real one
from the createRequire banner already in tsup.config.ts. Verified in both built
formats rather than assumed — esbuild rewrites it to require("crypto"), which is
the same module.

test/node-floor.test.ts stubs the global away to reproduce the floor's condition
on any Node, and was confirmed to fail against the previous code. The bug was
invisible where it was written; this makes it visible there.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 18:11:50 -05:00
chrnx a4bb3c02d6 refactor(http): resolve each request once, in the core that already routes it
Both adapters routed every request themselves, and then handle() routed it
again from the same inputs — a four-route app walked its table 2.5 times
per request. Neither side was wrong: an adapter must know the route to
decide whether to read a body, and the core must know it to dispatch.

The cause was the shape of the handoff. NeutralRequest carried an
already-parsed body, so producing one was the adapter's problem, and every
policy that depends on the matched route came with it — these four chains
were written out in server.ts and web.ts character for character:

    matched.def.maxBodyBytes   ?? opts?.limits?.maxBodyBytes ?? 1_000_000
    matched.def.bodyDuplicates ?? opts?.bodyDuplicates       ?? 'last'
    matched.def.maxParts       ?? opts?.limits?.maxParts     ?? 1000
    opts?.limits?.maxBodyBytes ?? 1_000_000

A fifth knob, or one changed default, meant editing both or letting the
runtimes quietly disagree about limits.

Handing over the ability to read rather than the result moves the decision
to where the route is already known. What stays in an adapter is what
genuinely differs between runtimes: getting bytes in, putting bytes out.
Enforcement stays with the reader too, because Node aborts an oversized
upload as chunks arrive while a fetch runtime can only measure what
arrayBuffer() already resolved — passing the limit in preserves that.
413/400/501 keep their exact current shape, Node's connection: close
included; it now has the test it never had.

Measured through app.fetch, both versions in one process, interleaved:
40 routes with the match declared last, 3.89 -> 3.58 us (-8.2%). One
route, where there is no second scan to save, is unchanged.

The first cut of this was 13% SLOWER, and the reason is worth recording:
a per-request closure for the reader plus the error-context object it
captured cost 250 ns, and the async frames around a body that did not
exist cost another 215 ns — together more than the duplicate scan the
whole change removes. The reader is now built once per server and takes
the runtime's request as an argument, and a bodiless request touches no
promise on this path at all.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:46:57 -05:00
chrnx 0c9f8a545e fix(router): route dot segments the same way on every runtime
The same bytes on the wire reached different routes depending on where
the app ran. `GET /public/../admin` hit a `/admin` route under Deno, Bun
and workerd, and 404'd under Node — 200 vs 404 for one request.

The fetch-based runtimes resolve dot segments inside the `Request`
constructor, before green-tea is handed anything: `new Request(
'http://x/public/../admin').url` is already `http://x/admin`. Node's raw
target has no such step. Rejecting outright — the stricter policy, and
what this module already does for `//` — is not implementable on three of
the four runtimes, because the raw target is unrecoverable there. So Node
converges on the rule the other three cannot opt out of.

`%2e` is a dot to the URL parser, so the encoded spelling resolves too;
leaving it out would keep it as a way to reach a route the plain spelling
resolves away from.

Cost is gated: paths with no `.` and no `%` pay two indexOf scans
(20.0 -> 21.7 ns for `/hello`), a literal dot pays the regex (35.5 ns),
and only real dot segments pay the split (103.6 ns).

The existing parity suite could not have caught this — its `both()`
helper goes through `fetch()`, which normalizes the URL before it reaches
the wire. The new cases write the request line to a socket by hand.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:35:26 -05:00
chrnx e625d5c881 perf(router): stop the route scan at a match nothing can outrank
matchRoute evaluated every registered route before answering, so `/hello`
cost the same whether it was declared first or last among 32 routes —
1227 ns against 1237 ns. That is ~38 ns of scanning per registered route
on every request, growing with the route table, and the benchmark app has
the smallest table any real service would have.

Specificity ranks a literal segment above every other kind, so a pattern
made only of literals cannot be outranked by anything else matching the
same path, and an equal rank keeps registration order — which is the
route already in hand. Finishing the scan only re-derives it.

The path split moves out of matchCompiled for the same reason: `split` +
`filter` ran once per candidate route on every request, always producing
the same array. Doing it once per request is 63.7% off a 32-route scan
that early exit cannot help at all (a :param match, which must be
compared against the rest of the table).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:35:06 -05:00
chrnx 8d8ef7ed09 perf(http): look injected header keys up directly instead of rebuilding a Set
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>
2026-08-16 22:57:37 -05:00
chrnx 0c5decbeae perf(router): skip query parsing when there is no query string
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>
2026-08-16 22:55:46 -05:00
chrnx 86dd3fe9b6 perf(router): stop decoding every path segment to throw the result away
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>
2026-08-16 22:44:35 -05:00
chrnx e052d5ba8f feat(observability): request-level events, and request logging that reads them
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>
2026-08-16 14:57:42 -05:00
chrnx 7b0a3d4e24 docs(observability): record why randomUUID is the fast option, not the lazy one
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>
2026-08-16 14:45:17 -05:00
chrnx dabab1812b perf(observability): hoist a per-request closure out of correlateRequest
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>
2026-08-16 14:42:13 -05:00
chrnx 633ef58032 perf(observability): do not build event payloads for an empty room
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>
2026-08-16 14:26:16 -05:00
chrnx 2c47ee8896 feat(observability): correlate and time the lifecycle event stream
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>
2026-08-16 14:20:44 -05:00
chrnx 586e14da72 feat(runtimes): a bounded close() on the Deno and Bun adapters
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>
2026-08-16 13:16:24 -05:00
chrnx 30f33b6383 fix(http): narrow buffered bodies to what the runtime's Response accepts
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>
2026-08-16 12:45:37 -05:00
hgshreyas 8c781c1258 fix: treat non-positive connection limits as unlimited
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-10 16:14:07 +05:30
hgshreyas 9e5e5cffe9 feat: add concurrent connection limits
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-09 17:27:47 +05:30
chrnx a2acec69bf feat(openapi): document constrained route params
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:47:18 -05:00
chrnx 9a61ba8646 feat(http): complete HEAD and OPTIONS semantics
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:45:44 -05:00
chrnx 8e38fffd77 fix(router): reject invalid and ambiguous paths
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:39:09 -05:00
chrnx 790db661e5 feat(router): compile safe constrained patterns
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:36:46 -05:00
chrnx dba40b0c8b feat(mesh): heartbeat the link, and tell the truth when a teapot is gone
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>
2026-07-15 23:32:45 -05:00
chrnx 0c68cba532 feat(mesh): mount the control channel on app.upgrade, and close links without a server
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>
2026-07-15 15:13:20 -05:00
chrnx 0ea4db3fef feat(mesh): connect the teacup over a runtime-neutral WebSocket client
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>
2026-07-15 15:00:04 -05:00
chrnx 71b59e7c25 refactor(mesh): serve the control channel over the neutral WsSocket
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>
2026-07-15 14:53:09 -05:00
chrnx d56eeafcd8 refactor: close type holes on the transport and error axes
- 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>
2026-07-15 14:37:03 -05:00
chrnx 9421b102d9 refactor(adapters): share ws plumbing across bun/deno/edge
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>
2026-07-15 14:37:03 -05:00
chrnx ad3a06f057 feat(views): zero-config static directory serving
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:42:20 -05:00
chrnx 70925035d7 fix(http): lazy-load http/https so createApp is edge/workerd-safe; drop test shim
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 23:40:28 -05:00
chrnx 7a8be39d57 refactor(ws): Node adapter builds WsSocket over the neutral core
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>
2026-07-09 16:56:17 -05:00
chrnx 5e68d2de65 fix(ws): runtime-neutral close reason + registry removal on transport close
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 16:51:42 -05:00
chrnx 179a58f0e4 feat(ws): neutral runWsConnection core behind a WsSocket capability
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 16:44:59 -05:00
chrnx 43a4316a29 fix(fetch): gate x-forwarded-for on trustProxy in app.fetch
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>
2026-07-09 14:45:27 -05:00
chrnx b75f127b2c fix(http): merge security headers into app.fetch CORS preflight responses
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>
2026-07-09 14:33:31 -05:00
chrnx 08cb8554e6 fix(fetch): security headers on early failures, live mesh boot gate
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>
2026-07-09 14:26:45 -05:00
chrnx 93a4246de5 feat(app): app.fetch — Web-Standards handler over the neutral core
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:15:26 -05:00
chrnx fc75cc05e5 feat(http): asReadableStream — AsyncIterable to web ReadableStream
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:04:03 -05:00
chrnx 16823408c7 refactor(http): extract runtime-neutral handle() core
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 13:58:35 -05:00
chrnx 118eb5516d refactor(http): extract mergeInjectedHeaders pure helper
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 13:51:55 -05:00
chrnx 2db5de6858 feat: per-route body limits, custom error rendering, OpenAPI generation
CI / build (push) Has been cancelled
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>
2026-07-08 08:29:17 -05:00
chrnx d6c5cee0ee feat: beta-hardening — routing, degradation, mesh gate, uploads, @header
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>
2026-07-07 12:00:15 -05:00