Commit Graph
149 Commits
Author SHA1 Message Date
chrnx 7d39aebfab fix(stream): report a stream's lifecycle on every adapter, not only Node
CI / runtimes (bun) (pull_request) Successful in 15s
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
`pipeStream` emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame.
`asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and
`app.fetch()` on Node — emitted nothing and called `controller.error(err)`.

Both halves of that were silent. A consumer counting `stream:error` saw zero on three of
the four runtimes while the streams were failing normally, and the client got a truncated
body with no explanation, which from the outside is indistinguishable from a clean end of
stream. The observability guide documents these three events without qualification; on
three runtimes they did not exist.

The error path now frames rather than breaks. Enqueue `encodeError`'s frame, then close
cleanly — the Node behaviour, and the better one: an SSE consumer that received an `error`
event knows what happened, where a transport-level failure looks exactly like the
connection dropping. `controller.error` is kept for an encoder with no error frame to
offer, because then breaking the stream is the only signal left.

`stream:close` is latched. A `cancel` can land after the body already ended, and the three
exits — done, error, cancel — must not each emit their own.

The test drives both adapters from one route table rather than asserting them in separate
blocks, since a table that describes one and then the other is how the two drifted in the
first place. Verified non-vacuous: reverting `src/http/web.ts` fails all four fetch rows
and leaves the three Node ones green, which is the split that says the test is measuring
the adapter and not the framework.

The `sse()` injection test from the previous commit went back to `app.fetch`. It had been
written against `listen()` only because the fetch path swallowed the error — that was a
workaround for this bug, and it is no longer needed.

Closes #83

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:52:42 -05:00
chrnx 7b3fe57590 feat(sse): emit id:, so an EventSource reconnect has something to resume from
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 30s
`sseEncoder` wrote one field. With no `id:` on the wire the browser had nothing to put in
`Last-Event-ID`, so every automatic reconnect rebuilt the route's iterable from its start
and lost the gap in silence — a healthy-looking stream that had simply skipped events.

Half of this already worked and it was worth checking before designing anything: the
request envelope has always carried every header, so a handler could already read
`@header('last-event-id')`. It just always arrived empty, because we never gave the
browser an id to send.

`sse(data, { id, event, retry })` tags a stream item; `sseEncoder` writes the fields ahead
of `data:`. An app that never calls it sees byte-identical output. `event:` and `retry:`
come along because the envelope carries them for free and neither was reachable before.

**green-tea stores nothing.** No buffer, no retention window, no replay. The framework
carries the marker in both directions and the handler decides what the gap means, because
only the source knows: a paged log re-reads from an offset, a live sensor has no past
worth delivering. Framework-managed replay would need a stream identity that survives a
disconnect — which does not exist, since every request builds a fresh iterable — plus a
retention policy no default can get right and an in-process buffer that breaks the moment
there are two instances. This commit is also the prerequisite for any of that: whatever
replay might land later keys on these ids.

An id with a newline is rejected, not stripped. An id is exactly the value most likely to
be derived from a request — a cursor, a page token — and the SSE format is line-based, so
one newline lets a caller append arbitrary fields to somebody else's stream. Stripping
would resume from the wrong place invisibly, which is the failure this whole feature
exists to close, so it throws where the stream can report it.

`ndjsonEncoder` unwraps the payload and drops the fields: a `negotiate` route yields the
same items to both encoders, and NDJSON has no frame to carry them and no resumption
protocol to use them.

Verified non-vacuous: reverting just the two `encode` functions fails the six framing and
round-trip assertions and leaves the validation ones passing, which is the right split.

Closes #46

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:47:14 -05:00
chrnx ccd329d12b perf(boot): run independent providers concurrently
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
`bootProviders` was a `for...of` with an `await` inside, so three providers that share
nothing took the sum of their latencies rather than the longest one. Measured on the
issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after.

The graph already knew. `topoSort` proves which nodes cannot constrain each other and
then throws that away by returning a flat list; `topoLevels` groups the sorted list back
into dependency levels in one forward pass, and boot runs a level with `Promise.all`.
Nothing else about the ordering changes: level N is fully registered and warmed before
level N+1 starts, which is the same guarantee the sequential walk gave.

This is the second thing users get for declaring `needs`/`provides` instead of ordering
`app.use` calls by hand. Pruning was the first. An Express app cannot parallelize its
middleware because nothing declares what is independent — we have that declaration and
were not spending it.

Three things had to survive the change, and each has a test:

- **Teardown stays deterministic.** Registration follows level order, not completion
  order, so the registry running in reverse still gives dependants teardown before their
  dependencies. Following whichever provider settled first would have turned that from a
  guarantee into luck.
- **A failed sibling does not strand the level.** `bootProvider` returns an outcome
  instead of rejecting, and successful teardowns are registered before any failure is
  raised — so a boot aborted by a required provider still leaves whatever its siblings
  opened closeable. Previously they had not started at all; now they may be in flight.
- **A provider that threw gets no teardown**, unchanged: it never provided anything, and
  `dispose()` on a half-constructed one is how a teardown finds a null connection.

Behaviour visible to a bus consumer: `boot:provider:start` no longer strictly alternates
with `:ok`. A level emits its starts together, then its results. That is the truth about
what is happening rather than a change in what is reported.

Verified non-vacuous: reverting `src/` fails the overlap assertion and all five
`topoLevels` cases, and puts the benchmark back at 616ms.

Closes #71

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:32:17 -05:00
chrnx 1c4f3fb8cb perf(http): skip the request-budget bookkeeping when no budget is set
Every request registered a `close` listener and set an acquire flag, including in the
apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true`
unconditionally when the limit is unset and `release()` early-returns for the same reason,
so both the closure and the EventEmitter registration were pure overhead: a per-request
cost, on the hot path, for a feature that is off.

The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the
gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not
counting" alike, which is exactly why a caller reading only the result pays either way.

With a budget configured nothing changes: the listener is what releases a slot when a
client disconnects mid-handler, and it comes back. The guard is about the unset case, not
about dropping the feature, and the test asserts both halves so a fix for one cannot
quietly become a regression in the other.

Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts.

Closes #74.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:01:52 -05:00
chrnx 1e76921d49 feat(di): a read-only events token, and framework names nobody can take
Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:57:47 -05:00
chrnx c00f714aa8 feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.

The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.

The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.

`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.

Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.

Closes #65.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:37:41 -05:00
chrnx 5294e62a5a fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.

This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.

It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.

All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.

Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.

`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.

Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.

Closes #80.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:35:03 -05:00
chrnx 3930804fb3 feat(bus): give request:failed a status, and write down the three-event overlap
One request that throws emits three events, and nothing said which of them to count. The
obvious first implementation counts the failure twice — once from `request:failed` and
once from the `request:end` that follows it, under whatever status it invents for the one
that had none. `route:unmatched` overlaps the same way, so a 404 is two events and one
outcome. Both mistakes are silent: the metrics simply lie.

The division of labour is now stated on `EventPayload`, where a consumer reads it:
`request:end` is terminal, universal and carries the status the client received, so it is
the request counter; `request:failed` means *handler code threw*, which no status can
express on its own since a rendered 422 is also a throw; `route:unmatched` means no route
ran. The last two are additional, not alternatives.

`request:failed` also carries a `status` now, so an error counter can break down by
status without joining back through `requestId` for something the emitter already had.

Getting it required moving the emission after the render rather than before, and the two
reasons are worth keeping: `onError` may turn any throw into any status, so deriving one
from the error would be a guess a custom renderer makes wrong — and the emission sits in
`finally`, so a renderer that *throws* cannot swallow the event. That case is the only one
where the event has no status, and the field's doc says so rather than leaving a reader to
find out.

Closes #64.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:26:00 -05:00
chrnx 5d8363d225 feat(bus): guarantee that every request:end has a request:start
`request:start` had one emitter and `request:end` had three, so the pairing every
consumer would reasonably assume held by accident rather than by promise. The
`maxConcurrentRequests` merge added the first terminal path that breaks it: a shed
request emits `request:end` and nothing before it, because it never reaches `handle()`.

Both shed paths now emit the pair, through one shared `emitShedPair` rather than two
copies — the guarantee lives in one place, and the two adapters already had a duplicate
of this block between them.

## Why the pair rather than documenting `request:end` as standalone

Both were defensible and the alternative was seriously considered. It loses on one
concrete case: the obvious in-flight gauge.

    bus.on('request:start', () => inFlight++);
    bus.on('request:end',   () => inFlight--);

Without the guarantee that drifts negative the moment a server sheds — under load, which
is exactly when an operator is reading it, and it fails by producing a plausible wrong
number rather than an error. Documenting "do not do that" asks every consumer to read
the warning; guaranteeing the pair makes the obvious code correct.

Emitting a `start` for a shed request is not a fabrication, which was the objection worth
answering: the request *did* arrive. The gate refused it before the router, and
`request:start` says a request arrived, not that it routed.

The cost of the guarantee is that it binds every future emitter, and that is real. It is
paid down by `test/lifecycle-pairing.test.ts`, which enumerates every response shape —
200, 404, 500, 413, 204 preflight, and 503 on both adapters — and asserts the pair and
the shared `requestId`. The constraint is now something CI enforces rather than something
a contributor has to remember. Verified non-vacuous: dropping the `request:start`
emission fails the two shed rows and nothing else.

Also writes down, next to `LifecycleEvent` where a consumer reads it, the half of this
that is not new: `request:end` is terminal and universal and is the one to count;
`request:failed` and `route:unmatched` describe the same request and are additional.

Closes #73.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:21:34 -05:00
chrnx b8b3548f15 perf(cors): resolve the request's headers once, not two or three times
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.

`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.

Measured against the built `dist/`, same script that produced the numbers in the issue:

    GET with Origin      2x -> 1x
    OPTIONS preflight    3x -> 1x
    buildFetch, Origin   2x -> 1x
    GET without Origin   0x -> 0x   (never reached the predicate; unchanged)

The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.

Closes #77.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:27:32 -05:00
chrnx 855e044d2a fix(types): export the extension-point types, not just the extension points
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
`Transformer` was exported and `TransformerFn` was not, so a custom transformer could
be attached but not typed. The workaround is to borrow the type off a value —
`const text: typeof JsonTransformer = ...` — which works and reads like a trick,
because it is one. `ErrorRenderer` and `StreamEncoder`, the two neighbouring extension
points, were both already exported; this one was an oversight rather than a decision.

Checking the rest of the barrel for the same shape turned up four more. A plugin split
into named functions rather than one inline arrow cannot annotate what it receives:
`Plugin` types the arrow, and `PluginApi`, `ScopeApi` and `ScopeNode` — the chain
reached through `api.scope.add`, which is how a plugin contributes to the graph — were
all unreachable. So was `Hooks`, which makes `createApp({ hooks })` typeable only
inline, and `TeardownFn`, the shape every one of those three doors takes.

Types only. Nothing at runtime moves, and no existing export changes.

Covered by a type test that fails to compile if any of them leaves the barrel again,
including the two that were already there — the failure mode this fixes is a barrel
edit nobody notices until a user writes the annotation.

Closes #66.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:15:35 -05:00
chrnx e5d5fb801a feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 30s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
The README promised shutdown was *"an extension point, not a SIGTERM handler you
write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the
*content* of teardown, but nothing called `close()`, so every application still wrote
the handler — and wrote it three times, because the spelling is per runtime. Forget it
and the container is SIGKILLed after its grace period, every `dispose()` the registry
so carefully ordered never runs, and nothing reports it.

`createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit.

Off by default, and that is the design rather than caution: a library that installs
process-wide handlers behind your back is worse than one that installs none, because
when the process exits is the application's call. Both halves are now supported and
documented — keep the handler, or hand it over. What is not optional either way is
that *something* calls `close()`, and the README now says so instead of implying the
framework already had it covered.

Declared once on `createApp`, wired per runtime by whichever boot call runs:
`listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their*
server to `app.handleSignals`, which returns a close that also unregisters. On Deno
that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener`
holds the process open, so an app that closed itself would otherwise hang.

Unregistering first also means a *second* signal falls through to the platform default
and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a
teardown that is stuck, and swallowing it for the length of a 10s budget would read as
a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there.

Tested against real processes, because a handler whose job is to exit its own process
cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal
escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`,
which is the API that actually differs. Bun shares Node's `process` path.

Closes #70.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:09:56 -05:00
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 0fad12688d ci(release): publish the release notes, not just the tag
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
The repository had two tags and no releases, so the only way to find out what
a version changed was to open CHANGELOG.md and scroll to the right heading.
The release page is where people who do not read changelogs look, and a
repository with tags and no releases reads as abandoned.

Notes come from CHANGELOG.md rather than from the commit range. The section
was written for humans and already exists by the time a tag is cut; generated
notes would restate merge subjects nobody chose. `scripts/changelog-section.mjs`
extracts one version's section and makes its relative links absolute against
the tag — a release body resolves them against the release page, not the
repository, so `./BENCHMARKS.md` would have 404'd.

That script is a parser writing text that cannot be corrected quietly once it
is published, so its boundaries are pinned by a test rather than checked by
eye at release time. Both of the bugs it caught while being written are in
there: a section swallowing the `[label]: url` block that follows the oldest
version, and a relative link surviving into a body.

The step is idempotent like the publishes before it, so a re-run finishes what
is left instead of stopping here, and `--verify-tag` keeps it from inventing a
tag — it attaches to the one that triggered the run and cannot move it. A
prerelease is marked as one, which is what keeps the "Latest" badge off a beta.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:31:05 -05:00
chrnx 46342a0aa2 fix(mesh): refuse to export a value the wire cannot carry, instead of delivering an empty object
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
Exporting a provider whose value was a connection pool produced HTTP 200 and
 on the other side. JSON keeps the shape and discards everything else, so
what arrived was an object that passed every truthiness check and had no
methods — and the failure surfaced as `db.query is not a function` at a call
site arbitrarily far from the export that caused it. Nothing warned, at either
end, at any point.

The teapot now checks before sending, which is the only place the evidence
still exists: past encode() a pool and an empty object are the same bytes.

An allowlist rather than a denylist. Date is refused too — it would arrive as
a string rather than the declared type, which is the same silent difference
wearing a smaller costume. Bounded by a scan budget so a large legitimate
payload is never turned into an error by the cost of checking it.

The constraint this makes visible was never written down anywhere: a mesh
export carries data, never behaviour. Export what the handle produces rather
than the handle. That limit is what makes an 'executable provider' (#50) the
missing shape rather than a nicety.

442 vitest / 12 Deno / 7 Bun / edge / JSR dry run. All 5 new tests verified to
fail against the old code.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 12:35:48 -05:00
chrnx 1975a7c03f feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 16m11s
A teapot that is thirty seconds behind and a teapot that does not exist look
identical for the first thirty seconds, and only one of them should stop a
deploy. bootTimeoutMs is that grace: retries with backoff until it passes.

It still fails after that, deliberately. A provider the graph depends on is
not optional, and booting without it would only move the failure to the first
request, where it is a caller's 503 rather than the deploy's error.

The full battery caught what the first cut got wrong: a bad secret was being
retried. That is not a transient failure — it is the teapot's decision, and it
will be the same decision in thirty seconds, so retrying only spends the
deploy's patience to arrive at the identical error. Refusals now fail at once.

Telling them apart without threading close codes through the neutral socket
contract of four runtimes: a peer that accepted the connection and then hung
up before answering rejected us on purpose; one that never accepted it may
simply not be listening yet. That is exactly the distinction needed here.

Retries are logged and emitted as mesh:boot:retry, kept separate from
mesh:disconnect — that one is a link that was up and went away, this one never
came up, and a deploy watching for trouble wants to tell those apart.

437 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 11:28:44 -05:00
chrnx f2cb411eac feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 18s
The observability release gave every request an id and lost it at the process
boundary — in the one place a distributed trace is the entire point. The RPC
envelope now carries requestId, traceId and url, and the teapot adopts them
instead of opening its own investigation.

Both fields are optional on the wire, so the protocol version does not move.
That decision needed a rule rather than a judgement call, so the rule is now
written beside the constant: bump when an old peer would misparse or misbehave
silently, not when work happened. Bumping per change would make the number
mean the opposite of what it is for.

Three things found while in here:

- mesh:rpc:error emitted the per-link counter where every other emitter puts a
  name, so the two sides of one failure could not be matched up.
- The teapot had no handshake deadline, so an unauthenticated peer could hold
  a socket by saying nothing, and no frame size cap, so it could make the
  process JSON.parse up to whatever the socket layer allowed — 100 MiB with
  the ws defaults, before authenticating.
- The remote-route envelope was cast from the internal request object, putting
  ip and protocol on the wire as fields the protocol never declared.

The cleartext warning is a warning and not a refusal on purpose: a private
network already doing mutual TLS is legitimate, and green-tea cannot tell it
apart from an exposed one.

4 of the 8 new tests verified to fail against the old code; the rest are the
negative cases, which should pass both before and after. The Deno test drives
the teapot's frame loop with a raw client, because server-side close codes are
where these runtimes have already differed once.

431 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 11:15:54 -05:00
chrnx 6ffbad9825 fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
A dropped link stayed dead for the life of the process. Every RPC answered
503 until the teacup restarted, so deploying a teapot forced a restart of
every teacup depending on it and boot order became load-bearing — a worse
operational property than any gap the docs actually listed.

The Link now outlives any single socket, because the graph captured its rpc
closure at boot and a reconnect that produced a new Link would leave the graph
pointing at the dead one. Backoff doubles from 500ms to 30s with full jitter,
so teacups that went down together do not return in lockstep.

A returning teapot whose manifest no longer exports what the graph was
validated against is refused, not adopted: that graph is already serving, and
a token cannot be validated away after the fact. The link keeps retrying,
since a partial deploy may still restore it, and logs once per distinct
manifest rather than once per attempt. Refusal ships as a named policy
(onManifestChange: 'refuse') so hot reconciliation can arrive later as an
addition rather than as a change of what the default means — these are
separate processes on separate deploy cadences.

close() is terminal. closeLinks runs on shutdown, and a link that reconnected
after the application hung up would leave a process that cannot exit.

Also closes the documented gap where an app-scope export outlived its teapot
with a stale value: a successful reconnect re-registers those bindings, so the
next resolve re-runs the RPC. That invalidation is a named function rather
than inline, because it is the seam a future 'reconcile' reuses.

Tested on all three runtimes rather than on Node alone — Node's ws package,
Deno's global WebSocket and Bun's server-level socket handler are three
implementations, and swapping a socket under a live graph is where they stop
agreeing. 7 of the 9 new Node tests were verified to fail against the old
code; the 2 that pass are the ones that should, since the old code never
reconnected at all.

Mesh stays alpha.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 10:53:24 -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 62d0b7aa3a test: execute the circuit-breaker recipe the docs publish
The recipe closing #13 lives in the documentation repository, which imports
nothing from here — so nothing fails when the page and the framework drift
apart. That is the seam Phase 4 opened, and a worked example that quietly
stops working is the worst version of it: it is the page a reader trusts most,
because it looks like code that ran.

This executes the three claims the page rests on rather than asserting them in
prose. That breaker state survives across requests, which is the entire reason
the recipe uses a provider and not a step. That the window re-opens after it
elapses. And that a failed trial in half-open re-opens immediately instead of
making a recovering upstream earn the full threshold again.

Beyond the file list Phase 5 asked for, which named only the guide page. Kept
because it is small and it turns Task 4.4's written rule into something that
fails, for one page at least.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:44:49 -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 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 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 f96c2ad401 test: pin the JSR manifest to package.json
npm and JSR publish from the same tag but read their identity from different
files. Bump package.json alone and that tag ships one version to npm and the
previous one to JSR, with nothing failing — the drift the deno.json manifest
introduced, closed where the other publication-metadata pins already live.

Also pins the entry points to npm's, so a docs example importing
@green-tea/core/bun keeps working whichever registry the reader installed from.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:47: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
chrnx 9d95260706 chore(test): nest the close({ timeoutMs }) case inside its describe block
CI / dco (push) Has been skipped
CI / dco (pull_request) Successful in 4s
CI / build (push) Successful in 35s
CI / build (pull_request) Successful in 34s
The test landed one line below the closing brace of describe('graceful
shutdown'), so it ran at the top level instead of under the block it
belongs to. Placement only; the assertions are untouched.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-12 13:34:07 -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
chrnx f200045fd7 chore: put a project address in the package metadata
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 35s
author had no email and bugs had no address, so the only contact npm could show for a
published package was a GitHub issues URL. bugs.email is a field npm actually reads and
npm bugs surfaces, which makes it the right home for the catch-all.

No security address here on purpose: npm has no field for one, an invented key is read by
nothing, and the standard location is /.well-known/security.txt on the domain root, which
this repo does not serve.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:32:32 -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 9398a5a2df fix(ci): keep Verdaccio staging mutable
CI / build (pull_request) Successful in 34s
Replace an existing prerelease before publishing the refreshed candidate. Verdaccio remains mutable for validation while npmjs release versions stay immutable.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:42:39 -05:00
chrnx 29aafde84c fix(ci): make Verdaccio staging idempotent
CI / build (pull_request) Successful in 32s
Stage only release branches and preserve immutable versions. Repeated identical candidates now exit successfully, while content changes under an existing version require a prerelease bump.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:56 -05:00
chrnx dbb996dd4c fix(package): declare npm publication metadata
Link the package to its public source, issue tracker, and documentation so npm Trusted Publishing can validate provenance and consumers receive canonical project links.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:47 -05:00
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 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