Commit Graph
141 Commits
Author SHA1 Message Date
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 24feca481c feat: shutdown teardown for plugins, providers and applications
Closing a connection meant writing process.on('SIGTERM') by hand: closeApp
drained the server and mesh links and knew nothing about the graph, and the
Bus had no shutdown event at all, so a plugin could not even observe that the
app was going away.

Implements docs/plans/2026-08-17-shutdown-teardown-design.md, D1-D8.

Three doors into one registry, with one order and one failure policy — a
@Provider may declare dispose(), a plugin may call api.onShutdown(fn), and an
application that wants neither passes createApp({ hooks: [{ onShutdown }] }).
Shipping only the plugin half would have frozen the public API around the less
common case: the thing that holds a database connection is a provider.

Callbacks take no arguments. Whatever needs closing is already in the closure
that registered it, so nothing crosses a scope and the registry needs no
container, app reference or transport. That is what keeps this a registry
rather than a second event bus — Bus.on is synchronous and emit swallows
failures on purpose, and a teardown needs the opposite of both.

Provider dispose() is registered as the provider boots rather than as it is
collected, so reverse-registration is reverse-topological order for free: a
cache that needs db closes before the db it is holding, with no second sort to
keep in step. It registers inside the try, so a provider that failed to boot is
never disposed — nothing it might close was ever opened.

Teardown runs after the drain, because an in-flight request may still be using
what a teardown is about to close, and inside the same timeoutMs, because that
number is a promise about when close() returns. teardownTimeoutMs reserves a
slice of that budget rather than extending it, and is rejected at boot rather
than clamped.

Node, Deno and Bun reach it through the close() each runtime actually uses.
app.close() returns at its no-server guard everywhere but Node, so the Deno and
Bun adapters chain it after their own drain — and app.close() now runs teardown
on that path too, since an app served through app.fetch still booted providers
that opened things. The registry drains once, so both entry points are safe.

Edge gets a doc comment and nothing else. workerd has no shutdown to intercept;
a best-effort call on an event that does not exist would be worse than saying so.

Recorded in mountPlugin's comment while widening it: "isolation is structural"
is a guarantee about the registration surface, not about the request context. A
plugin's step already receives the live context and can overwrite keys in it.
Pre-existing, unrelated, and now written where the next reader will look.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:37:31 -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 df460f01dd feat(observability): an injectable logger, and a lint rule that keeps core off console
Task 4. createApp({ logger }) accepts any Logger; the default writes structured
JSON, or a readable line on a TTY, decided once at construction rather than per
record. It writes through console, which is what lets core have a logging
contract while reflect-metadata stays the only runtime dependency.

Four levels, because four have callers. Core's diagnostics were all warn — every
one of the eight console.warn calls — and request logging adds info and error.
No trace, no fatal: a level nothing emits is a decision handed to the user for
no reason.

Registered rather than declared as a provider. Provider boot failures are
reported while the graph is still resolving and shutdown warnings after it is
gone, so a logger that lives in the graph cannot cover either end. It is also
registered as a builtin provider, so @needs('logger') reaches the same object —
one instance, two access paths — and exposed on App so serveDeno/serveBun report
through the application's logger instead of past it.

The [green-tea] prefix moves out of the prose into a `name` field: an aggregator
filters on a field and cannot filter on a substring of a sentence. Context that
was interpolated into messages is now structured alongside them.

#10 asks that nothing in core call console directly. That is now a lint rule
scoped to src/ rather than a grep somebody has to remember, with src/logger.ts
exempted because being the console sink is its entire job. Verified it fails on
a planted console.log.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:51:33 -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 085eb9a67d fix(app): arm the shutdown timer before finish(), and make the deadline an app option
Closes #20. finish() called clearTimeout(timer) from above the timer's own
declaration. It worked because server.close(cb) always defers, so the
assignment won the race — correct by timing, and a ReferenceError waiting in
the shutdown path for whoever added a synchronous call site.

The issue proposed hoisting a `let timer`, but prefer-const rejects that and
is right to. Swapping the two blocks fixes it without a suppression and lands
somewhere better: the surviving forward reference is the timer callback
reaching finish(), and setTimeout not firing synchronously is the event loop
rather than a library's current behaviour.

Closes #19. The 10s deadline is now settable via createApp({ shutdownTimeoutMs }),
with the per-call close({ timeoutMs }) still winning. close() is usually
reached from a signal handler, a test helper or a shutdown hook you do not
own, where passing it per call is not available. Nothing changes for anyone
passing neither. The precedence test uses a 30s app-level default, so it can
only pass if the per-call value took priority.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:03:09 -05:00
chrnx 1c5a908fb9 chore(types): name the decorator shapes so JSR sees no slow types
deno publish --dry-run reported 17 slow types across metadata.ts and
params.ts: two factories with inferred return types, and the fifteen exported
decorators built from them. Naming RouteDecorator and ArgDecorator fixes all
seventeen, since annotating each factory resolves its constants with it.

Fixed rather than waived with --allow-slow-types. That flag degrades the
generated declarations and makes type checking 1.5-2x slower for consumers,
which is a strange thing to ship in the framework whose central claim is type
safety. The two names are public API and worth having on their own: a caller
can now give a decorator of either shape a name.

The factories also lost their inline parameter types, which the declared
return type now supplies.

deno.json gains the JSR manifest. Exports mirror npm's four entry points on
purpose — a docs example importing @green-tea/core/bun has to work whichever
registry the reader installed from. Dry run is clean with no flags; claiming
the @green-tea scope on jsr.io is the remaining step.

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:45:47 -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
ServeurGoat 3dcf784159 fix: add timeout to app.close()
Signed-off-by: YxnnXriel <yannariel13@gmail.com>
2026-08-12 13:33:10 -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 1db4e01e40 fix(deno): snapshot metadata before websocket upgrade
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:18:40 -05:00
chrnx 74f09d2e0b docs: document router completeness for beta
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:13:59 -05:00
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 63be0ef8f7 feat(router): expose HEAD and OPTIONS decorators
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:40:02 -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 642ef109b2 feat(app): warn at boot when a route's dependency chain is unusually deep
A route whose need-closure resolves to more than 20 steps is almost always a modeling smell -- a step doing too much, or work that belongs in a provider. Per-request cost is linear, so this is a design nudge, not a perf guard (and a warning, not an error).

Tunable and silenceable via createApp({ warnGraphDepth }): a number sets the threshold, false quiets it. Default 20.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 16:25:31 -05:00
chrnx 4081106813 perf(pipeline): merge step output in place to drop the O(n^2) context copy
runSteps rebuilt the whole request context every step with { ...context, ...output }, so an N-step route paid 1+2+...+N = O(N^2) property copies plus N throwaway objects. At 100 chained steps that measured ~250us/req vs ~100us after the fix (2.5x throughput); per-step cost drops from superlinear to a flat ~0.5us/step.

Mutate one accumulator in place with Object.assign -- O(N). The returned context is now the same object every step observes. Adds a regression guard that fails if a per-step copy is reintroduced; full suite green (322 tests).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 15:50:59 -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 9886e53747 feat(app): add app.ready() so introspection works on any app
inspect()/graph()/explain() are synchronous, but a mesh graph is not knowable
until its teapots have been asked, so on a mesh app they threw and the caller had
no way to fix it. Code holding an `App` could not tell which kind it had — the
Liskov complaint from the audit, and the last of it: fetch/upgrade stopped
throwing when the boot moved into the gate.

app.ready() resolves the graph and returns. On a mesh app it connects the
teapots; on every other app it is a no-op. So one shape works for both:

    await app.ready();
    app.graph();

which is what actually restores substitutability — a uniform protocol, not a type
that describes the asymmetry.

Deliberately not a full boot: it does not run provider factories. Resolving the
graph and being ready to serve are different things, and a devtool drawing a
diagram should not open your database connections. Serving boots them too and
shares the same memoized step, so ready() then fetch() resolves the graph once.

The guards stay — sync code cannot await network I/O — but the message names the
fix instead of describing the trap.

createApp hit 26 on the complexity gate with ready() added. Both boot stages had
their own copy of the same memoisation, so it collapses into one `once` helper
used by both, which is a smaller createApp than before this change.

Refs .specs/2026-07-15-green-tea-solid-audit (App/Mesh LSP)

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:00:14 -05:00
chrnx 34dbb32b2c docs(mesh): warn on shadowed remote routes, and tell the truth about mesh
Local routes are merged ahead of remote ones, so a local twin wins. That
precedence is worth keeping — your own code beating an imported one is how you
override a teapot — but it was an accident of [...local, ...remote] ordering with
nothing said, so a shadowed export looked like a broken teapot from the outside.
Warn, name the teapot, and leave the call to the developer.

The docs had gone stale in the way that started all of this. runtimes.md claimed
four times that mesh is Node-only; the mesh guide said finalization is deferred to
listen(); the changelog said "WebSocket and mesh remain Node-only". All false now.

The mesh guide gains what was enforced but never written down — which is how the
listen() trap got made in the first place, when the previous plan's "document it"
never landed:
- runs on Node/Deno/Bun, teapot and teacup, any combination; not on edge, and why
- no listen() required: the graph boots on first use
- buffered routes only, and why streams cannot cross an RPC hop
- one teapot per route, local-over-remote precedence, and the protocol version

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 9

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:20:55 -05:00
chrnx 033af2d1fc fix(mesh): fail the boot when two teapots export the same route
Duplicate scope tokens already threw in setRunner, but duplicate routes did not:
both were pushed into remoteRoutes, and matchRoute keeps the first of two
identical patterns (moreSpecific returns 0, not > 0). The second teapot's route
was silently dead. Same collision, two behaviours — one loud, one mute.

Fail the boot instead, naming the route and both teapots, since which pair
clashed is the thing an operator needs. The message says load balancing is not
implemented *yet*: it is a not-yet, not an impossibility.

Throwing now also keeps the door open. "First teapot wins" is a semantic callers
could come to rely on, so shipping it would make balancing a breaking change
later. An error cannot be relied on — turning it into a strategy stays additive.

Scopes keep failing rather than balancing, and should: an app-scope provider is
memoised, so "balancing" a cached value means nothing.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:04:57 -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 db9a7712af feat(mesh): boot the mesh graph from the app boot gate, not listen()
Only listen() spliced remote scopes and finalized the graph, and listen() builds
a Node http.Server. Deno/Bun/edge serve through app.fetch and can never call it,
so mesh was Node-only by construction: fetch() threw "unavailable before
listen()" forever on those runtimes, telling operators to call something they
had no way to call. buildAppFetch also hardcoded remoteRoutes to [], so even past
the guard it would not have served a remote route.

Move splice+finalize into the memoized boot gate that fetch, upgrade and listen
already share, ahead of the providers — remote nodes must join before the topo
sort. Await it before building the route table rather than after, since for a
mesh app the table is not knowable until the splice has run. listen() keeps
working by awaiting the same gate; the memoization means a fetch followed by a
listen boots once, and concurrent first requests splice once.

The fetch/upgrade guards are gone rather than reworded: they are now unreachable.

inspect()/graph()/explain() keep theirs — they are synchronous and cannot await
network I/O — but their message no longer claims listen() is the only way in.

test/fetch.test.ts asserted the old contract (fetch throws until listen), i.e.
the trap itself; it now pins that a mesh app serves without listen() and that
listen() afterwards does not re-run provider factories.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 5

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:04:49 -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 87772868ab refactor(mesh): import node:crypto explicitly in the teapot
safeEqual guards the mesh shared secret and reached for Buffer + timingSafeEqual
through a bare 'crypto' specifier, leaving resolution to Deno/Bun node-compat
heuristics. Name the builtin explicitly — the authentication path should not
depend on which compat layer happens to answer.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 2

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:53:07 -05:00
chrnx dd0ea91a1b feat(mesh): version the wire protocol and validate frame shapes
Cross-runtime mesh means peers are separate processes on separate deploy
cadences, so the frame union is a contract between green-tea versions rather
than an internal detail. There was no version field, and decode validated only
that `type` was a known tag before casting `parsed as Frame` — every other
field was trusted, so a skewed or malformed peer failed somewhere downstream
instead of at the boundary.

Add MESH_PROTOCOL_VERSION to the hello/manifest frames. Both ends refuse a
mismatch: the teapot checks the version *before* the secret, since a skewed
peer is not an auth failure and "wrong secret" would send its operator hunting
the wrong bug.

Validate fields per frame type via a Record keyed on the type tag, so a new
frame type must add a row. The lookup uses an own-property check: `type` is
peer-controlled and a bare lookup would resolve SHAPE['constructor'] up the
prototype chain to a truthy non-check.

This is a breaking wire change, done now because it is free exactly once —
mesh is alpha behind experimental:true and has no deployed peers. Adding a
version later would break every peer already in the field.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 1

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:47:35 -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 922700674c fix(bus): emit step events for ws and mesh routes
Steps were executed by three separate hand-rolled loops: runPipeline (HTTP),
buildWsRoutes (ws) and resolveScope (mesh). Only the HTTP one emitted
request:step:enter/leave, so a logging plugin silently observed nothing on ws
routes — a gap in a documented public API, not just redundancy.

Route every transport through a single runSteps() so observability is uniform
by construction rather than by remembering to copy the emit calls.

Also fixes the plugins guide, which documented a request:step:exit event that
has never existed (the bus emits request:step:leave).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx f613a6427b feat(pipeline): enforce return contract by declared transport
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 15:55:22 -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 b8ebb9d04b feat(views): @Html string/file/template modes with boot validation
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:36:40 -05:00
chrnx e1a2c3253b feat(views): @Html decorator and metadata
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:31:12 -05:00
chrnx da5cc936a3 feat(views): built-in template engine + content-type map
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:26:57 -05:00
chrnx df13a62d93 fix(app): serve /__graph__ and /__openapi__ over app.fetch (dev tools on all runtimes)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 00:10:54 -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