Author SHA1 Message Date
chrnx 85b6c703bb Merge pull request 'A tag stages before it can publish' (#91) from ci/tag-staging-and-promotion into develop
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (push) Successful in 22s
CI / runtimes (edge) (push) Successful in 12s
Stage → Verdaccio / publish-stg (push) Successful in 25s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
Promote → GitHub / push-github (push) Successful in 8s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 29s
Release → npmjs / publish-prod (push) Has been skipped
Reviewed-on: #91
2026-09-04 13:23:20 +00:00
chrnx dfe71102ca docs(changelog): date the section for the day the tag actually ships
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 14s
The heading was written for 2026-09-02, the day the cut was planned, then dated 2026-09-03
when it was closed. Neither day shipped anything, and the workflow split that has to land
before the tag moved it once more.

AGENTS.md is explicit that a dated heading is a receipt rather than a plan, and that this
exact drift already happened once on beta.1 — a section claiming a release that did not
exist, with a day of further work accumulating underneath it. Correcting the date is
cheaper than being the second instance of the thing the guidance warns about.

Today is the day the tag is created, so the receipt says today.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-04 08:10:25 -05:00
chrnx cd4a9f65f6 ci(release): stage a tag on Gitea before it can reach production
A `v*` tag did two things at once: `promote.yml` mirrored it to GitHub, and GitHub's
`release.yml` published it to npm and JSR. Creating the tag *was* the release, so the only
place to catch a bad one was a registry where npm gives 72 hours to unpublish and JSR gives
nothing — a version number spent on a mistake is spent for good.

The tag now means something different on each forge. On Gitea it triggers `stage.yml`,
which runs the real publish path — same `prepublishOnly` gate, same tarball, same commit —
against the internal Verdaccio, where a version can be overwritten. On GitHub it still
publishes for real. Nothing carries the tag between them; that push is a decision made
after reading the staging run.

`--tags` comes off the branch push in the same change, and it is the part that mattered
most. Removing the tag trigger alone would have left any tag in the runner's clone riding
along with the next promotion of `main` — a production publish as a side effect of a
merge, which is the exact failure the split is meant to prevent.

The refusal to stage a stable version is left as it is, with a note. It will first bite at
the release most worth staging, and the fix there is a suffixed staging version rather than
dropping a guard that keeps a stable number from mutating under an internal consumer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-04 08:10:17 -05:00
chrnx aa15862f3b Merge pull request 'Cut 26.9.0-beta.1' (#89) from chore/close-changelog-26.9.0-beta.1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (pull_request) Successful in 7s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
Reviewed-on: #89
2026-09-04 12:33:44 +00:00
chrnx 0c099c7266 chore(release): cut 26.9.0-beta.1
CI / dco (pull_request) Successful in 6s
CI / runtimes (deno) (pull_request) Successful in 1m54s
CI / runtimes (edge) (pull_request) Successful in 29s
CI / build (pull_request) Successful in 13m16s
CI / runtimes (bun) (pull_request) Successful in 53s
`[Unreleased]` has been the heading since tier 3 closed, which was correct while entries
were still arriving. They stopped: the matcher entry was the last one, and everything the
section describes is merged and green. Holding the heading past that point only makes the
file describe work as unreleased that is about to ship.

`deno.json` moves in the same commit because `test/package-metadata.test.ts` pins the two
together — bumping `package.json` alone ships one version to npm and a different one to
JSR, and JSR versions are immutable. The release workflow reads the changelog section by
version, so a tag pushed against an `[Unreleased]` heading fails after the publishes have
already run.

Dated 2026-09-03, the day the cut happens, rather than the day it was planned for.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-03 23:55:47 -05:00
chrnx c472d4c0de Merge pull request 'changelog: record the matcher change' (#88) from docs/changelog-matcher into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 23s
CI / runtimes (edge) (push) Successful in 12s
2026-09-02 03:11:47 +00:00
chrnx f18aa9a42a docs(changelog): record the matcher change, which landed after the tier was written
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 29s
`[Unreleased]` was written when tier 3 closed and the route-ranking work came after it, so
a user-facing improvement with a measured number had no entry. That is the omission the
benchmark notes published in the same release are about — something measured that never
reached the file where anyone would read it — and cutting the beta without it would have
been a poor way to make the point.

Placed in Changed beside concurrent provider boot. Both are savings that appear only once
something grows, and reading them together says what neither says alone: what this release
improved is what happens when an application gets bigger.

The entry leads with what does not change, because "route ranking now happens somewhere
else" is the sort of sentence that makes a reader check whether their routes still resolve
the way they did. Equal specificity still keeps registration order; the ordering carries it
through a stable sort instead of through a scan.

The numbers are given per route-table size rather than as one figure. A single percentage
would be wrong at both ends — nothing at six routes, +14.9% at two hundred — and the shape
is the honest form of the claim.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 22:10:20 -05:00
chrnx 7ccb55d07a Merge pull request 'Route ranking at build time, and a benchmark that can measure a release' (#87) from perf/matcher-and-benchmarks into develop
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 31s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 18s
2026-09-02 03:07:37 +00:00
chrnx e61771077c docs(bench): refresh the tables and record what moved between releases
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
The tables were measured on 2026-07-07 at `fe1831a`, two releases ago. Re-measured at
`8c5855c` with the runtime matrix included, every row under 1.2% CV.

The headline is not in the cross-framework tables. green-tea sits within 2% of fastify on
`hello` and `param` and second only to `raw-http` on `validate` — but the same application
on Deno serves 153,408 req/s against Node's 90,976, and on Bun 131,674. Node's own `http`
module with no framework manages 119,357. The runtime-neutral boundary that costs on Node
is what makes those rows possible, and until this run nothing measured them.

The notes below the marker say what a table cannot. In order: the release gate — this
release is neutral against `26.8.0-beta.1` on every scenario but the CORS preflight, which
gains 2.7%; the interval against `26.7`, which is roughly −5% to −8% and is **not** a
regression, because July matched routes by splitting a string in one flat file and had no
constraints, no specificity, no correlation and one adapter; the figures recorded in the
code when each change landed, including one that reached 45% of a request before it was
fixed; and what is still unattributed, which is most of it.

That last part is the point. Three candidates were measured and none of them explain the
interval: `randomUUID` is 0.7% and lands within noise, replacing specificity ranking with
July's first-match-wins is noise, and the bundle versus the source is noise. A section that
explained everything would be a defence. This one says what was found and what was not.

The measurements were always there — `core.ts`, `bus.ts`, `pipeline.ts`, `headers.ts`,
`body.ts`, `router.ts` all carry them, with alternatives compared and rejected. They cite
different baselines, 4.4 µs to 10.19 µs, because each was taken against whatever a request
cost that day, so they cannot be added up. What was missing was never rigour. It was a
number per version against a fixed baseline, in the file where the question gets asked.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 21:26:27 -05:00
chrnx 9c78842684 test(bench): measure a release against the last one, and every runtime it claims
`BENCHMARKS.md` answered "how does this compare to fastify" and nothing answered "did the
last two months cost anything". Those are different questions and the second one is the
one a release has to pass, so it needed its own tool rather than a second reading of the
first one's table.

`npm run bench:compare` runs two worktrees of this repository against each other on one
box in one sitting, alternating which side goes first each round so drift lands on both
rather than on whichever ran second. It shares one `node_modules` and one byte-identical
server file, which holds everything except `src/` constant — and is only sound while
`package.json` has not moved between the revisions, which the header says out loud.

Three things it refuses to do quietly, each of which it did once before being taught not
to:

- A run whose connections all errored reports 0 req/s, and a median absorbs that without
  complaint. Non-2xx, errors and timeouts now fail the case, and so does a zero. Not on
  the warmup, which exists to absorb exactly the cold-start noise a fresh server produces.
- A range-overlap check flags a row as directional, and its own documentation says to
  treat that as "measure it again", never as a result. Three samples of two overlapping
  distributions separate by chance often enough to have produced a regression report that
  five rounds then erased.
- `cors.origins` invocations are counted rather than timed. The benchmark's predicate is a
  `Set` lookup, so calls saved are invisible in req/s — but the option takes a function so
  it can be a lookup, and there the same saving is a network round trip.

**The runtime servers finally run.** `bench/servers/green-tea-deno.ts` and `-bun.ts` were
written in July and referenced by nothing — not the runner, not a script, not CI. The
runner only knew how to launch Node, so both sat there looking like coverage the table did
not have. Launchers are per runtime now and they get their own section, kept out of the
cross-framework tables because a green-tea-on-Bun row beside fastify-on-Node reads as a
comparison nobody made.

`green-tea-node.ts` is new and loads `dist/` like its Deno and Bun counterparts. The
runtimes table exists to vary the runtime, and a Node row reading `src/` through tsx would
have varied the load form at the same time.

A route-table-width dimension, because every matcher cost scales with how many candidates
a request walks past and the tables here use six routes. Three separate matcher findings
measured as noise before this existed, which said nothing about them and everything about
the instrument.

Finally, `run.ts` preserves whatever sits below a marker instead of overwriting the file
whole. The tables answer what is true today; the notes below them carry which release moved
a number and what the move bought, and regenerating used to delete that silently.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 21:26:11 -05:00
chrnx 8c5855c59e perf(router): settle route ranking when the table is built, not per request
Route matching scanned every method-matching route on every request and ranked the
candidates as it went, calling `moreSpecific` — two `compilePattern` lookups each — per
candidate. Both the scan and the ranking scale with the size of the route table, and the
answer they compute cannot change between requests: the table is assembled once, after the
graph is prepared, and handed to the adapter unchanged.

So the ranking moves to where the table is built. Routes are compiled, bucketed by method
and sorted most-specific-first, and matching walks until the first match and returns it.
`sort` is stable, so patterns of equal specificity keep registration order — which is what
the old scan produced by refusing to replace its best on a tie.

Measured on a request to a parameterised route registered last, against the same tree
without these changes, medians of five and seven rounds:

      6 routes      no change (every row overlaps)
     50 routes      +3.3%, +3.5% across two runs
    200 routes      +14.9%, +12.0% — twelve rounds, not one crossing sample

The shape is the point rather than any single number: the saving is proportional to how
many candidates a request walks past, so it is invisible on a small table by construction.
That is also why it went unnoticed. The benchmark had no route-table-width dimension until
this commit added one, so every matcher change measured as noise no matter how real.

Two smaller savings on the same path. `decodeSegment` now skips `decodeURIComponent` when
the segment holds no `%`, the same gate `normalizeRequestPath` already applies to the whole
path for the same reason. And decoding memoizes per request rather than per candidate: a
scan reaching the same parameter position on several routes used to decode the same string
once per route, and position is all decoding depends on.

`allStatic` is deleted. It short-circuited the scan on an all-literal match, which sorting
subsumes — such a pattern now sorts first and wins by position.

The index is keyed by the identity of the route array, so it is built once and collected
with the table it describes. A table assembled fresh — mesh splicing a teapot's exports in
at boot — is a different array and gets its own index, so no caller has to invalidate
anything.

`matchRoute precedence` already covered the ordering this rewrite had to preserve, and it
passes unchanged. Two cases were missing and are added: that equal specificity keeps
registration order, which is the property the stable sort now carries, and that a parameter
decodes to the same value however many candidates the scan walks. Both pass against the
previous implementation too — they describe behaviour that already existed, which is what
makes them evidence the rewrite preserved it rather than evidence of the change.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 15:48:01 -05:00
chrnx e7b1c462e6 Merge pull request 'Tier 3 for the beta: what the graph earns you, and an event stream you can build on' (#82) from beta/tier-3 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 17s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 17:01:52 +00:00
chrnx a84960a46a docs(changelog): record the tier-3 work in Unreleased
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
Concurrent provider boot, `sse()` and the `id:` it writes, and the stream events that
three of the four runtimes never emitted.

#83 and #84 share one entry. They are two defects but one symptom — the stream events
were not usable — and a reader looking for "can I build a stream gauge on this" is served
better by one entry than by two bullets that both open with `stream:`.

The boot entry carries its two consequences rather than only its number, because "616ms
becomes 210ms" is not the part that can surprise someone: a required provider's
independent siblings now start, and `boot:provider:start` stops alternating with `:ok`.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:59:40 -05:00
chrnx 86a0d9c91b fix(observability): correlate stream events with the request that opened them
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
`src/http/core.ts` documented the design as "`stream:open`/`stream:close` already describe
the connection, and now carry the same `requestId`". They carried `{ name }` and nothing
else, on all three emitters, and `Bus.emit` forwards a payload verbatim — so there was
nowhere else it could have been arriving from. The comment described an intent that was
never carried out.

The split it describes is right: a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so ending the request span at the
handler's return keeps hour-long SSE connections out of the same latency distribution as
2ms replies. But the split only works if the two can be **joined**, and `requestId` is the
join key — it is what `EventPayload` defines itself as. Without it an exporter could not
say which request opened the connection still holding a slot, and `traceId`, carried
verbatim so an exporter can hand it to OTLP, never reached the longest-lived thing the
server does.

`route` comes along for a second reason. The contract this beta settled says label on
`route`, never on `name` — and `route` was absent from precisely the events a stream gauge
is built from, leaving a correct consumer with nothing to label. On a stream event `name`
is always the route pattern rather than the concrete path, so the two are the same value
here; both are emitted because the rule a consumer follows is written against `route`.

A WebSocket upgrade correlates itself. It is an HTTP request with headers like any other,
so `runWsConnection` derives its own correlation and adopts a gateway's `x-request-id`
rather than opening a second identity for a connection that already has one. Deriving it
in the one place a ws connection is set up is what keeps it one identity per connection
instead of one per emitter, and it also carries `transport: 'ws'`, which nothing on that
path previously distinguished.

Verified non-vacuous: reverting `src/` fails exactly the six new correlation assertions
across the three emitters and leaves the thirteen lifecycle ones green.

Closes #84

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:57:39 -05:00
chrnx 7d39aebfab fix(stream): report a stream's lifecycle on every adapter, not only Node
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
CI / runtimes (bun) (pull_request) Successful in 15s
`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 / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 5s
`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 / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 11s
`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 b75158eddc Merge pull request 'Tier 2 for the beta: the lifecycle stream gets a contract, plus a P0 found on the way' (#81) from beta/tier-2 into develop
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 21s
2026-09-01 16:11:13 +00:00
chrnx 0adab69466 docs(changelog): record the tier-2 work in Unreleased
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 14s
The event stream's contract, the read-only `events` token, the reserved framework names,
the unmatched-route label, the budget bookkeeping, and the `onError` crash.

Grouped by what a reader is looking for rather than one bullet per commit: the three
observability issues describe one contract and read better as one entry plus the two
fields it needed.

The reserved names get their own paragraph saying plainly that they **can fail an app
that boots today**, because a changelog that buries a breaking change under a feature
heading is how someone finds it from a stack trace instead.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:08:47 -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 0f2f62d8c1 Merge pull request 'docs(changelog): record the unreleased work, without cutting a version' (#79) from chore/changelog-unreleased into develop
CI / runtimes (bun) (push) Successful in 17s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
2026-09-01 14:59:27 +00:00
chrnx 4c9e606cfb docs(changelog): record the unreleased work, without cutting a version
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 11s
CI / runtimes (deno) (pull_request) Successful in 20s
Everything on `develop` since `26.8.0-beta.1` that a user would notice: the request
budget and the connection-drop warning from the contribution merge, `handleSignals`,
the extension-point type exports, the single header resolution, and the two crashes
(the CORS predicate, and the JSR package's missing `require`).

The heading stays `[Unreleased]`. The version bump and the dated section belong to the
cut, not to the work.

Left out on purpose: the two `ci(release)` commits. They change how the workflow spends
a dist-tag and whether it publishes release notes — real, and invisible to anyone
reading this file to find out what changed in the package they installed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:47:57 -05:00
chrnx f08956bea8 Merge pull request 'Tier 1 for 26.9.0-beta.1: the four that block the cut' (#78) from beta/tier-1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 14:44:41 +00:00
chrnx b8b3548f15 perf(cors): resolve the request's headers once, not two or three times
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 21s
CI / runtimes (bun) (pull_request) Successful in 16s
`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 / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 16s
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
chrnx d93037e2a0 Merge pull request 'Merge contrib: cap concurrent requests, from an outside contributor' (#75) from contrib into develop
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / dco (push) Has been skipped
CI / build (push) Successful in 30s
2026-09-01 13:29:40 +00:00
hgshreyas ff94e55496 feat: cap concurrent requests across runtimes
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
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 / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 11s
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 4b04421ddd Merge pull request 'ci(release): publish the release notes, not just the tag' (#62) from ci/github-releases into develop
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
Promote → GitHub / push-github (push) Failing after 6s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 19s
2026-08-19 19:32:14 +00: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 (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
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 ead71dc1b1 Merge pull request 'ci(release): spend the publish's one dist-tag on latest while there is no stable' (#60) from ci/publish-under-latest into develop
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / dco (push) Has been skipped
CI / build (push) Successful in 24s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 11s
Promote → GitHub / push-github (push) Failing after 6s
2026-08-19 19:18:20 +00:00
chrnx 19fcc18899 ci(release): spend the publish's one dist-tag on latest while there is no stable
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 4s
`npm dist-tag` cannot use Trusted Publishing. The OIDC exchange lives inside
`publish.js` and nowhere else, so the token it returns is publish-scoped: the
step added in the previous commit got `E401` on v26.8.0-beta.1, after both
registries had already taken the version.

That leaves one npm write per release, and it has to go where it counts.
While no stable exists, `latest` and `beta` mean the same thing — there is
nothing else to install — so `latest` takes the publish, because that is what
a bare `npm install @green-tea/core` resolves to and an untouched `latest`
hands the default install an older build than the one just released. The
channel tag is moved by hand; the step prints the command and AGENTS.md says
when it applies.

This is temporary by construction. Once a stable version exists it owns
`latest`, a beta published afterwards must not drag it backwards, and the
publish goes back to setting the channel tag directly — with nothing left to
move by hand.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:17:12 -05:00
chrnx 7f9e6b19d6 Merge pull request 'ci(release): keep latest on the newest beta, and make a re-run finishable' (#58) from ci/release-dist-tags into develop
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (edge) (push) Successful in 12s
Release → npmjs / publish-prod (push) Has been skipped
2026-08-19 19:11:16 +00:00
chrnx 7be26fda5c ci(release): keep latest on the newest beta, and make a re-run finishable
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
While there is no stable release, a bare `npm install @green-tea/core` should
get the same thing `@beta` gets — that is what the docs promise. Since
`1a313c2` a prerelease publishes under its channel tag only, so the next
release would have left `latest` behind on 26.8.0-beta.0: an older build for
anyone who installs without asking for a channel.

`npm publish` sets one tag, and `npm dist-tag` cannot use Trusted Publishing —
the OIDC exchange lives inside `publish.js` and nowhere else. Rather than keep
a long-lived npm token in a secret for one command, the step runs the same
exchange itself: request the Actions id-token, trade it for a short-lived
package-scoped token, move the tag. Both values are masked.

The rule is bounded on purpose. Once a stable version exists it owns `latest`
permanently, and a beta published afterwards must not drag it backwards; the
lookup that decides this is read into a variable first, so a failed request
fails the step instead of passing for "no stable exists".

Both publishes also become skip-if-present. That is not belt-and-braces: the
new step runs after them and can fail, so a re-run has to be able to finish
the remaining work instead of dying on a version npm would reject anyway. The
JSR guard asks api.jsr.io rather than jsr.io/meta.json, which is 404 for a
package with no versions yet — the state this package is actually in.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:10:00 -05:00
chrnx e540752f1e Merge pull request 'chore(release): close the changelog at 26.8.0-beta.1' (#56) from chore/close-changelog-26.8.0-beta.1 into develop
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 12s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (pull_request) Successful in 24s
CI / build (push) Successful in 24s
CI / runtimes (edge) (push) Successful in 12s
2026-08-19 19:02:33 +00:00
chrnx e86051382d chore(release): close the changelog at 26.8.0-beta.1
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
Everything in `[Unreleased]` ships under this tag, so the section gets its
date one step before the tag exists — the order AGENTS.md now prescribes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:01:14 -05:00
chrnx b8cb684a6b docs: close the changelog at the tag, not when the version is decided
The changelog said [26.8.0-beta.1] - 2026-08-17 with a date, above work that
has never been tagged and is on no registry — npm still ends at beta.0 and
neither forge has the tag. A day of further work then landed underneath it as
[Unreleased], so the file asserted both that beta.1 shipped and that its
contents had not.

Folds that section back into [Unreleased], where all of it actually belongs,
and writes the rule in AGENTS.md so the next version is closed one step before
its tag rather than the day it is decided.

A version number is a plan; a changelog heading is a receipt.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:00:55 -05:00
chrnx 2c838c8753 Merge pull request 'fix(mesh): refuse to export a value the wire cannot carry' (#54) from feat/mesh-transport-guard into develop
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 24s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (pull_request) Successful in 4s
Promote → GitHub / push-github (push) Successful in 6s
2026-08-18 18:39:32 +00:00
chrnx cd4f47486f Merge pull request 'feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one' (#53) from feat/mesh-boot-retry into develop
CI / runtimes (bun) (push) Successful in 22s
CI / build (push) Successful in 25s
CI / runtimes (edge) (push) Successful in 12s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 18s
2026-08-18 18:18:23 +00:00
chrnx ffb5139cae Merge pull request 'feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do' (#48) from feat/mesh-envelope into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (deno) (push) Successful in 18s
2026-08-18 18:00:58 +00:00
chrnx 46342a0aa2 fix(mesh): refuse to export a value the wire cannot carry, instead of delivering an empty object
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 18s
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 / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 16m11s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
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 / 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
CI / dco (pull_request) Successful in 4s
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 1ccbf6cadf Merge pull request 'fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits' (#47) from feat/mesh-reconnect into develop
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (edge) (push) Successful in 12s
2026-08-18 16:04:54 +00:00
chrnx 6ffbad9825 fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (edge) (pull_request) Successful in 12s
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 6672185ba2 Merge pull request 'fix(shutdown): arm the teardown timer before the callback that clears it' (#44) from fix/teardown-timer-ordering into develop
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 23s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 17s
CI / runtimes (edge) (push) Successful in 12s
2026-08-18 14:18:47 +00:00
chrnx 198e62944f fix(shutdown): arm the teardown timer before the callback that clears it
CI / runtimes (edge) (pull_request) Successful in 11s
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 17s
`runTeardown` declared `finish` above the `timer` it clears, so the
reference held only because every caller — the timer's own callback and
`teardown.run().then()` — happens to be asynchronous. That is correct by
timing rather than by construction, which is what #20 asked to remove from
this file; `closeApp` twenty lines below already arms its timer first and
carries a comment explaining why that direction is the safe one.

Reversing the order here leaves both shutdown paths resting the same forward
reference on the same guarantee: setTimeout cannot invoke its callback
synchronously. No behaviour changes.

Closes #20

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 09:16:27 -05:00
chrnx 7d04b2d736 Merge pull request 'chore: back-merge main so promotions can go back to fast-forward-only' (#42) from chore/backmerge-main into develop
CI / dco (pull_request) Successful in 4s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 24s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (bun) (push) Successful in 13s
CI / runtimes (edge) (push) Successful in 12s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
CI / build (push) Successful in 23s
CI / runtimes (deno) (push) Successful in 16s
2026-08-17 23:22:22 +00:00
chrnx 51608b0631 chore: back-merge main so promotions can go back to fast-forward-only
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 11s
CI / dco (pull_request) Successful in 5s
PR #40 promoted develop to main with a merge commit, which left an empty
merge commit living only on main. It carries no content — its diff against
its own develop parent is empty — but it keeps main out of develop's
ancestry, so the next fast-forward-only promotion cannot run at all.

This merge is a no-op by content and exists only to put that commit back
into develop's history. With it, develop -> main is a fast-forward again,
which is what AGENTS.md requires: no commit is ever born on main.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 18:20:47 -05:00
chrnx bbcc90eb4d Merge pull request 'feat: the trust release — observability, shutdown teardown, routing correctness and the docs split' (#41) from feature/trust-release into develop
CI / build (push) Successful in 23s
CI / runtimes (deno) (push) Successful in 16s
CI / runtimes (edge) (push) Successful in 13s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
2026-08-17 23:17:11 +00: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 0218508a96 docs(readme): lead with what the framework owns, not with what it is not
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Failing after 3m33s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 11s
Follows the website copy strategy, translated from marketing register into the
one this file is read in. The strategy's own summary of the change applies
here too: stop selling simplicity because the framework is small, start
selling simplicity because the framework carries the infrastructure.

The hero led with "not a mutable bag threaded through positional middleware".
Middleware ordering was the origin problem, not the whole of what this does,
and a reader who has never hit that pain learns only what green-tea is
against. It now says what it is for: declare what a step needs and produces,
and the framework derives the order, validates the wiring before traffic, and
runs only the slice a route requires.

Added "Who does the work?", the section the strategy ranks first and the file
never had. It is a table of which side of the import each infrastructure
decision lives on, ending with business rules on yours — and it is where the
single runtime dependency now sits, as evidence rather than as a headline. The
number was never the point: fewer moving parts to understand, upgrade,
coordinate and debug is. A framework owning less does not delete that work, it
moves it into your application.

"Batteries included — still one dependency" did both of the things the
strategy says to demote in one heading. It is now "What the foundation already
carries", which is the same list making the ownership argument instead of a
bloat-adjacent one.

Accuracy guardrails re-checked after editing rather than assumed: compile-time
guarantees stay scoped to the typed flow core with decorator wiring
boot-validated, mesh stays alpha, no zero-dependency claim, no benchmark
leadership, no anti-Web-Standards framing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 13:21:44 -05:00
chrnx 41c1f4308b chore(release): cut 26.8.0-beta.1
package.json and deno.json both still said 26.8.0-beta.0, which npm already
has. Publishing would have been rejected there and — the expensive half — JSR
versions are immutable, so a wrong one can never be replaced.

The changelog section is closed at today rather than left under Unreleased,
because what it now contains is the whole of this release: the observability
contract, shutdown teardown, the dot-segment behaviour change, and the two
fixes on the fetch and shutdown paths.

The documentation repository is tagged 26.8.0-beta.1 alongside, and that
number means the same thing there: not a version of the site, but the core
release its pages describe. Cutting the two together is what makes the version
a claim that the release is documented rather than only shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 13:05:27 -05:00
chrnx bb75cabeea docs(changelog): record the release's largest feature, which was missing entirely
Unreleased carried two entries for the 81 commits since v26.8.0-beta.0, and
the observability contract was not one of them — the feature four independent
reviews named as the project's biggest gap, and the reason issue #10 existed,
had no changelog presence in any version. Someone deciding whether to upgrade
would have read the release as a shutdown fix.

Also added, in the order a reader needs them rather than the order they landed:

Changed: `.` and `..` in a request path now resolve instead of 404ing. This is
a behaviour change and belongs under Changed rather than buried in Fixed — it
is Node-only, it ends a divergence where the same bytes reached different
routes per runtime, and it is worth telling anyone whose proxy matches on the
literal path that the proxy and the application no longer agree.

Fixed: the BodyInit narrowing on the app.fetch path, which is the path Deno,
Bun and the edge all use, and the shutdown timer ordering that left a
ReferenceError waiting for whoever touched it next.

Found by diffing the public surface at the tag against HEAD rather than
rereading the file. `createApp` gained five options and the package eleven
exports since the beta; the entries above are what had no home.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:50:37 -05:00
chrnx bead3c1569 docs: make the docs rule followable by the people it addresses
Two problems with the rule added earlier today, both found by asking what it
means for the beta rather than whether to automate it.

green-tea is public and green-tea-docs was private, so CONTRIBUTING.md — read
by external contributors — pointed them at a repository that answered 404 and
asked them to change a page they could not see. The repository is now public,
which is what makes the rule possible at all; nothing in it was ever private,
since the history came from this repository's own website/ directory.

And "in the same pull request" cannot be done: a pull request does not span
two repositories. It is a companion pull request, linked to the first, and
both documents now say so.

Added the escape hatch the rule was missing. A contributor who does not want
to write the docs change can say so and a maintainer writes it — what this
line exists to prevent is an API change nobody mentions, not an unwritten
page, and a rule with no honest way out gets ignored rather than followed.

Neither the automation decision nor the accepted risk changes. The link check
stays rejected on the measurement recorded in the trust-release plan.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:38:09 -05:00
chrnx 0414aff665 docs(plans): reject the docs link check, and record what measuring it showed
It was recommended in this plan as the automated guard worth building. Building
enough of it to decide argued the other way, and the reasoning is worth keeping
so the next person does not spend the afternoon rediscovering it.

The narrow version is clean and useless: all 24 symbols the pages import from
@green-tea/core exist among the package's 101 exports, so it finds nothing —
and it structurally could not have caught #18, the one incident there is.
That was close() gaining an option the docs never mentioned. Imports are the
part that does not drift.

Widening it to options and methods produced 17 findings and all 17 were false.
A regex cannot separate a nested tls: { key, cert } from a top-level option, or
prose describing Express's app.use() from a green-tea call. A check that cries
wolf 17 times out of 17 is worse than none, because people learn to skip it.

Type-checking the code blocks would catch the real class, and costs the
documentation repository a dependency on the framework plus examples that must
compile — buying the guarantee back by spending the independence the split was
for. The accepted risk stands, now chosen rather than defaulted to.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:32:01 -05:00
chrnx 21765c2a47 docs: put the docs-drift warning where nobody can miss it
The rule was already in both READMEs, and in both it was a subordinate clause
at the end of something else — a trailing "because nothing fails when the two
disagree" here, a closing section titled "The seam this repository opens"
there. Written, and easy to read past.

Both are now a callout: what breaks, that nothing tells you, and what to do
instead. The docs repository's moves to the top, above how to run it, because
someone opening that repository is usually about to edit a page.

Deliberately not in the marketing site. That risk belongs to whoever changes
the API, not to whoever is deciding whether to try the framework.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:17:30 -05:00
chrnx cd6e2f073f docs: put the docs-drift rule where a contributor reads it
Task 4.4's obligation was to state the risk the docs split opens, and the
first pass met it in the two places that publish rather than the two that
govern: both READMEs. The core README's copy sits in "Docs & development", a
section a user reads and a contributor about to rename a decorator does not.

AGENTS.md and CONTRIBUTING.md both already carried "New public API needs a
note in README.md". Both were written before the split and neither was
updated for it, so the two documents actually read mid-change said nothing
about the new repository — the rule existed everywhere except where it applies.

Both now name green-tea-docs and carry the reason, because a rule without one
is the first thing dropped when a change is nearly finished. #18 is that
reason, and it happened while the two still lived in the same repository.

Neither automated option was built, and the plan now records which is worth
building and why: a link check against the published package targets #18's
real failure mode — a page naming a decorator, a createApp option or a method
that no longer exists — and needs only the identifiers in the pages' code
blocks compared against the package's exports. It catches lies rather than
staleness. A docs job triggered from core releases is weaker: it fires after
the API has already shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 12:11:29 -05:00
chrnx 38b73cebce docs(readme): say which parts are settled and which still move
The last thing a reader needs before betting on a beta, and the one thing
Honest scope did not answer: it admits what is missing, not what is likely to
change under them.

Present state only. No dates, no delivery commitment, and deliberately not a
roadmap — this is one person's spare-time work, and a schedule it cannot keep
would cost more trust than the schedule earns. The API freeze stays declared
under **next**, untouched, and gets planned near the RC.

Every tier is read off the history rather than asserted. The graph is settled
because graph.ts and container.ts have not been touched since the beta
hardening on 7 July, and because the changes to metadata.ts since then only
add decorators (@Head, @Options, @Html) rather than redefine the ones that
were there. The plugin API is listed as moving because it moved this week.
The pipeline context is listed because 4081106 made it one object mutated in
place, which changed what a step that captured it observes — a real semantic
change, not a perf note, and worth a reader knowing.

Two claims the trust-release plan proposed are not made. It grouped decorator
syntax with the volatile things; the volatility there is TC39's, not ours, and
README already explains it. And it listed the CLI, which ships from its own
repository on its own version line, so nothing here can honestly speak for it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:56: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 08310ac252 Merge pull request 'release: promote the app.close() timeout and the nanoid bump to main' (#40) from develop into main
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / build (push) Successful in 35s
2026-08-12 19:11:55 +00:00
99 changed files with 7512 additions and 490 deletions

No files matched your search

+16 -12
View File
@@ -1,13 +1,22 @@
name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
# its release workflow (production publish).
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` to the public GitHub repo — develop and
# feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
# would expose every branch).
#
# Tags are deliberately NOT mirrored. The same `v*` tag means two different things on the two
# forges: on Gitea it stages to Verdaccio (`stage.yml`), on GitHub it publishes to npm and
# JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
# decision a person takes after reading the staging run, not a side effect of creating it:
#
# git push gh v<version>
#
# `--tags` is left off the branch push for the same reason. It used to ride along here, which
# meant any tag sitting in the runner's clone could reach production as a side effect of
# promoting `main` — a publish nobody chose, of a commit nobody was looking at.
on:
push:
branches: [main]
tags: ['v*']
jobs:
push-github:
@@ -16,15 +25,10 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history + tags for a clean push
- name: Push main + tags to GitHub
fetch-depth: 0 # full history for a clean push
- name: Push main to GitHub
env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: |
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
if [ "${{ github.ref_type }}" = "tag" ]; then
git push github "refs/tags/${{ github.ref_name }}"
else
git push github "HEAD:refs/heads/main"
git push github --tags
fi
+68 -4
View File
@@ -12,9 +12,11 @@ jobs:
publish-prod:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
env:
PKG: '@green-tea/core'
permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read
contents: write # create the GitHub release for this tag
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -40,11 +42,41 @@ jobs:
# types, module analysis — and learning about them after npm has published leaves the tag
# half-shipped. Seconds, against a failure mode with no clean recovery.
- run: deno publish --dry-run
# A publish sets exactly one dist-tag, and it is the only npm write this workflow can make:
# Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token
# it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag
# the publish gets has to be the one that matters most.
#
# While no stable release exists, `latest` and the channel tag mean the same thing — there is
# nothing else to install — and `latest` takes it, because that is what a bare
# `npm install @green-tea/core` resolves to. Leaving it behind on an older beta would hand the
# default install an older build than the one just released. The channel tag is then moved by
# hand; the step prints the command. Once a stable version exists it owns `latest` for good,
# a later beta must not drag it backwards, and the channel tag becomes the automatic one again.
- name: Publish to npmjs
run: |
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
echo "dist-tag: $TAG"
VERSION=$(node -p "require('./package.json').version")
CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
# Read the list into a variable so a failed lookup fails the step, rather than passing for
# "no stable exists" and pointing `latest` at a prerelease that should not have it.
VERSIONS=$(npm view "$PKG" versions --json)
if [ "$CHANNEL" != latest ] \
&& ! node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
TAG=latest
else
TAG=$CHANNEL
fi
echo "$VERSION under dist-tag: $TAG"
# Skip rather than fail when the version is already up, so a re-run after a later failure
# can finish the remaining work instead of dying on a duplicate npm rejects anyway.
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
echo "npm already has $VERSION"
else
npm publish --access public --tag "$TAG"
fi
if [ "$TAG" != "$CHANNEL" ]; then
echo "::notice::Move the channel tag by hand: npm dist-tag add $PKG@$VERSION $CHANNEL"
fi
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
# failure *after* it would cost a version number permanently. Version and entry points come
@@ -52,4 +84,36 @@ jobs:
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
# id-token npm just used; the package is linked to this repository on jsr.io.
- name: Publish to JSR
run: deno publish
run: |
VERSION=$(node -p "require('./package.json').version")
PKG=${PKG#@}
# 404 until the version exists, and also for a package with no versions at all — which is
# what this one was until v26.8.0-beta.1 — so the guard must not read a 404 as an error.
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
echo "JSR already has $VERSION"
else
deno publish
fi
# The release page is where people who do not read a changelog find out what changed, 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, and generated notes would restate merge subjects nobody chose.
#
# Idempotent like the publishes above, so a re-run after a later failure does not stop here.
# `--verify-tag` refuses to invent a tag: the release attaches to the one that triggered this
# run and can never move it. A prerelease is marked as such, which is what keeps GitHub's
# "Latest" badge off a beta.
- name: Create the GitHub release
env:
GH_TOKEN: ${{ github.token }}
run: |
VERSION=$(node -p "require('./package.json').version")
TAG=${GITHUB_REF_NAME}
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "release $TAG already exists"; exit 0
fi
node scripts/changelog-section.mjs "$VERSION" "$TAG" > /tmp/notes.md
case "$VERSION" in *-*) PRE=--prerelease ;; *) PRE= ;; esac
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" \
--notes-file /tmp/notes.md --verify-tag $PRE
+13 -2
View File
@@ -1,12 +1,18 @@
name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
# internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag.
# Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version.
#
# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path —
# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we
# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm
# allows 72 hours to unpublish and JSR allows nothing at all.
on:
push:
branches: ['release/**']
tags: ['v*']
jobs:
publish-stg:
@@ -32,6 +38,11 @@ jobs:
run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version")
# Staging overwrites the version it publishes, and a stable number that changes
# under an internal consumer is worse than no staging at all. This will need
# revisiting at the first stable release, which is exactly the one most worth
# staging: the answer is probably to stage it under a suffixed version rather
# than to drop the guard.
case "$VER" in
*-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
+54 -5
View File
@@ -29,16 +29,19 @@ Run the first four before proposing anything as finished. The runtime suites sta
## Two forges
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and release tags, nothing else.
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` automatically and release tags only by hand.
```
feature/* → develop → main → [promote.yml] → GitHub main
↑ ↓
lead dev GitHub contrib ← external PRs
↑ │ ↓
lead dev │ GitHub contrib ← external PRs
│
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
└─── GitHub (pushed by hand): [release.yml] → npm + JSR
```
- **Gitea `develop`** — active development.
- **Gitea `main`** — staging. Merging here publishes nothing; only a `v*` tag publishes.
- **Gitea `main`** — staging. Merging here publishes nothing. A `v*` tag here publishes to the internal Verdaccio, never to a public registry.
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
- **`contrib`** — exists on *both* forges. Where outside contributions land.
@@ -66,6 +69,52 @@ The exception is a `hotfix/*`, which lands on `main` without passing through `de
A conflict against unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve.
## Releasing
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
nowhere is worse than no heading at all, because the next reader believes it.
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
two contradictory things — that beta.1 was released, and that everything in it was not.
So the order is: everything merged and promoted → **close the section with the release date** → tag →
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
number feels.
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
A version number is a plan; a changelog heading is a receipt.
**A tag is created twice, on purpose.** Pushing `v*` to Gitea stages that exact commit to
Verdaccio through the real publish path; pushing the same tag to GitHub publishes it to npm and
JSR. Nothing promotes the tag for you — `promote.yml` mirrors `main` and only `main`, so the
second push is a decision made after reading the first run:
```bash
git push origin v<version> # Gitea → Verdaccio, reversible
git push gh v<version> # GitHub → npm + JSR, permanent on JSR
```
The split exists because a mistake caught on Verdaccio costs a re-tag, and the same mistake
caught on JSR costs the version number forever.
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
on `v26.8.0-beta.1`). While there is no stable release the publish spends that one tag on `latest`,
since that is what a bare `npm install @green-tea/core` resolves to, and the workflow prints the
command for the rest:
```bash
npm dist-tag add @green-tea/core@<version> beta
```
Once a stable version exists this stops being a chore: `latest` belongs to the stable release, the
publish gives a beta its channel tag directly, and there is nothing left to move.
## CI
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
@@ -80,4 +129,4 @@ GitHub does not run workflows on fork pull requests until a maintainer approves
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
- New public API needs a note in `README.md`.
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
+161 -34
View File
@@ -4,14 +4,14 @@
## Environment
- **Date**: 2026-07-07
- **Commit**: fe1831a
- **Date**: 2026-09-02
- **Commit**: 8c5855c
- **Node**: v22.22.2
- **OS**: darwin
- **CPU**: Apple M4 Max (16 cores)
- **RAM**: 69 GB
- **Core-pinned**: no
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
- **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
> loopback on the same machine, sharing the same cores as the server processes they measured. That
@@ -29,64 +29,74 @@
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
| raw-http | 119,357 | 0.00 | 1.00 | 1.00 | 0.4% | 118,560–120,067 |
| nestjs-fastify | 98,039 | 0.00 | 1.00 | 2.00 | 1.2% | 96,073–99,680 |
| fastify | 89,097 | 1.00 | 1.00 | 2.00 | 0.1% | 88,864–89,207 |
| green-tea | 87,473 | 1.00 | 2.00 | 2.00 | 0.3% | 86,903–87,607 |
| express | 24,677 | 3.00 | 5.00 | 8.00 | 0.2% | 24,647–24,769 |
| nestjs-express | 21,879 | 4.00 | 6.00 | 9.00 | 0.2% | 21,845–21,953 |
### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
| raw-http | 120,905 | 0.00 | 1.00 | 1.00 | 0.5% | 119,927–121,713 |
| nestjs-fastify | 91,849 | 1.00 | 1.00 | 2.00 | 0.3% | 91,825–92,599 |
| fastify | 88,317 | 1.00 | 1.00 | 2.00 | 0.2% | 87,997–88,439 |
| green-tea | 86,595 | 1.00 | 2.00 | 2.00 | 0.2% | 86,368–86,880 |
| express | 24,200 | 3.00 | 5.00 | 8.00 | 0.2% | 24,158–24,260 |
| nestjs-express | 21,182 | 4.00 | 6.00 | 9.00 | 0.7% | 21,150–21,518 |
### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
| raw-http | 118,996 | 0.00 | 1.00 | 1.00 | 0.3% | 118,583–119,584 |
| nestjs-fastify | 89,527 | 1.00 | 2.00 | 2.00 | 1.0% | 87,572–90,028 |
| fastify | 86,671 | 1.00 | 1.00 | 2.00 | 0.1% | 86,490–86,793 |
| green-tea | 80,079 | 1.00 | 2.00 | 2.00 | 0.2% | 80,026–80,375 |
| express | 24,325 | 3.00 | 5.00 | 8.00 | 0.2% | 24,281–24,407 |
| nestjs-express | 20,872 | 4.00 | 6.00 | 9.00 | 0.2% | 20,801–20,940 |
### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
| raw-http | 104,288 | 0.00 | 1.00 | 1.00 | 0.4% | 103,776–104,916 |
| green-tea | 70,298 | 1.00 | 2.00 | 3.00 | 1.0% | 68,972–70,607 |
| fastify | 65,905 | 1.00 | 2.00 | 3.00 | 0.3% | 65,725–66,367 |
| nestjs-fastify | 63,318 | 1.00 | 2.00 | 3.00 | 0.9% | 62,454–63,747 |
| express | 20,297 | 4.00 | 6.00 | 10.00 | 0.5% | 20,158–20,414 |
| nestjs-express | 18,788 | 5.00 | 7.00 | 10.00 | 0.3% | 18,684–18,862 |
## Step-scaling (green-tea)
| Path | Steps | req/s |
| --- | --- | --- |
| /steps/0 | 0 | 92,282 |
| /steps/3 | 3 | 81,530 |
| /steps/5 | 5 | 71,994 |
| /steps/0 | 0 | 88,108 |
| /steps/3 | 3 | 79,951 |
| /steps/5 | 5 | 74,127 |
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
Each additional pipeline step costs roughly 2,796 req/s (-15.9% over 5 steps), on this box.
## green-tea across runtimes
| Scenario | node | deno | bun |
| --- | --- | --- | --- |
| JSON hello (overhead) | 90,976 | 153,408 | 131,674 |
| Route param | 88,905 | 146,368 | 126,909 |
| Pipeline (3 steps) | 82,045 | 136,256 | 117,489 |
| POST JSON + validation | 72,236 | 106,662 | 95,124 |
Same application, same built bundle, same box — only the runtime differs. Read across a row, never against the cross-framework tables above: those measure other frameworks on Node, and nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.
## Cost of secure-by-default (green-tea)
| Label | req/s |
| --- | --- |
| security:false (parity) | 98,093 |
| security:true (default) | 92,998 |
| security:false (parity) | 87,473 |
| security:true (default) | 83,773 |
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.2% req/s on this box.
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
@@ -116,3 +126,120 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
<!-- keep-below: hand-written, survives `npm run bench` -->
## What moved between releases
These figures were measured per function and never per version. Every change on the request path
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
`npm run bench:compare` exist to close.
### The release gate: `26.8.0-beta.1` → `26.9.0-beta.1`
Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
one `node_modules` and one byte-identical server file. Medians of five rounds:
| Scenario | 26.8.0-beta.1 | 26.9.0-beta.1 | Δ |
| --- | --- | --- | --- |
| hello | 91,343 | 90,371 | −1.1% |
| param | 88,113 | 87,921 | −0.2% |
| pipeline (3 steps) | 80,934 | 80,893 | −0.1% |
| validate (POST) | 72,340 | 72,241 | −0.1% |
| hello + security | 85,967 | 86,426 | +0.5% |
| hello + cors predicate | 82,609 | 83,401 | +1.0% |
| preflight + cors predicate | 112,055 | 115,069 | **+2.7%** |
Every row but the last overlaps between the two sides and is noise. The preflight row does not: the
new tree wins all three rounds, which is where a `cors.origins` predicate stopped being evaluated
three times per request.
That change is a call count, not a rate, and the benchmark's predicate is a `Set` lookup — so the
saving is invisible in req/s here and would be two or three network round trips in the lookup the
option exists for:
| | per cross-origin GET | per preflight |
| --- | --- | --- |
| 26.8.0-beta.1 | 2 | 3 |
| 26.9.0-beta.1 | **1** | **1** |
### Against `26.7`, and why it is not a regression
The table this file carried until today was measured at `fe1831a`, before `26.8.0-beta.1`
shipped. Re-running
that tree today, under the same toolchain and dependencies, gives 94,403 req/s on `hello` and
93,361 on `param` against 89,527 and 85,839 for the current tree — roughly −5% and −8%. Against
`fastify` as a control, which moved +1.2% to +1.8% across the same scenarios, green-tea's ratio to
it fell 6.6% to 11.7%.
**That number is real and it is not a regression, because it is not the same program.** July matched
routes by splitting the path and comparing segments, returning on the first hit, in one flat file.
It had no route constraints, no specificity ranking, no per-request correlation, no lifecycle
stream, and one adapter. It was fast the way something is fast before it does anything.
What the interval bought, in the order it costs: a runtime-neutral request and response boundary,
which is what serves Deno, Bun and workerd from one core rather than one adapter; constraint and
specificity matching; a correlated event stream; and per-request identity.
The first of those is now measurable, because the runtimes table above did not exist either. The
same boundary that costs on Node is what puts the same application on Deno at 153,408 req/s and Bun
at 131,674 against Node's 90,976 — and above the 119,357 that Node's own `http` module manages with
no framework at all. Whether the trade is worth it is the reader's call. This file's job is to say
what it cost and what it bought.
### Figures recorded when each change landed
Measured at the time, in the code, against a microbenchmark rather than this harness:
| Where | Finding |
| --- | --- |
| `src/http/core.ts:63` | a per-request derivation that reached **45% of a whole request** before it was fixed |
| `src/http/core.ts:89` | six request-id generators compared; `crypto.randomUUID` at 76 ns was the fastest cross-runtime option, and the only alternatives that beat it are Node-only |
| `src/http/core.ts:229` | wrapping `dispatch` in a second async frame: 0.43 µs per request |
| `src/bus.ts:173` | spreading request identity into an event payload: ~197 ns on a two-step pipeline |
| `src/pipeline.ts:58` | one timestamp per step boundary instead of two: 25.2 ns against 45.3 ns per step |
| `src/http/headers.ts:30` | 146.4 ns against 55.9 ns for the same header answer |
| `src/http/body.ts:39` | 250 ns per request for a closure and the error context it captured |
| `src/http/router.ts:232` | per-segment decoding on a path nobody decodes: 95.8 ns for `/hello`, 342.7 ns for six segments |
**These do not add up to the release delta, and cannot.** They cite different baselines — 4.4 µs,
4.5 µs, 10.19 µs — because each was taken against whatever a request cost on the day. A dozen
findings in nanoseconds against inconsistent references is a discussion, not a total. A version-level
number measured against a fixed baseline is what was missing, not rigour.
### What is still unattributed
Three candidates for the `26.7` → `26.9` interval were measured and none of them account for it:
- **`crypto.randomUUID` per request** — removing it entirely lands within noise on every scenario,
and one row moves the wrong way. At 76 ns against a ~11 µs request it is ~0.7%, below what a load
test at this CV can resolve.
- **Specificity ranking in the matcher** — replacing it with July's first-match-wins is noise on all
four rows at this route-table size.
- **The bundle versus the TypeScript source** — every row overlaps, so the form the table loads does
not explain it either.
No single culprit was found. The remaining candidates are the neutral request and response objects
and the several small per-request allocations around them, which is a shape that resists a single
measurement.
## What this file does not measure
- **Route-table width was invisible until `26.9`.** Every matcher cost scales with how many
candidates a request walks past, and the cross-framework tables use six routes — so any matcher
change measures as noise there regardless of its size. `npm run bench:compare` carries 50- and
200-route cases for this reason. Settling route ranking when the table is built rather than per
request is worth nothing at six routes, +3.4% at fifty, and **+12% to +14.9% at two hundred**,
across twelve rounds without a crossing sample.
- **Boot time is absent.** Independent providers began booting concurrently in `26.9`: three
providers with no edges and 200 ms of work each went from 616 ms to 210 ms. No table here shows it.
- **Streaming is absent.** Every scenario is a buffered response. SSE framing, the encoder's
per-item work, and the stream lifecycle events are not exercised.
- **The cross-framework tables are Node-only**, and they load green-tea from `src/` through `tsx`
while the other frameworks load their published JavaScript. Measured today, that difference is
within noise — but it is a difference, and the runtimes table above avoids it by loading the built
bundle on all three.
- **The runtimes table compares each runtime's HTTP server, not its JavaScript engine.** `Deno.serve`
and `Bun.serve` are native stacks; Node's `http` is JavaScript. "green-tea on this runtime" is the
claim, and it is the one an application actually experiences.
+373 -4
View File
@@ -6,17 +6,382 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
## [26.9.0-beta.1] - 2026-09-04
### Added
- **A request budget, not just a connection cap.** `createApp({ limits: { maxConcurrentRequests } })`
bounds how many handlers run at once, per server and per Fetch adapter instance; over the budget a
request gets `503` with `Retry-After: 1` instead of queueing behind the ones already running. It is
opt-in and unlimited by default, and it counts *executing handlers* rather than open connections —
the slot is released when routing and the handler finish, so a long-lived SSE stream or a WebSocket
upgrade does not hold one for its lifetime. On Node a client disconnect releases the slot early. A
handler that never returns keeps its slot, which is the honest behaviour for a budget of this shape.
Contributed by @hgshreyas.
Node's connection cap also stopped being silent: reaching `maxConnections` now logs a warning
naming the dropped peer, rate-limited to one a minute. Until now the socket was destroyed with no
HTTP response and nothing said so, which reads from the outside like a network fault.
- **`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 supported — keep the handler, or hand it over. What is not
optional either way is that *something* calls `close()`; the teardown registry only runs from
there, so a container `SIGKILL`ed after its grace period skips every `dispose()` and reports
nothing.
Declared once and wired per runtime by whichever boot call runs — `listen()`, `serveDeno()` and
`serveBun()` each attach it to the closer that drains *their* server, so `process.on` on Node and
Bun and `Deno.addSignalListener` on Deno stop being the application's problem. `close()`
unregisters, which means a *second* signal falls through to the platform default and ends the
process at once: Ctrl-C twice is the way out of a teardown that is stuck.
- **The extension-point types are exported, not just the extension points.** `TransformerFn` — the
type of `@Transformer`'s only argument — could not be imported, so a custom transformer was
attached with its shape redeclared inline or borrowed off a value as `typeof JsonTransformer`.
Checking the barrel for the same oversight turned up four more, all now exported: `PluginApi`,
`ScopeApi` and `ScopeNode`, the chain reached through `api.scope.add`, without which a plugin split
into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only —
nothing at runtime moved and no existing export changed.
- **The lifecycle stream has a contract now, not just events.** `request:end` is documented as
terminal and universal — it fires for every request shape and is the only one carrying the status
the client received, which makes it the request counter. `request:failed` means *handler code
threw*, which no status expresses on its own since a rendered `422` is also a throw, and
`route:unmatched` means *no route ran*. Both are **additional** to `request:end`, not alternatives
to it: one failing request emits three events and a 404 emits two, all sharing a `requestId`, and
an exporter that treats them as separate outcomes counts the same request twice. Silently — the
metrics just come out wrong.
`request:failed` now carries `status`, so an error counter can break down by status without
joining back through `requestId` for something the emitter already had. It is absent in exactly
one case: a custom `onError` that threw while producing it, where the framework does not know what
was sent and will not guess.
- **`@needs('events')` reaches the read-only half of the bus** — `{ on }`, the same narrowing
plugins already get, exported as the `Events` type. `app.bus` was public and a plugin could
subscribe, but the bus was not a graph token, so `@needs('bus')` failed at boot and nothing said
why. It still is not one, and that is the design: handing `emit` to every node turns a one-way
observation channel into something anything can forge events on. `@needs('bus')` now fails saying
exactly that, and pointing at the two things that do work.
A plugin remains the right home for observation, because it gets `on` and `onShutdown` *together*.
This token gives the subscribe half alone — `on()` returns its own unsubscribe for a `@Provider`
to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request
and would add a listener each time.
- **`@Sse` can emit an `id:`, so an `EventSource` reconnect has something to resume from.**
`sse(data, { id, event, retry })` tags a stream item and the encoder writes the fields ahead of
`data:`; an app that never calls it produces byte-identical output. Until now the encoder wrote one
field, so the browser had nothing to put in `Last-Event-ID` and every automatic reconnect — the
reason to choose SSE over a raw WebSocket — rebuilt the route's iterable from its start and lost
the gap in silence. The other half already worked: the request envelope has always carried every
header, so a handler could already read `@header('last-event-id')`; it simply always arrived empty.
`event:` and `retry:` come along because the same envelope carries them, and neither was reachable
before.
**green-tea stores nothing** — no buffer, no retention window, no replay. It 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. An `id` containing a
newline is rejected rather than stripped, since the SSE format is line-based and an id is exactly
the value most likely to be built from a request — a cursor, a page token — so one newline would
let a caller append fields to somebody else's stream. On an `ndjson` or `negotiate`-to-ndjson route
the payload is unwrapped and the fields dropped. New exports: `sse`, `isSseEvent`, `SseEvent`,
`SseFields`.
### Changed
- **A request's security and CORS headers are computed once.** They were derived twice per request
and three times for a preflight — once in the adapter, to seed the headers a response written
before routing still has to carry, and again during dispatch. Nothing was incorrect, but
`cors.origins` is a predicate precisely so it can be a lookup: an allowlist in Redis, a tenant
query. Running it two or three times charged the caller's latency budget and their backend for an
answer whose inputs had not changed in between, and made a predicate with a counter in it count
double.
- **Every `request:end` is now preceded by a `request:start` carrying the same `requestId`.** The
pairing held by accident until `maxConcurrentRequests` arrived: `request:start` had a single
emitter, so nothing could break it, and a shed request emitted only the `request:end`. A consumer
that opens per-request state on the first and closes it on the second — an in-flight gauge, most
obviously — would have drifted under shedding, which is when an operator is reading it, and would
have done so by producing a plausible wrong number rather than an error. It is a guarantee now,
written next to `LifecycleEvent` and enforced by a test that enumerates every response shape.
- **An unmatched request carries a bounded `route`.** `route:unmatched` was the one terminal request
event with no `route`, so the only subject a consumer could reach was `name` — which on that event
is the concrete, caller-controlled path. A matched path is bounded by the route table; an
unmatched one is bounded by nothing, and a scanner walking `/aaa`, `/aab`, `/aac` is a memory leak
with a metrics backend attached. It and the `request:end` that follows now carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE`. Written down alongside it: `name` is
caller-controlled and must never be a metric label.
- **Framework token names are reserved.** `logger`, `rooms`, `events` and `bus` cannot be declared
by a module, plugin or mesh export; taking one is a boot error naming it. Built-ins used to be
registered only if the name was free, 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 discovered from a log line that never appeared. `bus` is reserved without
being provided, so `@needs('bus')` cannot resolve to whatever a user happened to call `bus`.
**This can fail an app that boots today**, which is the point of it, and the fix is to rename.
- **No per-request bookkeeping when no request budget is set.** Every request registered a `close`
listener and set a flag for `maxConcurrentRequests`, which is opt-in and unlimited by default — so
most applications paid a closure and an `EventEmitter` registration per request, on the hot path,
for a feature that was off. Unchanged where a budget *is* configured: the listener is what
releases a slot when a client disconnects mid-handler.
- **Route ranking is settled when the route table is built, not on every request.** Matching scanned
every route registered under the request's method and ranked the candidates as it went, deriving
each pattern's specificity from its source string per comparison. Both the scan and the ranking
scale with the size of the route table, and neither can produce a different answer between two
requests — the table is assembled once, after the graph is prepared, and handed to the adapter
unchanged. Routes are now compiled, bucketed by method and ordered most-specific-first once, and
matching returns at the first route that matches.
Nothing about which route answers changes. Equal specificity still keeps registration order, which
the ordering carries through a stable sort rather than through a scan that declined to replace its
best on a tie. Two smaller savings ride along on the same path: a path segment holding no `%` skips
`decodeURIComponent` entirely, and decoding is memoized per request rather than repeated for every
candidate route that reaches the same parameter position.
Worth nothing on a small route table and worth a great deal on a large one, which is the shape of
the saving rather than a caveat on it: **no measurable change at 6 routes, +3.4% at 50, and +12% to
+14.9% at 200**. That is also why it went unnoticed for two releases — the benchmark had no
route-table-width dimension until this one, so every matcher change measured as noise regardless of
its size.
- **Independent providers boot concurrently.** Boot walked the topological order one node at a time,
so an application paid the *sum* of its providers' latencies rather than its longest chain — three
providers with no edges between them and 200ms of work each took 616ms for a graph whose critical
path is 200ms; it now takes 210ms. The graph already proved which nodes cannot constrain each
other, and flattening the sort was the only thing throwing that away: the ordered list is grouped
back into dependency levels and each level runs together, with level *N* fully registered and
warmed before *N+1* starts. Nothing the graph derives changes, and this is the second thing users
get for declaring `needs`/`provides` rather than ordering calls by hand — pruning was the first,
and neither is available to a middleware chain, where nothing declares what is independent.
Two consequences worth knowing. Teardown still runs in the exact reverse of boot: registration
follows level order rather than completion order, which is what keeps that a guarantee instead of
a race. And a required provider that fails no longer prevents its independent siblings from
starting — they are already in flight — so whatever they opened is registered for teardown before
the boot is aborted. On the bus, `boot:provider:start` no longer strictly alternates with `:ok`; a
level emits its starts together and then its results.
### Fixed
- **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on
the request path, above the region where errors convert to a response, so a throw became a rejected
promise nobody awaited — and Node's default for that is to exit. One cross-origin request was
enough, `onError` never saw it, and the trigger is a browser: the predicate is only reached when an
`Origin` header is present, so no test that forgets the header can catch it. A predicate that throws
now **denies** the origin and the failure is logged. A lookup that failed has not said yes, and a
broken allowlist must never widen into an open one.
- **The JSR package works.** JSR serves `src/` rather than the tsup build, and the ESM build's
`createRequire` banner therefore never existed there — so every lazy `require()` in the source had
nothing to resolve. `@Html('file')` and template mode died at boot on Deno with `ReferenceError:
require is not defined`. Two other 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, and 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.
Every call site now resolves through one helper that prefers the ambient `require` — so both npm
builds behave exactly as before — and otherwise rebuilds one from
`process.getBuiltinModule('node:module')`, which Node, Deno and Bun all expose synchronously. On
workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem"
story is finally the true one.
- **A custom `onError` that throws no longer takes the process down.** `createApp({ onError })` is
the advertised way to render errors, it runs on the request path, and it ran with no boundary — a
renderer that threw exited the process, exit code 1. It is the same shape as the CORS predicate
crash above and easier to reach: not a cross-origin request, but *any* request that produces an
error. The renderer produces the 404 too, so an app with a custom renderer and no matching route
was one request away from exiting.
It was also the worst-timed crash there was, since the renderer only runs once something has
already gone wrong: an error occurs, the code written to report it fails, and instead of a
degraded report the server ends. A renderer that throws now falls back to the built-in rendering —
which is exactly what the option overrides — so the original error still gets its response, and
the renderer's own failure is logged separately, naming both.
- **A stream's lifecycle is reported on every runtime, and joins back to its request.** `stream:open`,
`stream:close` and `stream:error` were emitted only by the Node adapter. Every Fetch runtime — Deno,
Bun, workerd, and `app.fetch()` on Node — emitted none of them and broke the response with a
transport error instead of writing the encoder's error frame. Both halves were silent: a consumer
counting `stream:error` saw zero on three of the four runtimes while streams were failing normally,
and the client got a truncated body indistinguishable from a clean end of stream. The Fetch path now
emits all three and frames the error before closing cleanly, which is what the Node adapter always
did and the better answer for the client — an SSE consumer that received an `error` event knows what
happened, where a dropped connection tells it nothing.
All three events now also carry the opening request's `requestId` and `traceId`, plus a bounded
`route`. `src/http/core.ts` had documented them as carrying the id since the stream landed; they
never did. The split they exist for is deliberate — a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so `request:end` fires at the handler's return
and hour-long connections stay out of the same latency distribution as 2ms replies — but it only
works if the two can be *joined*, and without the id an exporter could not say which request opened
the connection still holding a slot. A WebSocket upgrade correlates itself: it is an HTTP request
with headers like any other, so it adopts a gateway's `x-request-id` rather than opening a second
identity, and carries `transport: 'ws'`.
## [26.8.0-beta.1] - 2026-08-19
### Added
- **Observability: a correlated lifecycle event stream and an injectable logger.** Every request is
given an id — an incoming `x-request-id` is adopted rather than replaced — and every event of that
request carries it, alongside the matched route _pattern_ (never the concrete URL, which would give
a metrics backend one label per distinct path). Each step reports its own duration. `createApp({
logger })` accepts any object with `debug`/`info`/`warn`/`error`; the default writes structured JSON,
or a readable line on a TTY, decided once at boot. Nothing in core writes to `console`, enforced by a
lint rule rather than by intention. `createApp({ logRequests: true })` logs one line per request, off
by default. New exports: `Logger`, `LogLevel`, `LogFields`, `createDefaultLogger`,
`withConsoleFallback`, `logRequests`, `LifecycleEvent`, `EventPayload`, `Correlation`.
No metrics registry and no OpenTelemetry exporter in core — those live outside it, because core
keeps one runtime dependency. A `traceparent` header is carried through untouched for an exporter to
interpret; core implements no propagation spec. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
- **A bounded `close()` on the Deno and Bun adapters**, and `createApp({ shutdownTimeoutMs })` for the
Node one. `app.close()` returns at its no-server guard on Deno and Bun, so the deadline lives on the
server `serveDeno()`/`serveBun()` returns. One difference the deadline cannot hide: Node and Bun
force the remainder shut, while Deno cannot — aborting a server that is already draining throws from
Deno's own listener, so there the deadline bounds how long `close()` waits, not when connections die.
- Shutdown is now an extension point. A `@Provider` may declare `dispose()`, a plugin may call
`api.onShutdown(fn)`, and an application may pass `createApp({ hooks: [{ onShutdown }] })` — three
doors into one registry, so an app closing a connection no longer writes `process.on('SIGTERM')`
by hand. Callbacks are **awaited**, unlike `bus.on` listeners, and take no arguments: whatever
needs closing is already in the closure that registered it.
They run in reverse boot order, so a `cache` that needs `db` closes before the `db` it is holding.
A failing teardown is logged and the rest still run — one broken callback must not leave the
process up. Everything happens inside `close()`'s existing deadline; `createApp({ teardownTimeoutMs })`
reserves a slice of that budget when a connection must get its chance to close, and is rejected at
boot if it exceeds `shutdownTimeoutMs`.
Node, Deno and Bun behave identically — on Deno and Bun the teardown runs from the `close()` on the
server `serveDeno()`/`serveBun()` returned. **The edge cannot participate**: workerd has no
shutdown to intercept, so anything that must be released belongs in the request that acquired it.
Nothing changes for existing code. `Plugin`'s signature is unchanged, `Hooks` methods are optional,
and `dispose()` is called only if present.
- `limits.maxConnections` changes Node's previously unlimited concurrent socket count to a
default cap of `1000`; values `<= 0` leave Node unlimited. Deno and Bun have no equivalent
runtime setting and require a platform or reverse-proxy connection cap.
### Changed
- **A request that crosses the mesh keeps its identity.** The RPC envelope now carries the caller's
`requestId` and `traceId`, and a teapot adopts them rather than opening a new investigation — the
same rule an incoming `x-request-id` already got, applied at the process boundary where a trace
matters most. It also carries `url`, so a proxied handler sees the path its caller asked for.
Both fields are **optional on the wire and the protocol version does not move**: `decode` validates
only what a frame type requires and passes extras through, so a teapot on an older green-tea
ignores them and keeps answering. That is degraded, not broken. The rule for when the version
_does_ move is now written next to the constant, because "bump on any breaking change" never said
what counts as breaking.
The remote-route envelope is also built explicitly instead of cast from the internal request
object, which had been putting `ip` and `protocol` on the wire — fields the protocol never
declared and a teapot could have come to depend on.
- **Boot waits for a teapot that is merely slow, and still fails for one that is absent.**
`createApp({ mesh: { bootTimeoutMs } })` gives a teacup a grace period — default `timeoutMs`, so
30s — in which a teapot that has not finished starting is retried with backoff. When it passes,
the boot still fails, because a provider the graph depends on is not optional: booting without it
would only move the failure to the first request, where it becomes a caller's 503 instead of the
deploy's error. `bootTimeoutMs: 0` restores a single attempt.
**A refusal is not retried.** A wrong secret or a protocol-version mismatch is the teapot's
decision and will be the same decision in thirty seconds, so it fails immediately rather than
spending the whole budget to reach an identical error. The two are told apart by whether the
socket ever opened — a peer that accepted the connection and then hung up rejected us on purpose;
one that never accepted it may simply not be listening yet.
Every retry is logged _and_ emitted as the new `mesh:boot:retry` lifecycle event, so a slow boot
is visible to whatever collects events and not only to whoever is watching a terminal.
- **`.` and `..` in a request path are now resolved rather than 404'd.** `GET /public/../admin` reaches
a route declared as `/admin`, and `%2e` counts as a dot, so the encoded spelling cannot reach a route
the plain one resolves away from. This is a **behaviour change on Node only**, and it exists to end a
divergence: Deno, Bun and Workers resolve dot segments inside the `Request` constructor before the
framework sees anything, so the same bytes on the wire already reached different routes depending on
where you deployed. Rejecting them — the stricter option, and what this module does for `//` — is not
implementable on three of the four runtimes. If a proxy or WAF in front of you matches on the literal
path, note that it sees `/public/...` where the application now routes `/admin`.
### Fixed
- **A mesh export that carried behaviour arrived as `{}`, with HTTP 200 and no warning.** The wire is
JSON, so a value with methods — a connection pool, a client, a `Map` — lost everything but its
shape in transit. What reached the caller was an object: truthy, passing any `if (db)` check, and
missing every method, so the failure surfaced as `db.query is not a function` at a call site
arbitrarily far from the export that caused it.
A teapot now refuses to send one, on the side that still holds the real value, with a message
naming the token and what sat where: `mesh cannot transport 'db': result.db is a Pool instance`.
The check is an allowlist — primitives, plain objects, arrays — so `Date` is refused too, since it
would arrive as a string rather than the type the caller declared, which is the same silent
difference in a smaller costume. It is bounded by a scan budget, so a large legitimate payload is
never turned into an error by the cost of checking it.
**This is a constraint the documentation never stated:** a mesh export carries _data_, never
behaviour. Export what a handle produces, not the handle.
- **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for
the life of the process: every RPC answered 503 until the teacup was restarted, so deploying a
teapot forced a restart of every teacup that depended on it, and boot order became load-bearing.
Links now reconnect with exponential backoff and jitter (500ms doubling to 30s), tunable through
`mesh: { reconnect: { initialDelayMs, maxDelayMs } }` and disabled with `reconnect: false`.
`close()` is terminal — a link the application hung up on never reconnects, so `app.close()` cannot
leave a process that refuses to exit.
A returning teapot whose manifest no longer exports something the graph was validated against at
boot is **refused** rather than adopted, named by `mesh: { onManifestChange: 'refuse' }`, which is
the default and currently the only policy. The link keeps retrying, since a partial deploy may
still restore it, and logs the refusal once per distinct manifest rather than once per attempt.
Serving against a manifest that no longer backs the graph would surface as a 500 that looks like
application code. Extra exports in a returning manifest are ignored: the graph is fixed at boot.
This 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.
Mesh remains **alpha** and behind `experimental: true`.
- **`mesh:rpc:error` reported the wire id where every other emitter reports a name.** A failing
remote call emitted `name: "0"` — the per-link request counter — so the teacup's event could not be
lined up with the teapot's event for the same failure. It now names the token or route.
- **A teapot now bounds its own handshake and caps the size of a control frame.** The teacup has
always timed out its side; the teapot had no equivalent, so an unauthenticated peer could hold a
socket open forever by simply never sending `hello`. And `decode` runs `JSON.parse` on
peer-controlled input _before_ authentication, with no ceiling below whatever the WebSocket layer
allowed — 100 MiB under the `ws` package's defaults. Frames above 4,000,000 characters are now
refused with close code 1009, sized above the 1 MB default body limit a legitimate RPC can carry.
- **A `ws://` teapot on a non-loopback host now warns at boot.** The shared secret travels verbatim
in the `hello` frame, so an unencrypted link puts it in front of anyone on the path. A warning
rather than a refusal, since a private network doing its own mutual TLS is a real deployment and
green-tea cannot tell the two apart.
- **Buffered response bodies are narrowed to what the host runtime's `Response` accepts.** A Node
`Buffer` is a `Uint8Array` at runtime but its declared backing store admits `SharedArrayBuffer`, which
`BodyInit` does not — so Deno's types rejected it. This was a real typing hole on the `app.fetch`
path, which is the path Deno, Bun and the edge all use, rather than a JSR formality.
- **`close()`'s shutdown timer is armed before `finish()` is referenced.** The previous ordering relied
on `server.close(cb)` deferring, which is Node's behaviour rather than a guarantee to us, and left a
`ReferenceError` waiting in the shutdown path for whoever changed it.
## [26.8.0-beta.0] - 2026-08-02
### Added
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
@@ -36,14 +401,14 @@ npm treats versions as semver and semver forbids leading zeros.
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot _and_ teacup, in any combination
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
`nodejs_compat` does not provide.
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
The teapot checks the version *before* the secret — a skewed peer is not an auth failure.
The teapot checks the version _before_ the secret — a skewed peer is not an auth failure.
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
(`retry-after`, `etag`, …) without a special case in the error renderer.
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
@@ -59,6 +424,7 @@ npm treats versions as semver and semver forbids leading zeros.
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
### Fixed
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
@@ -94,6 +460,7 @@ npm treats versions as semver and semver forbids leading zeros.
`request:step:leave`.
### Changed
- Root, runtime-only, and website dependency audits are clean after supported package updates and
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
GitHub OIDC release workflow audits immediately before its publish gate.
@@ -118,6 +485,7 @@ First public beta, published under the npm `beta` dist-tag. The API may still
change before the stable release.
### Added
- **Transport security** — native TLS termination (https/wss), CORS with a
guarded preflight and credentials-safe origins, secure-by-default response
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
@@ -159,6 +527,7 @@ change before the stable release.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
[26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
+1 -1
View File
@@ -148,7 +148,7 @@ npm run build
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
- Keep runtime dependencies at zero beyond `reflect-metadata`.
- A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package.
- New public API needs a doc note in `README.md`.
- New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page.
- If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not.
On GitHub, workflows do not run on pull requests from forks until a maintainer approves them, so your first push may sit without any checks for a while. That is not a rejection.
+47 -8
View File
@@ -7,8 +7,13 @@
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
<p align="center">
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
<b>Declare intent. Derive execution.</b><br />
You declare what each step <b>needs</b> and <b>produces</b>; green-tea derives the order,<br />
validates the wiring before it serves traffic, and runs only the slice each route requires.
</p>
<p align="center">
<i>Less infrastructure in your application. Less infrastructure in your head.</i> 🍵
</p>
---
@@ -53,7 +58,33 @@ npm install busboy # multipart/form-data file uploads
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
## Who does the work?
Every backend has the same set of infrastructure decisions. The question is which side of the
`import` they live on.
| Decision | Owned by |
|---|---|
| Execution order | green-tea — derived from `needs`/`provides`, never maintained by hand |
| Dependency validation | green-tea — boot fails when nothing provides a key |
| Which steps a route runs | green-tea — the graph slice its handler actually depends on |
| Streaming mechanics — framing, backpressure, cleanup, disconnects | green-tea |
| OpenAPI projection | green-tea — from the same metadata that runs the app |
| Secure transport defaults | green-tea — headers, CORS, TLS |
| Runtime serving boundary | green-tea — `listen`, `fetch`, `upgrade` per runtime |
| Shutdown sequencing | green-tea — drain, then teardown, inside one deadline |
| **Business rules** | **you** |
That division is the whole design, and it is why `reflect-metadata` is the only runtime dependency:
the goal is not a small number for its own sake, it is **fewer moving parts your team has to
understand, upgrade, coordinate and debug**. A framework that owns less pushes the difference into
your application, where it becomes your maintenance instead of disappearing.
Automated does not mean invisible. `app.explain()` prints the ordered chain, `app.graph()` renders
the live graph, and `app.openapi()` projects the same metadata — the graph is not documentation drawn
after the fact, it is the structure green-tea validates and executes.
## Real-time is a primitive, not a second framework
@@ -98,9 +129,10 @@ class Live {
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
## Batteries included — still one dependency
## What the foundation already carries
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
The parts a real API needs, owned by the framework rather than assembled in your application — and
without growing the runtime dependency tree past `reflect-metadata`:
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
@@ -109,9 +141,11 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. `app.close()` is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -252,11 +286,16 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
## Docs & development
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs); a change to public API here needs a matching change there, because nothing fails when the two disagree.
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs).
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
> **Changing public API? The docs are a separate repository now, and nothing tells you when you break them.**
> [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) imports nothing from here, so no build fails and no test turns red when a guide describes an API that no longer exists. **A pull request that changes public API updates the page documenting it, in the same pull request.** This is a rule rather than a check because no check exists yet — issue #18 is what a stale page looks like from a user's side, and that happened while both still lived in this repository.
```bash
npm install
npm test # vitest (Node only) — the fast loop, ~2s
+270
View File
@@ -0,0 +1,270 @@
/**
* Compares green-tea against an earlier green-tea, on one box, in one sitting.
*
* `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release
* actually has to pass: **did the last N commits cost anything.** It is a different measurement and
* it needs a different setup, because comparing today's numbers against a table generated weeks ago
* compares two machines-in-a-mood, not two versions.
*
* Usage:
*
* git worktree add /tmp/base v26.8.0-beta.1
* ln -s "$PWD/node_modules" /tmp/base/node_modules
* AB_BASE=/tmp/base npm run bench:compare
*
* The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has
* not moved between the two revisions — check that first, or the comparison is measuring a
* dependency bump.
*
* Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100),
* `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json).
*/
import autocannon from 'autocannon';
import { spawn } from 'child_process';
import { writeFileSync } from 'fs';
const DURATION = Number(process.env.AB_DURATION ?? 10);
const ROUNDS = Number(process.env.AB_ROUNDS ?? 3);
const CONNS = Number(process.env.AB_CONNS ?? 100);
const HEAD = process.cwd();
// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables.
const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare';
const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare';
function requireBase(): string {
const base = process.env.AB_BASE;
if (base) return base;
console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.');
process.exit(1);
}
const BASE = requireBase();
interface Case {
name: string;
path: string;
method?: 'GET' | 'POST' | 'OPTIONS';
body?: unknown;
headers?: Record<string, string>;
env?: Record<string, string>;
}
const ORIGIN = { origin: 'http://bench.example' };
const CASES: Case[] = [
{ name: 'hello', path: '/hello' },
{ name: 'param', path: '/users/42' },
{ name: 'pipeline (3 steps)', path: '/pipeline' },
{ name: 'steps5', path: '/steps/5' },
{ name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } },
{ name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } },
// The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets
// the header measures the path around it rather than the path through it.
{ name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN },
{
name: 'preflight + cors predicate',
path: '/hello',
method: 'OPTIONS',
env: { GT_CORS: '1' },
headers: { ...ORIGIN, 'access-control-request-method': 'GET' },
},
// Route-table width. Every matcher cost scales with the number of candidates a request walks
// past, and the cross-framework table has six routes — so a change that saves work per candidate
// measures as noise there no matter how real it is. `/users/:id` is registered last and is not
// all-static, so it takes the full scan rather than the early exit a literal path gets.
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
];
const ONLY = process.env.AB_ONLY;
const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES;
function log(m: string): void {
process.stderr.write(`[compare] ${m}\n`);
}
async function boot(cwd: string, env: Record<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], {
cwd,
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env },
});
let stderr = '';
child.stderr.on('data', (d) => (stderr += d));
const port = await new Promise<number>((resolve, reject) => {
const t = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error(`no READY in 15s:\n${stderr}`));
}, 15000);
let buf = '';
child.stdout.on('data', (d) => {
buf += d;
const m = /READY (\d+)/.exec(buf);
if (m) {
clearTimeout(t);
resolve(Number(m[1]));
}
});
child.on('exit', (c) => {
clearTimeout(t);
reject(new Error(`exited ${c}:\n${stderr}`));
});
});
const kill = (): Promise<void> =>
new Promise<void>((r) => {
child.on('exit', () => r());
child.kill('SIGTERM');
setTimeout(() => {
try {
child.kill('SIGKILL');
} catch {
/* already dead */
}
}, 2000);
});
return { port, kill };
}
async function hit(port: number, c: Case, warmup = false): Promise<number> {
const r = (await autocannon({
url: `http://127.0.0.1:${port}${c.path}`,
connections: CONNS,
duration: DURATION,
pipelining: 1,
method: (c.method ?? 'GET') as 'GET',
headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers },
body: c.body ? JSON.stringify(c.body) : undefined,
})) as unknown as {
requests: { average: number };
non2xx?: number;
errors?: number;
timeouts?: number;
};
// A case whose route 404s still posts a req/s number, and a run whose connections all errored
// posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this
// case claims to send before believing any of it.
// Not on the warmup: a cold server drops a handful of connections from the opening burst, and
// absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise
// it exists to discard.
if (!warmup) {
const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0);
if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`);
if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`);
}
return r.requests.average;
}
const median = (xs: number[]): number => {
const s = [...xs].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
};
/**
* True when the two sides' sample ranges do not overlap at all.
*
* A weak signal on its own and stated as such: with three samples a pair of overlapping
* distributions separates by chance often enough to fool you, which it did the first time this was
* run. Treat a flagged row as "measure it again with more rounds", never as a result.
*/
const separated = (a: number[], b: number[]): boolean => {
const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)];
return x[0] > y[y.length - 1] || y[0] > x[x.length - 1];
};
/**
* Counts `cors.origins` invocations for one cross-origin GET and one preflight.
*
* Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved
* are invisible in req/s — but the option takes a function so it can be a lookup, and there the
* same saving is a network round trip.
*/
async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> {
const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server);
const base = `http://127.0.0.1:${port}`;
// The read carries no `Origin`, so asking cannot change the answer.
const read = async (): Promise<number> => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls;
try {
const before = await read();
await fetch(`${base}/hello`, { headers: ORIGIN });
const afterGet = await read();
await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } });
const afterPreflight = await read();
return { get: afterGet - before, preflight: afterPreflight - afterGet };
} finally {
await kill();
}
}
async function main(): Promise<void> {
const samples: Record<string, { base: number[]; head: number[] }> = {};
for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] };
for (let round = 0; round < ROUNDS; round++) {
// Alternate which side goes first. Thermal drift and background load over a half-hour run are
// real; alternating spreads them across both sides instead of charging them to whichever went
// second.
const order: Array<['base' | 'head', string]> =
round % 2 === 0
? [
['base', BASE],
['head', HEAD],
]
: [
['head', HEAD],
['base', BASE],
];
for (const [side, cwd] of order) {
for (const c of RUN_CASES) {
const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER);
try {
await hit(port, c, true); // warmup, discarded
const v = await hit(port, c);
samples[c.name][side].push(v);
log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`);
} finally {
await kill();
}
}
}
}
const rows = RUN_CASES.map((c) => {
const b = median(samples[c.name].base);
const h = median(samples[c.name].head);
return {
name: c.name,
base: b,
head: h,
delta: ((h - b) / b) * 100,
separated: separated(samples[c.name].base, samples[c.name].head),
samples: samples[c.name],
};
});
const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) };
writeFileSync(
process.env.AB_OUT ?? 'bench/compare-results.json',
JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2),
);
const f = (n: number): string => Math.round(n).toLocaleString();
console.log('\n| Scenario | base | head | Δ | |');
console.log('| --- | --- | --- | --- | --- |');
for (const r of rows) {
const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps';
console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`);
}
console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`);
console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+31 -1
View File
@@ -37,6 +37,8 @@ export interface RenderData {
scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; reqSec: number }[];
/** Optional: results captured before the runtime matrix existed still render. */
runtimes?: { runtime: string; scenario: string; reqSec: number }[];
}
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
@@ -124,6 +126,33 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
}
/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */
function renderRuntimes(runtimes: RenderData['runtimes']): string {
if (!runtimes?.length) return '';
const names = [...new Set(runtimes.map((row) => row.runtime))];
const scenarios = [...new Set(runtimes.map((row) => row.scenario))];
const at = (runtime: string, scenario: string): number | undefined =>
runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec;
const header = `| Scenario | ${names.join(' | ')} |`;
const divider = `| --- | ${names.map(() => '---').join(' | ')} |`;
const lines = scenarios.map((scenario) => {
const cells = names.map((runtime) => {
const value = at(runtime, scenario);
return value === undefined ? '—' : fmtInt(value);
});
return `| ${scenario} | ${cells.join(' | ')} |`;
});
const note =
'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' +
'never against the cross-framework tables above: those measure other frameworks on Node, and ' +
'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.';
return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n');
}
function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |';
const divider = '| --- | --- |';
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
}
export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data;
const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
return [
renderLeaderboard(scenarios),
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
'',
renderScenarios(scenarios),
renderStepScaling(stepScaling),
renderRuntimes(runtimes),
renderSecureCost(secureCost),
renderMethodology(),
].join('\n');
+206 -144
View File
@@ -1,7 +1,7 @@
{
"env": {
"date": "2026-07-07",
"commit": "fe1831a",
"date": "2026-09-02",
"commit": "8c5855c",
"node": "v22.22.2",
"os": "darwin",
"cpu": "Apple M4 Max (16 cores)",
@@ -10,8 +10,8 @@
},
"config": {
"conns": 100,
"duration": 5,
"runs": 3,
"duration": 10,
"runs": 5,
"warmup": 1,
"pipelining": 1
},
@@ -23,11 +23,11 @@
{
"framework": "raw-http",
"reqSec": {
"median": 115398.4,
"min": 114822.4,
"max": 115539.2,
"stddev": 310.09010876768724,
"cv": 0.0026905088104554075
"median": 119357.1,
"min": 118560,
"max": 120066.91,
"stddev": 484.9030139151553,
"cv": 0.0040636145553490976
},
"p50": 0,
"p99": 1,
@@ -36,24 +36,24 @@
{
"framework": "fastify",
"reqSec": {
"median": 86764.8,
"min": 86496,
"max": 87123.2,
"stddev": 256.9227813090051,
"cv": 0.002960121758353106
"median": 89096.73,
"min": 88864,
"max": 89207.28,
"stddev": 111.97759400880093,
"cv": 0.001257219726589825
},
"p50": 1,
"p99": 2,
"p99": 1,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 24366.4,
"min": 24283.2,
"max": 24417.6,
"stddev": 55.38455460585383,
"cv": 0.002273984274990166
"median": 24677.1,
"min": 24646.55,
"max": 24768.73,
"stddev": 43.02015834466458,
"cv": 0.0017417832565876405
},
"p50": 3,
"p99": 5,
@@ -62,39 +62,39 @@
{
"framework": "green-tea",
"reqSec": {
"median": 98092.8,
"min": 98054.4,
"max": 98668.8,
"stddev": 281.0175795212842,
"cv": 0.002859589501804015
"median": 87473.46,
"min": 86903.28,
"max": 87607.28,
"stddev": 280.84365746087286,
"cv": 0.0032155347907296527
},
"p50": 0,
"p99": 1,
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 21761.6,
"min": 21697.6,
"max": 21896,
"stddev": 82.67870880032535,
"cv": 0.0037952010918943873
"median": 21878.55,
"min": 21845.1,
"max": 21952.73,
"stddev": 41.00873789816055,
"cv": 0.0018731606009975037
},
"p50": 4,
"p99": 6,
"p999": 10
"p999": 9
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 95033.6,
"min": 94240,
"max": 95264,
"stddev": 438.6166536839312,
"cv": 0.00462452048886261
"median": 98039.28,
"min": 96072.73,
"max": 99680,
"stddev": 1215.4038343760499,
"cv": 0.012396669934655963
},
"p50": 1,
"p50": 0,
"p99": 1,
"p999": 2
}
@@ -107,11 +107,11 @@
{
"framework": "raw-http",
"reqSec": {
"median": 116332.8,
"min": 115974.4,
"max": 116409.6,
"stddev": 189.66281191162406,
"cv": 0.001631663389130871
"median": 120904.73,
"min": 119927.28,
"max": 121713.46,
"stddev": 658.0250991747977,
"cv": 0.005441723483024015
},
"p50": 0,
"p99": 1,
@@ -120,24 +120,24 @@
{
"framework": "fastify",
"reqSec": {
"median": 86278.4,
"min": 86137.6,
"max": 86764.8,
"stddev": 268.69839349476365,
"cv": 0.003110165492522174
"median": 88317.1,
"min": 87997.1,
"max": 88439.28,
"stddev": 182.99174422907566,
"cv": 0.00207430857941761
},
"p50": 1,
"p99": 2,
"p99": 1,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 23835.2,
"min": 23803.2,
"max": 24046.4,
"stddev": 107.89690552662897,
"cv": 0.004515472130491916
"median": 24200,
"min": 24157.82,
"max": 24259.64,
"stddev": 39.43298619176589,
"cv": 0.0016290899720752198
},
"p50": 3,
"p99": 5,
@@ -146,11 +146,11 @@
{
"framework": "green-tea",
"reqSec": {
"median": 93433.6,
"min": 93152,
"max": 93612.8,
"stddev": 189.6628119116206,
"cv": 0.002030662686635119
"median": 86594.91,
"min": 86368,
"max": 86880,
"stddev": 179.11650003279965,
"cv": 0.002068552609808656
},
"p50": 1,
"p99": 2,
@@ -159,27 +159,27 @@
{
"framework": "nestjs-express",
"reqSec": {
"median": 20955.2,
"min": 20948.8,
"max": 21201.6,
"stddev": 117.69157432317111,
"cv": 0.005594982425799189
"median": 21181.82,
"min": 21149.82,
"max": 21517.82,
"stddev": 139.0670808494951,
"cv": 0.006540068168697097
},
"p50": 4,
"p99": 6,
"p999": 11
"p999": 9
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 89312,
"min": 89235.2,
"max": 89529.6,
"stddev": 124.68598780759793,
"cv": 0.001395338811201841
"median": 91848.73,
"min": 91825.46,
"max": 92599.28,
"stddev": 296.55679952413783,
"cv": 0.00322222064035544
},
"p50": 1,
"p99": 2,
"p99": 1,
"p999": 2
}
]
@@ -192,11 +192,11 @@
{
"framework": "raw-http",
"reqSec": {
"median": 113491.2,
"min": 112531.2,
"max": 114809.6,
"stddev": 933.9810324031724,
"cv": 0.008220892102882115
"median": 118996.37,
"min": 118583.28,
"max": 119584,
"stddev": 341.82644850274596,
"cv": 0.002872466494470492
},
"p50": 0,
"p99": 1,
@@ -205,24 +205,24 @@
{
"framework": "fastify",
"reqSec": {
"median": 85024,
"min": 84512,
"max": 85177.6,
"stddev": 284.55819947576623,
"cv": 0.003351507726431956
"median": 86670.55,
"min": 86490.19,
"max": 86792.73,
"stddev": 97.03476704769095,
"cv": 0.0011197471063834074
},
"p50": 1,
"p99": 2,
"p99": 1,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 23950.4,
"min": 23902.4,
"max": 24011.2,
"stddev": 44.519758410046,
"cv": 0.0018585004345727763
"median": 24325.1,
"min": 24281.46,
"max": 24406.55,
"stddev": 50.44878456414985,
"cv": 0.002073096921615235
},
"p50": 3,
"p99": 5,
@@ -231,11 +231,11 @@
{
"framework": "green-tea",
"reqSec": {
"median": 84896,
"min": 84243.2,
"max": 85267.2,
"stddev": 423.2825796347192,
"cv": 0.004991414284012342
"median": 80078.55,
"min": 80026.19,
"max": 80375.28,
"stddev": 126.5427427235537,
"cv": 0.00157915416330658
},
"p50": 1,
"p99": 2,
@@ -244,24 +244,24 @@
{
"framework": "nestjs-express",
"reqSec": {
"median": 20824,
"min": 20804.8,
"max": 20878.41,
"stddev": 31.17605954717337,
"cv": 0.001496278247605678
"median": 20872,
"min": 20800.73,
"max": 20940.37,
"stddev": 44.78034640330492,
"cv": 0.0021458031999967474
},
"p50": 4,
"p99": 6,
"p999": 11
"p999": 9
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 87328,
"min": 86867.2,
"max": 87660.8,
"stddev": 325.38753646827104,
"cv": 0.0037278603866430907
"median": 89527.28,
"min": 87572.37,
"max": 90027.64,
"stddev": 867.875358507201,
"cv": 0.009726340137622384
},
"p50": 1,
"p99": 2,
@@ -276,24 +276,24 @@
{
"framework": "raw-http",
"reqSec": {
"median": 100140.8,
"min": 99846.4,
"max": 100294.4,
"stddev": 185.88177843875883,
"cv": 0.0018570746103533369
"median": 104288,
"min": 103776,
"max": 104916.37,
"stddev": 371.6125197245094,
"cv": 0.0035614220793380035
},
"p50": 0,
"p99": 1,
"p999": 2
"p999": 1
},
{
"framework": "fastify",
"reqSec": {
"median": 63721.6,
"min": 63574.4,
"max": 63760,
"stddev": 79.99288857281053,
"cv": 0.0012560645345785087
"median": 65905.46,
"min": 65725.1,
"max": 66366.55,
"stddev": 217.1439762369652,
"cv": 0.0032914527300013986
},
"p50": 1,
"p99": 2,
@@ -302,53 +302,53 @@
{
"framework": "express",
"reqSec": {
"median": 20097.6,
"min": 20056,
"max": 20174.41,
"stddev": 49.04789518646266,
"cv": 0.0024390608203285337
"median": 20297.46,
"min": 20157.82,
"max": 20413.82,
"stddev": 99.50819415505447,
"cv": 0.004902635960088364
},
"p50": 4,
"p99": 6,
"p999": 12
"p999": 10
},
{
"framework": "green-tea",
"reqSec": {
"median": 77177.61,
"min": 77126.4,
"max": 77254.4,
"stddev": 52.602458962379814,
"cv": 0.0006815013839797027
"median": 70298.19,
"min": 68971.64,
"max": 70606.55,
"stddev": 704.8749988359651,
"cv": 0.01008804689681251
},
"p50": 1,
"p99": 2,
"p999": 2
"p999": 3
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 18856,
"min": 18852.8,
"max": 19067.2,
"stddev": 100.32338821143516,
"cv": 0.005301010367660728
"median": 18787.64,
"min": 18684.37,
"max": 18861.82,
"stddev": 57.13389375843402,
"cv": 0.0030419312672842124
},
"p50": 5,
"p99": 7,
"p999": 30
"p999": 10
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 59145.6,
"min": 59004.8,
"max": 59376,
"stddev": 153.00625985741647,
"cv": 0.002585636725423652
"median": 63317.82,
"min": 62453.82,
"max": 63746.91,
"stddev": 543.811870536126,
"cv": 0.00860786685722159
},
"p50": 1,
"p99": 3,
"p99": 2,
"p999": 3
}
]
@@ -358,27 +358,89 @@
{
"path": "/steps/0",
"steps": 0,
"reqSec": 92281.6
"reqSec": 88107.64
},
{
"path": "/steps/3",
"steps": 3,
"reqSec": 81529.61
"reqSec": 79950.55
},
{
"path": "/steps/5",
"steps": 5,
"reqSec": 71993.61
"reqSec": 74126.55
}
],
"secureCost": [
{
"label": "security:false (parity)",
"reqSec": 98092.8
"reqSec": 87473.46
},
{
"label": "security:true (default)",
"reqSec": 92998.4
"reqSec": 83773.1
}
],
"runtimes": [
{
"runtime": "node",
"scenario": "JSON hello (overhead)",
"reqSec": 90976
},
{
"runtime": "node",
"scenario": "Route param",
"reqSec": 88904.73
},
{
"runtime": "node",
"scenario": "Pipeline (3 steps)",
"reqSec": 82045.1
},
{
"runtime": "node",
"scenario": "POST JSON + validation",
"reqSec": 72235.64
},
{
"runtime": "deno",
"scenario": "JSON hello (overhead)",
"reqSec": 153408
},
{
"runtime": "deno",
"scenario": "Route param",
"reqSec": 146368
},
{
"runtime": "deno",
"scenario": "Pipeline (3 steps)",
"reqSec": 136256
},
{
"runtime": "deno",
"scenario": "POST JSON + validation",
"reqSec": 106661.82
},
{
"runtime": "bun",
"scenario": "JSON hello (overhead)",
"reqSec": 131674.19
},
{
"runtime": "bun",
"scenario": "Route param",
"reqSec": 126909.1
},
{
"runtime": "bun",
"scenario": "Pipeline (3 steps)",
"reqSec": 117489.46
},
{
"runtime": "bun",
"scenario": "POST JSON + validation",
"reqSec": 95124.37
}
]
}
+74 -3
View File
@@ -1,17 +1,30 @@
import autocannon from 'autocannon';
import { spawn, execSync } from 'child_process';
import os from 'os';
import { writeFileSync } from 'fs';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
/** Hand-written notes start here and are carried across regenerations verbatim. */
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
const SMOKE = process.env.BENCH_SMOKE === '1';
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
/** Whether a runtime is on PATH. */
function which(cmd: string): boolean {
try {
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`);
}
@@ -23,11 +36,25 @@ interface RunResult {
p999: number;
}
/**
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
* are handed to their own runtime, which is the whole point of measuring them.
*/
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
// missing flag fails as a boot timeout that reads like a framework problem.
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
bun: (file) => ({ cmd: 'bun', args: [file] }),
};
async function spawnServer(
name: string,
extraEnv: Record<string, string> = {},
runtime: 'node' | 'deno' | 'bun' = 'node',
): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
const child = spawn(cmd, args, {
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
});
let stderr = '';
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
}));
const stepScaling: RenderData['stepScaling'] = [];
const secureCost: RenderData['secureCost'] = [];
const runtimes: RenderData['runtimes'] = [];
for (const fw of frameworks) {
log(`booting ${fw}`);
@@ -145,6 +173,42 @@ async function main(): Promise<void> {
}
}
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
// fastify-on-Node would read as a comparison nobody made.
//
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
// runtime is not installed — a contributor without Bun should still get every other table.
for (const { runtime, server } of [
{ runtime: 'node', server: 'green-tea-node' },
{ runtime: 'deno', server: 'green-tea-deno' },
{ runtime: 'bun', server: 'green-tea-bun' },
] as const) {
if (runtime !== 'node' && !which(runtime)) {
log(`skipping ${runtime}: not installed`);
continue;
}
log(`booting green-tea on ${runtime}`);
try {
const { port, kill } = await spawnServer(server, {}, runtime);
try {
for (const s of SCENARIOS) {
const runs = await measure(port, s.path, s.method, s.body);
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
}
} finally {
await kill();
}
} catch (error) {
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
// of the run over.
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
}
}
const commit = execSync('git rev-parse --short HEAD').toString().trim();
const data: RenderData = {
env: {
@@ -160,8 +224,15 @@ async function main(): Promise<void> {
scenarios: scenarioBlocks,
stepScaling,
secureCost,
runtimes,
};
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
// Everything below the marker is written by hand and survives a re-run. The generated tables
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
// history this file exists to keep gets lost a second time.
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
log('wrote BENCHMARKS.md + bench/results.json');
}
+61
View File
@@ -0,0 +1,61 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+84
View File
@@ -0,0 +1,84 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
type Ctor = new (...args: any[]) => any;
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
// Filler routes, so the width of the route table becomes a dimension the harness can see.
//
// Every matcher cost discussed for this file — the specificity scan, the per-candidate
// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate
// routes a request has to walk past. At the six routes the cross-framework table uses, all of them
// measure as noise, which says nothing about them and everything about the instrument. `/users/:id`
// is declared last so a request for it pays the full scan.
function fillerRoutes(count: number): Ctor[] {
return Array.from({ length: count }, (_, i) => {
@Route(`/filler${i}`)
class Filler {
@Get('/:a/:b') ab(@param('a') a: string) {
return { a };
}
}
return Filler as Ctor;
});
}
const EXTRA = Number(process.env.GT_ROUTES ?? 0);
@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+47
View File
@@ -0,0 +1,47 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
// Same BenchModule as green-tea.ts, but loaded from `dist/` rather than `src/`.
//
// The runtimes table exists to vary the runtime. The Deno and Bun servers import the built bundle
// because that is the only form those runtimes can load here, so a Node row reading `src/` through
// tsx would vary the load form at the same time and the table would answer neither question.
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/0') steps0() { return { hello: 'world' }; }
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
async function main(): Promise<void> {
const server = await app.listen(0);
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
console.log(`READY ${(server.address() as { port: number }).port}`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.9.0-beta.1",
"license": "MIT",
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
@@ -241,6 +241,21 @@ Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`.
The split trades CI coupling for drift risk: docs and code can now disagree without anything failing. #18 exists precisely because docs fell behind an API change. Decide what catches that — a link check against the published package, a docs job triggered from core releases, or an explicit accepted risk written down. Do not leave it unstated.
**Resolved 2026-08-17: accepted risk, stated where the rule is read rather than where it is published.** The first pass put it in both READMEs and stopped there, which satisfies the letter of "do not leave it unstated" and little else — the core README's copy sits in *Docs & development*, a section a user reads and a contributor changing an API does not.
What governs behaviour is `AGENTS.md:83` and the pre-PR checklist in `CONTRIBUTING.md`, both of which already carried *"New public API needs a note in `README.md`"* — written before the split and never updated for it, so the two documents that a contributor (or an assistant) actually reads mid-change said nothing about the new repository. Both now name it and say why the rule exists, since a rule without its reason is the first one dropped under time pressure.
**The link check was prototyped and then rejected, on measurement rather than taste.** It had been recommended here as the one worth building; building enough of it to decide showed otherwise.
- Every symbol the pages import is real: **24 distinct imports from `@green-tea/core` across 25 pages, all present** among the package's 101 exports. No bug for it to find today.
- More decisively, **an import check could not have caught #18**. That issue was *"docs still describe `close()` without the timeout"* — the method existed; the **option** was undocumented. Imports are the part that does not drift. Options, option shapes and method signatures are.
- Extending it to options and methods was tried and produced **17 findings, all 17 false** — a regex cannot tell a nested `tls: { key, cert }` from a top-level option, `app.example.com` in a CORS example from an `app.*` call, or prose describing Express's `app.use()` from a green-tea API. A check with that signal-to-noise trains people to ignore it, which is worse than not having one.
- What would genuinely catch #18's class is **type-checking the code blocks** (twoslash / Expressive Code). That requires the documentation repository to depend on `@green-tea/core` and its examples to be complete and compilable — many are deliberately fragments. It buys the guarantee back by spending exactly the independence this split was for.
So the accepted risk stands, now as an informed choice rather than a default. A **docs job triggered from core releases** was the other option and remains the weaker one: it fires after the API has already shipped.
One page is covered by more than a rule: `test/circuit-breaker-recipe.test.ts` executes the recipe published in `guides/circuit-breaker.md`. That is one page of twenty-five, and is not a substitute for the check above.
---
## Phase 4.5: Move the JSR gate off the tag — **run this before Task 2.5's code**
@@ -122,10 +122,12 @@ Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**:
`timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for.
- Drain runs first. Teardown runs after, within the same budget.
- `teardownTimeoutMs` is optional and defaults to `timeoutMs` — no separate cap, teardown may use whatever the drain left.
- Setting it lower **reserves**: the drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one.
- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
- `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped.
An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement.
Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run.
---
@@ -72,7 +72,7 @@ Tests: `dispose()` is called; a provider without one is skipped; `cache` needing
Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining.
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` defaults to `timeoutMs`; when set lower it **reserves**, so the drain is bounded to `timeoutMs − teardownTimeoutMs` and teardown is guaranteed its slice. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
`closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering.
@@ -0,0 +1,82 @@
# A teapot that may be absent, declared per teapot
**Status:** planned, 2026-08-18
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
**Mesh stays alpha.**
## The decision
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
away is a degraded checkout; an authorization provider being away is not a degraded anything.
```ts
mesh: {
teapots: [
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
{ url: authUrl, secret }, // 'fail' — the default
],
}
```
## Why `expects` is required for `'degrade'`, and not inferred
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
validation fails the boot anyway — degrading would fail identically, just later.
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
loudly.
It also pushes the developer to state what a service depends on, which is the same discipline the
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
`expects`, naming the teapot.
## Decisions
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
and throws `503`, naming the token and the teapot it belongs to.
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
simply do not exist locally, because a route needs a method and a pattern we were never told. A
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
silent.
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
logged and emitted.
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
instead of a boot manifest.
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
wrong, not a reason to write a second one.
## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
`expects`.
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
3. `degraded()` reporting per D3, plus the warn and the event.
4. Background attempt loop per D4, and adoption per D5/D6.
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
refused, and `'degrade'` without `expects` fails at `createApp`.
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
## Size
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
three runtimes. Not a follow-up to squeeze into another change.
@@ -0,0 +1,102 @@
# Mesh reconnection, with a refusing manifest policy
**Status:** planned, 2026-08-18
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
unusable in production; it does not move the label, because the label is a statement about how much
we know, and we will know more once this runs somewhere real.
## The problem
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
serially and throwing on any failure (`src/app/index.ts:631`):
- a teapot down at boot → the teacup does not start;
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
load-bearing. That is a worse operational property than any gap currently written in the docs.
## Vocabulary
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
words must not be used interchangeably in code, CHANGELOG or docs.
## Decisions
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
`connectLink` becomes "establish, then keep established".
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
configured" with "this dependency is temporarily away".
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
heartbeat, so reconnection never holds a process open on its own.
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
Rationale: the graph was validated at boot against the old manifest and is already running. A token
that vanished cannot be validated away after the fact, and serving requests against a manifest that
no longer backs the graph is how you get a 500 that looks like application code.
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
not spliced in. Documented, not silent.
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
place to be breaking.
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
provider is resolved once at boot and frozen into the container as `() => value`
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
call on the reconnect path, where its failure has nowhere to go. This closes the documented
"app-scope export survives its teapot with a stale value" gap.
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
inline in the reconnect handler — that function is what reconciliation will reuse.
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
cannot exit.
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
not a wait for `timeoutMs`.
## Tasks
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
`mesh:connect` on success (existing events; no new bus contract in alpha).
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
Reconnect defaults **on**. Validate at boot like the other mesh options.
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
where a swappable socket can break.
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
a defect, not a feature.
## Not in this plan
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.9.0-beta.1",
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
@@ -102,6 +102,7 @@
"complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts",
"bench:compare": "tsx bench/compare.ts",
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true"
},
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// Prints one version's section of CHANGELOG.md, for a GitHub release body.
//
// Reads the current file rather than the tag's copy on purpose: the changelog is the record, so a
// correction to an old entry should reach the release that describes it.
//
// Usage: node scripts/changelog-section.mjs <version> [tag]
// The optional tag makes relative links absolute — a release body resolves them against the release
// page, not the repository, and pinning to the tag keeps the link on the file as that version had it.
import { readFileSync } from 'node:fs';
const REPO = 'Expressive-Tea/green-tea';
const [version, tag] = process.argv.slice(2);
if (!version) {
console.error('usage: changelog-section.mjs <version> [tag]');
process.exit(2);
}
const lines = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8').split('\n');
const isHeading = (l) => l.startsWith('## [');
// The `[label]: url` block at the bottom of the file belongs to no section. Without this the last
// section swallows it, since nothing else comes after.
const isLinkRef = (l) => /^\[[^\]]+\]:\s+\S/.test(l);
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
if (start === -1) {
console.error(`no section for ${version}. Headings in CHANGELOG.md:\n${lines.filter(isHeading).join('\n')}`);
process.exit(1);
}
const rest = lines.slice(start + 1);
const stop = rest.findIndex((l) => isHeading(l) || isLinkRef(l));
const body = (stop === -1 ? rest : rest.slice(0, stop)).join('\n').trim();
const absolute = tag
? body.replace(/\]\(\.\/([^)\s]+)\)/g, `](https://github.com/${REPO}/blob/${tag}/$1)`)
: body;
console.log(absolute);
+457 -54
View File
@@ -1,8 +1,8 @@
import type http from 'http';
import { Bus } from '../bus';
import { Bus, type Events } from '../bus';
import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
@@ -12,6 +12,9 @@ import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocke
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import { installSignalHandlers } from '../http/signals-shutdown';
import type { Hooks } from './types';
import {
Ctor,
getModuleMeta,
@@ -27,7 +30,7 @@ import {
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, type Link } from '../mesh/link';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
@@ -38,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
type Runner = (ctx: any) => any;
@@ -48,11 +51,18 @@ interface Registry {
stepNodes: GraphNode[];
runners: Map<string, Runner>;
providerMeta: Map<string, { optional: boolean }>;
/**
* The `@Provider` instance behind each node, kept only so a `dispose()` can be reached.
*
* `collectProviders` used to build the instance and let it live on solely inside the runner's
* closure, which meant nothing could ever call a method on it again.
*/
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
routePlans: RoutePlan[];
exportedProviders: string[];
exportedSteps: string[];
exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void;
setRunner(name: string, runner: Runner, framework?: boolean): void;
}
/**
@@ -76,6 +86,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus;
onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
}
/**
@@ -86,6 +98,14 @@ interface PipelineDeps {
export function createApp(opts: {
modules: Ctor[];
plugins?: Plugin[];
/**
* Lifecycle participation without extending the graph.
*
* A plugin means "I want to add nodes"; someone who only needs to close a connection should not
* have to declare an extension they do not want. Methods are optional so later stages can join
* without a breaking change — only `onShutdown` exists today.
*/
hooks?: Hooks[];
mesh?: MeshConfig;
limits?: RequestLimits;
devGraph?: boolean;
@@ -111,6 +131,36 @@ export function createApp(opts: {
* where passing it per call is not an option.
*/
shutdownTimeoutMs?: number;
/**
* Milliseconds reserved out of the shutdown budget for teardown, in ms (default: none reserved).
*
* Teardown runs after the drain and inside the same `timeoutMs`, so `close()` never takes longer
* than the caller asked for. Left unset, the drain may use the whole budget and teardown gets
* whatever remains — possibly nothing. Set it when a connection *must* get its chance to close:
* the drain is then bounded to `timeoutMs - teardownTimeoutMs` and this slice is guaranteed.
*
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
*/
teardownTimeoutMs?: number;
/**
* Register `SIGINT`/`SIGTERM` to run `close()` and exit the process (default: `false`).
*
* Off by default because a library that installs process-wide handlers behind your back is worse
* than one that installs none — when the process exits is the application's call, not ours. Turn
* it on and the framework absorbs the last runtime difference an app otherwise has: `process.on`
* on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each.
*
* Leaving it off is a supported choice, not a gap — write the handler yourself if you want the
* control. What is *not* optional either way is that something calls `close()`: the teardown
* registry only runs from there, so a container `SIGKILL`ed after its grace period skips every
* `dispose()` the registry so carefully ordered, and reports nothing.
*
* Registered by `listen()`, `serveDeno()` and `serveBun()`, and taken back off by `close()` —
* so a *second* signal arriving mid-shutdown falls through to the platform default and ends the
* process at once. Ctrl-C twice is the way out of a teardown that is stuck; once is the way to
* let it finish.
*/
handleSignals?: boolean;
/**
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
*
@@ -158,8 +208,9 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry);
provideBuiltins(registry, logger);
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph.
@@ -180,7 +231,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -188,7 +239,7 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks);
finalize();
@@ -236,7 +287,7 @@ export function createApp(opts: {
registry,
opts.overrides,
() => orderedProviders,
{ runners, container, providerMeta, bus, logger },
{ runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
degradedProviders,
ready,
);
@@ -245,6 +296,7 @@ export function createApp(opts: {
const fetchOpts: HttpOptions = {
bus,
logger,
limits: opts.limits,
tls: opts.tls,
trustProxy: opts.trustProxy,
@@ -256,7 +308,7 @@ export function createApp(opts: {
};
const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
@@ -276,6 +328,7 @@ export function createApp(opts: {
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
bus,
logger,
limits: opts.limits,
streams,
tls: opts.tls,
@@ -288,15 +341,52 @@ export function createApp(opts: {
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
// After the socket is up, so a boot that throws never leaves a handler behind pointing at an
// app that never served.
handleSignals(close);
return server;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger);
// Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is
// load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app
// that closed itself and expected to exit would simply hang.
let removeSignalHandlers: (() => void) | undefined;
const clearSignalHandlers = (): void => {
removeSignalHandlers?.();
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
return closeApp(
server,
meshLinks,
streams,
options,
opts.shutdownTimeoutMs,
logger,
teardown,
opts.teardownTimeoutMs,
);
};
const handleSignals = <T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T => {
if (!opts.handleSignals) return closer;
const wrapped = ((options?: { timeoutMs?: number }) => {
clearSignalHandlers();
return closer(options);
}) as T;
removeSignalHandlers = installSignalHandlers(() => wrapped(), logger);
return wrapped;
};
return {
listen,
close,
handleSignals,
ready,
fetch: fetchFn,
upgrade: upgradeFn,
@@ -316,7 +406,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn
const setRunner = (name: string, runner: Runner) => {
const setRunner = (name: string, runner: Runner, framework = false) => {
if (!framework && RESERVED_TOKENS.has(name))
throw new Error(
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
);
if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner);
@@ -327,6 +422,7 @@ function emptyRegistry(): Registry {
stepNodes: [],
runners,
providerMeta: new Map(),
providerInstances: new Map(),
routePlans: [],
exportedProviders: [],
exportedSteps: [],
@@ -343,6 +439,7 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides);
const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
}
}
@@ -459,12 +556,40 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
return registry;
}
/**
* Builds the teardown registry, seeds it with the application's hooks, and validates the reservation.
*
* Hooks land before plugins, so the registry running in reverse tears plugins down before the hooks
* an application registered around them. Both go into the same list: one order, one failure policy.
*/
function buildTeardownRegistry(
hooks: Hooks[] | undefined,
teardownTimeoutMs: number | undefined,
shutdownTimeoutMs: number | undefined,
): TeardownRegistry {
const budget = shutdownTimeoutMs ?? 10_000;
// Rejected rather than clamped: a reservation larger than the budget it is carved from is a
// mistake in the caller's numbers, and quietly shrinking it would hide which of the two they got
// wrong — at boot, where there is time to fix it, rather than during a shutdown.
if (teardownTimeoutMs !== undefined && teardownTimeoutMs > budget) {
throw new Error(
`teardownTimeoutMs (${teardownTimeoutMs}) cannot exceed shutdownTimeoutMs (${budget}) — ` +
'it is reserved out of that budget, not added to it',
);
}
const teardown = new TeardownRegistry();
for (const hook of hooks ?? []) if (hook.onShutdown) teardown.add(hook.onShutdown);
return teardown;
}
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -475,22 +600,46 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
}
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry, logger: Logger): void {
/**
* Token names the framework owns. Declaring one is a boot error, not a silent override.
*
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
* That is the kind of thing that is discovered from a log line that never appeared.
*
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
*/
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
const builtin = (name: string, value: () => Record<string, unknown>): void => {
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
registry.providerMeta.set(name, { optional: false });
registry.setRunner(name, value, true);
};
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
// same object createApp holds, not a second one — core cannot depend on the graph for something
// it must use while the graph is still resolving.
if (!registry.runners.has('logger')) {
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
registry.providerMeta.set('logger', { optional: false });
registry.setRunner('logger', () => ({ logger }));
}
builtin('logger', () => ({ logger }));
if (registry.runners.has('rooms')) return;
const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
builtin('rooms', () => ({ rooms: roomsInstance }));
// The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
// not one.
//
// A subscription is not like the other injectables, and the difference is the scope that reaches
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
// `on` and `onShutdown` together, remains the right home for observation.
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
}
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -548,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) {
for (const need of plan.needs) {
if (allowed.has(need)) continue;
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
// news that it is not the same shape. Say why, where they are.
if (need === 'bus') {
throw new Error(
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
`that could reach it could also emit, and an observation channel anything can write to ` +
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
`which gets on() and onShutdown() together and is the right home for observation.`,
);
}
const hint = nearest(need, allowed);
throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
@@ -556,12 +720,102 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
}
}
/**
* Keep trying to reach a teapot until `bootTimeoutMs` passes, then give up and fail the boot.
*
* The grace exists because "the container is thirty seconds behind" and "the teapot does not
* exist" look identical for the first thirty seconds, and only one of them should stop a deploy.
* When the deadline passes it still throws: a provider the graph depends on is not optional, and
* booting without it would only move the failure to the first request, where it becomes a caller's
* 503 instead of the deploy's error.
*
* Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator
* watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever
* collects lifecycle events rather than only to whoever is reading a terminal.
*/
async function connectUntilDeadline(
mesh: MeshConfig,
bus: Bus,
logger: Logger,
attempt: () => Promise<Link>,
): Promise<Link> {
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
const deadline = Date.now() + budgetMs;
let delay = 500;
let attempts = 0;
for (;;) {
try {
return await attempt();
} catch (error) {
attempts += 1;
const remaining = deadline - Date.now();
// A refusal is the teapot's decision, not the network's, and it will be the same decision in
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
// identical error, so it fails now.
if (isPermanentRefusal(error)) {
logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`);
throw error;
}
// Rethrown as-is rather than wrapped: connectLink already says whether this was a refused
// handshake, a version mismatch or a timeout, and each sends you somewhere different.
if (remaining <= 0) {
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`);
throw error;
}
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
logger.warn(
`mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`,
);
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
delay = Math.min(delay * 2, 5_000);
}
}
}
/**
* Warn when a teapot's shared secret would cross a network in cleartext.
*
* The `hello` frame carries the secret verbatim, so `ws://` to anywhere but this machine puts it on
* the wire for anyone in the path to read. Loopback is exempt because there is no path.
*
* A warning rather than a refusal: a private network behind a service mesh that already does mutual
* TLS is a legitimate deployment, and green-tea cannot tell it apart from an exposed one.
*/
function warnIfCleartext(url: string, logger: Logger): void {
if (!url.startsWith('ws://')) return;
const host = url.slice('ws://'.length).split('/')[0].split(':')[0];
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return;
logger.warn(
`mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` +
'use wss:// unless the link already runs inside an encrypted network.',
);
}
/**
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
*
* Named and separate rather than inlined in the reconnect handler: this is the seam a future
* `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice.
*
* Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a
* network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection.
*/
function invalidateRemoteBindings(rebind: Array<() => void>): void {
for (const bind of rebind) bind();
}
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
registry: Registry,
logger: Logger,
container: Container,
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
@@ -569,13 +823,23 @@ async function spliceRemoteScopes(
try {
for (const teapot of mesh.teapots ?? []) {
const link = await connectLink({
warnIfCleartext(teapot.url, logger);
// Deferred so the reconnect callback can name this link's provider tokens, which are only
// known once its manifest arrives — the callback is registered before the link can drop.
const rebind: Array<() => void> = [];
const link = await connectUntilDeadline(mesh, bus, logger, () =>
connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange,
onReconnect: () => invalidateRemoteBindings(rebind),
logger,
bus,
});
}),
);
meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
@@ -584,6 +848,10 @@ async function spliceRemoteScopes(
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
registry.providerMeta.set(provider.name, { optional: false });
registry.setRunner(provider.name, provider.run);
// A remote app-scope value is resolved once at boot and frozen into the container, so it
// would keep answering from a cache the teapot no longer stands behind. Re-registering
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
}
for (const step of steps) {
@@ -633,7 +901,19 @@ async function spliceRemoteScopes(
method: route.method,
pattern: route.pattern,
transport: 'buffer',
handler: async (req) => route.handler(req as RequestEnvelope),
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}
}
@@ -657,8 +937,41 @@ function applyOverrides(overrides: Record<string, unknown> | undefined, registry
}
}
/** What a provider's boot produced: nothing to say, or the error it failed with. */
interface BootOutcome {
node: GraphNode;
error?: Error;
}
/** Boots one provider and registers its value. Never rejects — the caller decides what a failure means. */
async function bootProvider(
node: GraphNode,
deps: { runners: Map<string, Runner>; container: Container; bus: Bus },
): Promise<BootOutcome> {
const { runners, container, bus } = deps;
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
try {
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
bus.emit('boot:provider:ok', { name: node.name });
return { node };
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
return { node, error: error as Error };
}
}
/**
* Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn.
* Runs app-scoped providers level by level — concurrently within a level, sequentially between
* them; required failures abort, optional ones warn.
*
* The topo sort already proved nothing in a level can order anything else in it, so serializing a
* level only ever bought latency: an app paid the sum of its providers' boot times instead of its
* longest chain. Concurrency is the second thing the graph earns its users, after pruning, and the
* one a middleware chain structurally cannot offer.
*
* @returns The names of optional providers that failed and are running degraded (unregistered).
*/
async function bootProviders(
@@ -667,35 +980,45 @@ async function bootProviders(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
): Promise<string[]> {
const { runners, container, providerMeta, bus, logger } = deps;
const { providerMeta, providerInstances, teardown, logger } = deps;
const degraded: string[] = [];
for (const node of orderedProviders) {
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
for (const level of topoLevels(orderedProviders)) {
// Outcomes rather than rejections: a sibling that throws must not strand the ones that
// succeeded, or a provider that opened a pool would never get its dispose() registered.
const outcomes = await Promise.all(level.map((node) => bootProvider(node, deps)));
try {
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
bus.emit('boot:provider:ok', { name: node.name });
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
// Teardown in level order, not completion order. `orderedProviders` is topologically sorted and
// the registry runs in reverse, which is what gives dependants teardown before their
// dependencies for free — a guarantee that would have become luck if this followed whichever
// provider happened to settle first. Registered before the failure pass so a level that aborts
// the boot still leaves its successful siblings closeable.
//
// Skipped for a failure on purpose: a provider that threw never provided anything, and calling
// dispose() on a half-constructed one is how a teardown finds a null connection.
for (const { node, error } of outcomes) {
if (error) continue;
const instance = providerInstances.get(node.name);
if (instance?.dispose) teardown.add(() => instance.dispose!());
}
for (const { node, error } of outcomes) {
if (!error) continue;
if (!providerMeta.get(node.name)?.optional) {
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
throw new Error(`provider '${node.name}' failed: ${error.message}`);
}
// optional: warn, leave it unregistered; routes needing it fail at request time
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
degraded.push(node.name);
logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, {
provider: node.name,
error,
});
logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error });
}
}
@@ -717,6 +1040,8 @@ function makeAppBooter(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
@@ -759,7 +1084,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError } = deps.deps;
const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
@@ -770,7 +1095,14 @@ function buildMeshControl(
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
const context = await runSteps(steps, seed, bus);
// The caller's identity, adopted rather than replaced — the same rule an incoming
// `x-request-id` gets, applied at the process boundary where it matters most. No `route`:
// resolving a scope is not a route, and inventing one would put a token in a route label.
const context = await runSteps(steps, seed, bus, {
requestId: env.correlation?.requestId,
traceId: env.correlation?.traceId,
method: env.method,
});
return context[name];
};
@@ -791,7 +1123,15 @@ function buildMeshControl(
transformer: plan.transformer,
bus,
onError,
logger,
transport: plan.transport,
correlation: {
requestId: env.correlation?.requestId,
traceId: env.correlation?.traceId,
route: plan.pattern,
method: plan.method,
transport: plan.transport,
},
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
});
@@ -809,7 +1149,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError } = deps;
const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -828,6 +1168,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer,
bus,
onError,
logger,
transport: plan.transport,
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete
// paths gets one label per distinct URL, and that takes down the metrics backend.
@@ -1006,6 +1347,50 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
}));
}
/**
* Runs registered teardown, bounded so it cannot push `close()` past the budget it was given.
*
* Bounding lives here rather than in {@link TeardownRegistry} because the registry has no business
* knowing about deadlines — `closeApp` and `closeWithDeadline` each already own one, and a third
* implementation is how the three drift into different meanings of the same `timeoutMs`.
*
* A teardown that overruns is left running rather than awaited: the callback is someone else's code
* and there is no way to interrupt it, so the choice is between returning on time and waiting
* indefinitely. It resolves on its own timer for the same reason `closeWithDeadline` does.
*/
function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: number): Promise<void> {
if (teardown.size === 0) return Promise.resolve();
return new Promise<void>((resolve) => {
let settled = false;
// Armed before `finish` exists, for the reason spelled out in `closeApp` below: setTimeout
// cannot fire synchronously, so the forward reference to `finish` rests on a guarantee, while
// the reverse ordering would rest on `teardown.run().then()` deferring.
const timer = setTimeout(
() => {
if (settled) return;
logger.warn(`shutdown teardown exceeded its ${Math.max(0, budgetMs)}ms budget — returning without it`, {
budgetMs: Math.max(0, budgetMs),
});
finish();
},
Math.max(0, budgetMs),
);
timer.unref?.();
const finish = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
void teardown.run(logger).then(finish, finish);
});
}
function closeApp(
server: http.Server | undefined,
meshLinks: Link[],
@@ -1013,8 +1398,17 @@ function closeApp(
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
logger: Logger,
teardown: TeardownRegistry,
reservedMs: number | undefined,
): Promise<void> {
return new Promise((resolve) => {
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
const startedAt = Date.now();
// Unset reserves nothing: the drain may use the whole budget and teardown takes what is left.
// Set, it is carved out of the same budget rather than added to it, so `close()` still returns
// within `timeoutMs` — which is the whole reason the caller set that number.
const drainBudget = timeoutMs - (reservedMs ?? 0);
const drain = new Promise<void>((resolve) => {
// A mesh app booted through `app.fetch` has links but no server, and would leak every
// teapot connection otherwise — so links close before we even check for a server.
closeLinks(meshLinks);
@@ -1026,16 +1420,20 @@ function closeApp(
if (!server) {
if (options.timeoutMs !== undefined) {
logger.warn(
'close({ timeoutMs }) has no effect here — this app has no listen()ed server. On Deno ' +
'and Bun, call close() on the server serveDeno()/serveBun() returned; it takes the ' +
'same option. On the edge the platform owns the lifecycle.',
'close({ timeoutMs }) does not drain connections here — this app has no listen()ed ' +
'server, so it only bounds teardown. On Deno and Bun, call close() on the server ' +
'serveDeno()/serveBun() returned; it takes the same option and drains too. On the ' +
'edge the platform owns the lifecycle.',
);
}
// Falls through to teardown rather than returning from close(). An app served through
// `app.fetch` still booted its providers, so it still has connections that were opened and
// are owed a close — the transport being someone else's job does not make them not ours.
// Running teardown twice is safe: the registry drains once, whichever entry point is first.
return resolve();
}
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
let settled = false;
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
@@ -1056,7 +1454,7 @@ function closeApp(
// below — `engines` in package.json only guarantees >=18, so this matters.
server.closeAllConnections();
finish();
}, timeoutMs);
}, drainBudget);
timer.unref?.();
@@ -1072,6 +1470,11 @@ function closeApp(
for (const closeStream of streams) closeStream();
server.closeIdleConnections();
});
// Teardown runs after the drain and before close() resolves: an in-flight request may still be
// using the connection a teardown is about to close, so draining first is not an ordering
// preference. It gets whatever is left of the budget — at least the reservation, if one was made.
return drain.then(() => runTeardown(teardown, logger, timeoutMs - (Date.now() - startedAt)));
}
/** Best-effort close of every mesh link, ignoring individual failures. */
+53
View File
@@ -1,6 +1,7 @@
import type http from 'http';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { TeardownFn } from '../lifecycle';
import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata';
@@ -37,6 +38,15 @@ export interface Explain {
export interface App {
listen(port: number): Promise<http.Server>;
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
*
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
* their server, which is why the option is declared once on `createApp` and works on all three.
* Call it yourself only if you serve the app some other way.
*/
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
/**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
@@ -102,4 +112,47 @@ export interface MeshConfig {
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
*/
heartbeatMs?: number;
/**
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
*
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep.
*/
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/**
* What to do when a returning teapot's manifest no longer exports something the graph was
* validated against at boot (default: `'refuse'`).
*
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
* rather than left implicit so that arriving is additive rather than a change of default.
*/
onManifestChange?: 'refuse';
/**
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
* so 30s). Attempts use the same backoff as reconnection.
*
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
* has not settled — should not fail a deploy, and this is the grace for that. A teapot that is
* genuinely absent still fails the boot when the deadline passes, because a provider the graph
* depends on is not optional: booting without it would only move the failure to the first
* request, where it is somebody else's 503 instead of your deploy's error.
*
* `0` restores the old behaviour of a single attempt.
*/
bootTimeoutMs?: number;
}
/**
* Lifecycle participation for an application that does not want to be a plugin.
*
* Every method is optional, and the shape is an object rather than a single callback so later
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
*/
export interface Hooks {
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
onShutdown?: TeardownFn;
}
+11 -2
View File
@@ -117,9 +117,17 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.stop(false),
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.stop(false).then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
@@ -128,5 +136,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
runtime: 'bun',
}),
),
),
});
}
+102 -3
View File
@@ -1,4 +1,28 @@
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
/**
* Names of every lifecycle event the framework emits over the {@link Bus}.
*
* ### The request pair is a guarantee
*
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
* consumer may open per-request state on the first and close it on the second without checking
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
* does.
*
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
* every response shape so that the next one cannot break it quietly. The alternative — documenting
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
* exactly when an operator is reading it.
*
* ### `request:end` is terminal and universal; the others are additional
*
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
* the only one of these carrying the real status. **Count it, and nothing else.**
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
*/
export type LifecycleEvent =
| 'boot:provider:start'
| 'boot:provider:ok'
@@ -6,19 +30,34 @@ export type LifecycleEvent =
| 'request:step:enter'
| 'request:step:leave'
| 'request:step:error'
// A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately
// *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its
// connection may live for hours, so `request:end` fires at the handler's return and these three
// describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is
// what lets a consumer join the two rather than watch them as unrelated streams of events.
| 'stream:open'
| 'stream:close'
| 'stream:error'
| 'mesh:connect'
| 'mesh:disconnect'
| 'mesh:rpc:error'
// A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
// Separate from `mesh:disconnect`, which 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.
| 'mesh:boot:retry'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
| 'request:start'
| 'request:end'
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
// also a throw, which is a thing a status alone cannot express.
| 'request:failed'
| 'route:matched'
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
// misreport the other, and "no route ran" is the fact a consumer actually wants.
// misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
// no route either, and answers 200. Read the status from the `request:end` that follows.
| 'route:unmatched';
/**
@@ -27,8 +66,39 @@ export type LifecycleEvent =
*
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
* name, and requiring a shape they cannot fill would only mean inventing values for it.
*
* ### One failed request produces three events
*
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
* All three carry the same `requestId`, and the first implementation anyone writes 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: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
* outcome.
*
* The division of labour, which is the thing to build against:
*
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
* received. This is the request counter and the latency histogram.
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
* rendered `422` is also a throw. This is a separate error counter, not a second request
* counter.
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
*
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
* the outcome from `request:end` and only the message from `request:failed`.
*/
export interface EventPayload {
/**
* What the event is about, for a human reading a log line.
*
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
* which is bounded by construction.
*/
name: string;
scope?: string;
error?: unknown;
@@ -37,10 +107,23 @@ export interface EventPayload {
requestId?: string;
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
traceId?: string;
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */
/**
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
*
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
* that follows it: a single series for every path that was never a route, instead of a fallback
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
* starts with `/`.
*/
route?: string;
method?: string;
transport?: string;
/**
* The status the client received. Present on `request:end` always, and on `request:failed`
* except when a custom `onError` renderer threw while producing it — the one case where the
* framework does not know what was sent, and will not guess.
*/
status?: number;
}
@@ -54,6 +137,22 @@ export interface EventPayload {
*/
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
}
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
+11 -2
View File
@@ -76,9 +76,17 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.shutdown(),
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.shutdown().then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
@@ -96,5 +104,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
{ timeoutMs: ms, runtime: 'deno' },
),
),
),
});
}
+7
View File
@@ -15,6 +15,13 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*/
export function edgeHandler(
app: App,
+100 -2
View File
@@ -11,10 +11,106 @@ export interface StreamEncoder {
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
// being recognised across them would silently degrade back to an id-less `data:` frame.
const SSE_EVENT = Symbol.for('green-tea.sse-event');
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
export interface SseFields {
/**
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
* `@header('last-event-id')` and resume from there.
*/
id?: string;
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
event?: string;
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
retry?: number;
}
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
export interface SseEvent<T = unknown> extends SseFields {
readonly [SSE_EVENT]: true;
data: T;
}
/** Type guard: true when a stream item was built by {@link sse}. */
export function isSseEvent(item: unknown): item is SseEvent {
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
}
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
function assertFieldSafe(field: string, value: string): void {
if (!/[\r\n\0]/.test(value)) return;
throw new Error(
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
'one would end the field and let the rest of the value be read as further SSE fields. ' +
`Received ${JSON.stringify(value)}.`,
);
}
/**
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
* instead of a bare `data:` frame.
*
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
* marker in both directions and stores nothing — a source that can resume, resumes; one that
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
*
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
*
* @example
* ```ts
* @Sse('/feed')
* feed(@header('last-event-id') from: string) {
* return (async function* () {
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
* })();
* }
* ```
*/
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
// reconnection delay at the default rather than at the value the app asked for.
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
}
return { [SSE_EVENT]: true, data, ...fields };
}
/**
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
*/
function sseFrame(item: unknown): string {
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
let frame = '';
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
if (item.event !== undefined) frame += `event: ${item.event}\n`;
if (item.id !== undefined) frame += `id: ${item.id}\n`;
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
}
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
encode: sseFrame,
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n',
};
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
/** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' },
encode: (item) => `${JSON.stringify(item)}\n`,
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
};
+29
View File
@@ -78,6 +78,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
return ordered;
}
/**
* Groups an already topo-sorted list into dependency levels: nothing in a level can constrain
* anything else in it, and a level depends only on the levels before it — so a level can run
* concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain
* nothing and are ignored.
*/
export function topoLevels(ordered: GraphNode[]): GraphNode[][] {
const producedBy = new Map<string, GraphNode>();
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
const depthOf = new Map<GraphNode, number>();
const levels: GraphNode[][] = [];
// One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's
// needs already has its depth by the time the node is reached.
for (const node of ordered) {
let depth = 0;
for (const key of node.needs) {
const producer = producedBy.get(key);
if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1);
}
depthOf.set(node, depth);
(levels[depth] ??= []).push(node);
}
return levels;
}
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
const producedBy = new Map<string, GraphNode>();
+1 -1
View File
@@ -129,7 +129,7 @@ function parseAcquired(
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body },
);
}
+100 -15
View File
@@ -9,13 +9,31 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
// The project tsconfig's `lib` is `es2020` with no `DOM`, so the Web Crypto global is undeclared
// even though all four supported runtimes provide it. Ambient-declare only what is called — the
// same approach `src/deno.ts` takes for the Deno globals. Deliberately *not* `node:crypto`: this
// file is the runtime-neutral core, and the web-standard global is what Deno, Bun and workerd all
// have without a compatibility flag.
declare const crypto: { randomUUID(): string };
/**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
*
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
*
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release.
*
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
*/
const randomUUID: () => string = (() => {
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
/**
* A runtime-neutral inbound request.
@@ -78,7 +96,7 @@ export function correlateRequest(headers: Record<string, string | string[] | und
// The only cross-runtime win is 26 ns, against ~10.19 us for a real socketed request. A hand-
// rolled entropy pool is not worth 0.26%. A lazy getter is separately useless: the adapters and
// the payload builders both spread this object, and the first spread materialises it.
return { requestId: incoming || crypto.randomUUID(), traceId: traceId || undefined };
return { requestId: incoming || randomUUID(), traceId: traceId || undefined };
}
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
@@ -115,7 +133,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
return injected;
}
@@ -126,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, req, opts?.onError);
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
injected,
outcome: {
@@ -174,6 +192,15 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/**
* The `route` reported for a request no route matched.
*
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
* single series where the concrete path would produce one per distinct URL.
*/
export const UNMATCHED_ROUTE = '<unmatched>';
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace {
route?: string;
@@ -194,6 +221,7 @@ export function handle(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const bus = opts?.bus;
@@ -209,10 +237,52 @@ export function handle(
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined);
return dispatch(routes, opts, req, undefined, undefined, injected);
}
return observedDispatch(routes, opts, req, bus);
return observedDispatch(routes, opts, req, bus, injected);
}
/**
* Whether anything is listening for the request pair — the one check both adapters need before
* paying for a `performance.now()` on a request they are about to refuse.
*/
export function watchingRequests(bus: Bus | undefined): bus is Bus {
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
}
/**
* Emits the lifecycle pair for a request shed before routing.
*
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
* time a server sheds — under load, which is when it can least afford them.
*
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
* costs nothing for a subscriber of one.
*/
export function emitShedPair(
bus: Bus,
req: { method: string; url: string; requestId?: string; traceId?: string },
startedAt: number,
): void {
const name = `${req.method} ${req.url}`;
if (bus.hasListeners('request:start'))
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
if (bus.hasListeners('request:end'))
bus.emit('request:end', {
name,
method: req.method,
status: 503,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
async function observedDispatch(
@@ -220,6 +290,7 @@ async function observedDispatch(
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0;
@@ -233,7 +304,7 @@ async function observedDispatch(
traceId: req.traceId,
});
const result = await dispatch(routes, opts, req, bus, trace);
const result = await dispatch(routes, opts, req, bus, trace, injected);
if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
@@ -259,8 +330,13 @@ async function dispatch(
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req);
// Both adapters compute this before routing, because a response written above `handle()` — a
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
const injected = precomputed ?? computeInjected(opts, req);
let path: string;
try {
@@ -270,15 +346,24 @@ async function dispatch(
}
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) };
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
}
const matched = resolveRoute(routes, req.method, path);
if (!matched) {
// `name` here is the path that arrived, and it is the one value in this payload that must never
// become a metric label: 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. So the event carries a bounded `route` as well, and so does the
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
// and some of them to get it wrong.
if (trace) trace.route = UNMATCHED_ROUTE;
if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', {
name: `${req.method} ${path}`,
route: UNMATCHED_ROUTE,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
@@ -325,7 +410,7 @@ async function dispatch(
traceId: req.traceId,
});
} catch (error) {
result = renderError(error, req, opts?.onError);
result = renderError(error, req, opts?.onError, opts?.logger);
}
if (isStreamResult(result)) {
+43
View File
@@ -0,0 +1,43 @@
/**
* Per-server/adapter request budget.
*
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
*/
export interface RequestGate {
/**
* Whether a budget is actually configured.
*
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
* per-request cost behind it should be skipped entirely.
*/
limited: boolean;
acquire(): boolean;
release(): void;
}
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
export function createRequestGate(limit: number | undefined): RequestGate {
let active = 0;
const limited = limit !== undefined && limit > 0;
return {
limited,
acquire(): boolean {
if (limit === undefined || limit <= 0) return true;
if (active >= limit) return false;
active++;
return true;
},
release(): void {
if (limit === undefined || limit <= 0) return;
if (active > 0) active--;
},
};
}
+80 -34
View File
@@ -13,8 +13,6 @@ export interface CompiledPattern {
segments: CompiledSegment[];
kinds: number[];
catchAll: boolean;
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
allStatic: boolean;
}
const compiledCache = new Map<string, CompiledPattern>();
@@ -160,7 +158,6 @@ export function compilePattern(pattern: string): CompiledPattern {
.filter((segment) => segment.kind !== 'catchAll')
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
catchAll: segments.at(-1)?.kind === 'catchAll',
allStatic: segments.every((segment) => segment.kind === 'static'),
};
compiledCache.set(pattern, compiled);
return compiled;
@@ -248,7 +245,10 @@ export function normalizeRequestPath(path: string): string {
}
function decodeSegment(value: string): string {
return decodeURIComponent(value);
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
// runs for every param segment of every candidate route the scan reaches.
return value.includes('%') ? decodeURIComponent(value) : value;
}
/**
@@ -262,7 +262,18 @@ function splitPath(path: string): string[] {
return path.split('/').filter(Boolean);
}
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined {
/**
* Matches one compiled pattern against a request's segments.
*
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
* several routes decoded the same string once per route. Position is all decoding depends on, so one
* array shared across the scan is the same answer for less work.
*/
function matchCompiled(
compiled: CompiledPattern,
pathSegs: string[],
decoded?: Array<string | undefined>,
): Record<string, string> | undefined {
const params: Record<string, string> = {};
for (let index = 0; index < compiled.segments.length; index++) {
@@ -280,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<st
continue;
}
const value = decodeSegment(pathSegs[index]);
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value;
}
@@ -293,10 +304,15 @@ export function matchPattern(pattern: string, path: string): Record<string, stri
return matchCompiled(compilePattern(pattern), splitPath(path));
}
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
function moreSpecific(a: string, b: string): number {
const scoreA = compilePattern(a);
const scoreB = compilePattern(b);
/**
* Orders patterns by exactness, then static/constrained/plain segment specificity.
*
* Takes compiled patterns rather than their source strings: it used to re-derive both through
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
*/
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
const scoreA = a;
const scoreB = b;
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
@@ -309,35 +325,65 @@ function moreSpecific(a: string, b: string): number {
return 0;
}
/** Finds the most specific route matching both method and path; ties keep registration order. */
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
interface IndexedRoute {
def: RouteDef;
compiled: CompiledPattern;
}
/**
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
* they were built from.
*
* A server hands the same array to every request, so this is built once and collected with the
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
* different array and gets its own index, so nothing has to remember to invalidate anything.
*/
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
const cached = routeIndexCache.get(routes);
if (cached) return cached;
const byMethod = new Map<string, IndexedRoute[]>();
for (const def of routes) {
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
const bucket = byMethod.get(def.method);
if (bucket) bucket.push(entry);
else byMethod.set(def.method, [entry]);
}
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
// keep registration order — which is exactly what the old scan did by refusing to replace its
// best on a tie.
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
routeIndexCache.set(routes, byMethod);
return byMethod;
}
/**
* Finds the most specific route matching both method and path; ties keep registration order.
*
* The ranking is settled when the table is built, not per request: the answer cannot change between
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
* table. What is left here is a walk that stops at the first match.
*/
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
const candidates = routeIndex(routes).get(method);
if (!candidates) return undefined;
const pathSegs = splitPath(path);
let best: MatchedRoute | undefined;
let bestPattern = '';
const decoded: Array<string | undefined> = new Array(pathSegs.length);
for (const route of routes) {
if (route.method !== method) continue;
const compiled = compilePattern(route.pattern);
const params = matchCompiled(compiled, pathSegs);
if (!params) continue;
// An all-static match ends the scan. Specificity ranks a literal segment above every other
// kind, so no pattern that also matches this path can outrank one made only of literals — and
// an equal rank keeps registration order, which is this route. Finishing the scan would
// re-derive the answer already in hand.
//
// The scan used to run to the end regardless: `/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, and it grows with the route table.
if (compiled.allStatic) return { params, def: route };
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
best = { params, def: route };
bestPattern = route.pattern;
}
for (const { def, compiled } of candidates) {
const params = matchCompiled(compiled, pathSegs, decoded);
if (params) return { params, def };
}
return best;
return undefined;
}
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
+96 -15
View File
@@ -1,15 +1,24 @@
import type http from 'http';
import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest } from './core';
import {
handle,
correlateRequest,
computeInjected,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { nodeRequire } from '../node-require';
interface HandlerConfig {
routes: RouteDef[];
@@ -43,17 +52,29 @@ export function createHttpServer(
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttp = require('http') as typeof import('http');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
const nodeHttp = nodeRequire<typeof import('http')>('http');
const nodeHttps = nodeRequire<typeof import('https')>('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server;
const maxConnections = opts?.limits?.maxConnections ?? 1000;
if (maxConnections > 0) server.maxConnections = maxConnections;
if (maxConnections > 0) {
server.maxConnections = maxConnections;
let lastDropWarn = 0;
server.on('drop', ({ remoteAddress, remotePort }) => {
const now = Date.now();
if (now - lastDropWarn < 60_000) return;
lastDropWarn = now;
opts?.logger?.warn(
`maxConnections (${maxConnections}) reached \u2014 dropped connection from ${remoteAddress ?? 'unknown'}:${remotePort ?? 'unknown'}`,
{ maxConnections, remoteAddress, remotePort },
);
});
}
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
@@ -73,6 +94,7 @@ function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, trustProxy } = cfg;
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
// Install the security-header patch BEFORE any routing/response so every path
@@ -80,14 +102,57 @@ function createRequestHandler(cfg: HandlerConfig) {
const secure = deriveSecure(req, trustProxy);
// Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
// One computation for the whole request: this object is patched into every response below, and
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
// `cors.origins` may be a predicate with a network call in it.
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(bus);
const startedAt = watching ? performance.now() : 0;
const result = await handle(routes, opts, {
try {
if (!gate.acquire()) {
if (watching)
emitShedPair(
bus,
{
method: req.method ?? 'GET',
url: req.url ?? '/',
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
res.writeHead(503, {
'content-type': 'application/json',
'retry-after': '1',
connection: 'close',
});
res.end(JSON.stringify({ error: 'Service Unavailable' }));
return;
}
// Both the flag and the listener are skipped when no budget is configured, which is most
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
// with nothing on the other side of it.
if (gate.limited) {
acquired = true;
res.once('close', () => {
if (!acquired) return;
acquired = false;
gate.release();
});
}
result = await handle(
routes,
opts,
{
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
@@ -96,7 +161,15 @@ function createRequestHandler(cfg: HandlerConfig) {
source: req,
secure,
ip: deriveIp(req, trustProxy),
});
},
injected,
);
} finally {
if (acquired) {
acquired = false;
gate.release();
}
}
if ('preflight' in result) {
res.writeHead(204, result.preflight);
@@ -105,7 +178,15 @@ function createRequestHandler(cfg: HandlerConfig) {
}
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return;
}
@@ -131,7 +212,7 @@ function readRequestBytes(
return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }),
(error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError);
const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
},
);
+125
View File
@@ -0,0 +1,125 @@
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
import type { Logger } from '../logger';
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
type Signal = (typeof SIGNALS)[number];
interface SignalApi {
runtime: string;
on(signal: Signal, handler: () => void): void;
off(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface DenoSignals {
addSignalListener(signal: Signal, handler: () => void): void;
removeSignalListener(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface ProcessSignals {
on(signal: Signal, handler: () => void): unknown;
off?(signal: Signal, handler: () => void): unknown;
removeListener?(signal: Signal, handler: () => void): unknown;
exit(code: number): void;
}
/**
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
* listener holds the process open until it is removed. Node and Bun share `process`.
*/
function signalApi(): SignalApi | undefined {
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
if (typeof deno?.addSignalListener === 'function')
return {
runtime: 'deno',
on: (signal, handler) => deno.addSignalListener(signal, handler),
off: (signal, handler) => deno.removeSignalListener(signal, handler),
exit: (code) => deno.exit(code),
};
const proc = (globalThis as { process?: ProcessSignals }).process;
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
const remove = proc.off ?? proc.removeListener;
return {
runtime: 'node',
on: (signal, handler) => void proc.on(signal, handler),
off: (signal, handler) => void remove?.call(proc, signal, handler),
exit: (code) => proc.exit(code),
};
}
return undefined;
}
/**
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
* the process from exiting on its own.
*
* The close is expected to unregister first thing, which leaves a **second signal falling through
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
*
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
* not a clean one and an orchestrator should be told.
*/
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
const api = signalApi();
if (!api) {
logger.warn(
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
);
return () => {};
}
const registered: Array<[Signal, () => void]> = [];
const remove = (): void => {
while (registered.length) {
const [signal, handler] = registered.pop()!;
api.off(signal, handler);
}
};
for (const signal of SIGNALS) {
const handler = (): void => {
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
void close().then(
() => api.exit(0),
(error: unknown) => {
logger.error(`shutdown failed after ${signal}`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
api.exit(1);
},
);
};
try {
api.on(signal, handler);
registered.push([signal, handler]);
} catch (error) {
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
// platform does have beats refusing to start over the one it does not.
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
}
}
return remove;
}
+10 -4
View File
@@ -2,7 +2,7 @@ import type http from 'http';
import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
const PING_MS = 15_000;
@@ -35,10 +35,16 @@ export async function pipeStream(
bus?: Bus,
name = '',
streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> {
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
// is always the route pattern, never the concrete path the request events can carry — but a
// consumer following the documented contract labels on `route` and would otherwise find it
// absent on the longest-lived thing the server does. See `EventPayload.name`.
const trace = { name, route: name, ...correlation };
res.writeHead(200, encoder.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
@@ -76,13 +82,13 @@ export async function pipeStream(
}
}
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame);
} finally {
if (ping) clearInterval(ping);
streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end();
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}
+4
View File
@@ -5,11 +5,13 @@ import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
/** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
requestTimeoutMs?: number; // default 30_000
headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000
@@ -24,6 +26,8 @@ export interface HttpOptions {
* a separate channel for it.
*/
bus?: Bus;
/** Where this server writes diagnostics. Optional because `createHttpServer` takes no options at all in tests. */
logger?: Logger;
limits?: RequestLimits;
streams?: Set<() => void>;
tls?: TlsOptions;
+126 -18
View File
@@ -1,33 +1,85 @@
import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
import type { Bus, Correlation } from '../bus';
import { createRequestGate } from './request-gate';
import {
handle,
computeInjected,
correlateRequest,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
* cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the
* lifecycle of a stream must not depend on which adapter is serving it.
*/
export function asReadableStream(
source: AsyncIterable<unknown>,
encoder: StreamEncoder,
bus?: Bus,
name = '',
correlation: Correlation = {},
): ReadableStream<Uint8Array> {
const iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder();
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
// says label on `route`, so both are carried.
const trace = { name, route: name, ...correlation };
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
// its own path — so the close is latched rather than emitted from each of the three exits.
let closed = false;
const close = (): void => {
if (closed) return;
closed = true;
bus?.emit('stream:close', trace);
};
return new ReadableStream<Uint8Array>({
start() {
bus?.emit('stream:open', trace);
},
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
close();
controller.close();
return;
}
const encoded = encoder.encode(value);
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
controller.enqueue(bytes);
controller.enqueue(frame(encoder.encode(value)));
} catch (err) {
bus?.emit('stream:error', { ...trace, error: err });
const errorFrame = encoder.encodeError(err);
close();
// Framed and closed cleanly, which is what the Node adapter does and the better answer for
// the client: an SSE consumer that received an `error` event knows what happened, where a
// transport-level failure is indistinguishable from the connection simply dropping.
// `controller.error` is kept for the encoder that has no error frame to offer, because
// then breaking the stream is the only signal left.
if (errorFrame === null) {
controller.error(err);
return;
}
controller.enqueue(frame(errorFrame));
controller.close();
}
},
async cancel() {
close();
await iterator.return?.();
},
});
@@ -68,7 +120,7 @@ function readFetchBytes(
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
@@ -106,11 +158,18 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult): Response {
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
const body = asReadableStream(
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
correlation,
);
return new Response(body, { headers });
}
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
@@ -127,6 +186,7 @@ function outcomeToResponse(result: HandleResult): Response {
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (request: Request): Promise<Response> => {
const url = new URL(request.url);
@@ -139,7 +199,43 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers });
const result = await handle(routes, opts, {
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(opts?.bus);
const startedAt = watching ? performance.now() : 0;
try {
if (!gate.acquire()) {
if (watching)
emitShedPair(
opts!.bus!,
{
method: request.method,
url: path,
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
});
}
acquired = gate.limited;
result = await handle(
routes,
opts,
{
...correlation,
method: request.method,
url: path,
@@ -147,23 +243,35 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
readBody,
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
});
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
injected,
);
} finally {
// Release when routing/handling finishes, not when a returned stream finishes.
// Long-lived streams therefore do not permanently consume the request budget.
if (acquired) gate.release();
}
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
// so picks up the same authoritative security headers `injected` carries.
if ('preflight' in result) {
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
});
}
return outcomeToResponse(result);
return outcomeToResponse(result, opts?.bus, correlation);
};
}
+2 -2
View File
@@ -1,6 +1,7 @@
import { channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
/**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
@@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor {
if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws') as SocketCtor;
return nodeRequire<SocketCtor>('ws');
}
/**
+9 -3
View File
@@ -1,5 +1,6 @@
import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
@@ -109,6 +110,11 @@ export async function runWsConnection(
): Promise<void> {
const { closer } = trackConnection(socket, streams);
const name = route.def.pattern;
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
// keeps one identity per connection instead of one per emitter.
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => {
@@ -117,7 +123,7 @@ export async function runWsConnection(
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
try {
const outbound = await route.def.open({
@@ -129,9 +135,9 @@ export async function runWsConnection(
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}
+2 -2
View File
@@ -3,14 +3,14 @@ import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
import { nodeRequire } from '../node-require';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null {
try {
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
// support don't fail. When absent this throws and we fall back to null (501 on upgrade).
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws').WebSocketServer;
return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
} catch {
return null;
}
+8 -5
View File
@@ -40,8 +40,10 @@ export {
Options,
Html,
} from './metadata';
export type { Transport, HttpMethod, RouteDecorator } from './metadata';
export type { Plugin } from './plugin';
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals
export { JsonTransformer } from './transformers';
@@ -58,7 +60,7 @@ export {
// Bus & flow
export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
@@ -74,11 +76,12 @@ export type { Logger, LogLevel, LogFields } from './logger';
export { channel, isAsyncIterable } from './channel';
export type { Channel } from './channel';
export { Rooms } from './rooms';
export { sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder } from './encoders';
export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation
export type { RequestLimits } from './http';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema';
+70
View File
@@ -0,0 +1,70 @@
// src/lifecycle.ts — the teardown registry. Knows nothing about plugins, providers, apps or HTTP;
// the doors into it live where those things do.
import type { Logger } from './logger';
/**
* Something to run before the app goes away.
*
* Takes no arguments on purpose. State lives in the closure that registered it — a provider's
* `dispose()` already holds its own connection, and a plugin's callback already holds whatever the
* plugin built. Nothing has to cross a scope, which is what makes this a registry rather than an
* event bus: a bus solves "tell someone I do not know", and this is "run the thing I registered".
*/
export type TeardownFn = () => void | Promise<void>;
/**
* Await-aware teardown, deliberately not the {@link Bus}.
*
* `Bus.on` takes a synchronous listener and `emit` swallows failures, both so that an observer can
* never break the pipeline. A teardown needs the opposite of each: it must be awaited, and its
* failure must be visible. Same word, opposite guarantees — see D1 of the design.
*
* Bounding is deliberately *not* here. `closeApp` and `closeWithDeadline` already implement a
* deadline each, and a third implementation is how the three drift into different meanings of the
* same `timeoutMs`.
*/
export class TeardownRegistry {
private readonly callbacks: TeardownFn[] = [];
private drained = false;
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
add(fn: TeardownFn): void {
this.callbacks.push(fn);
}
/** How many callbacks are registered; lets a caller skip the whole path when nothing wants it. */
get size(): number {
return this.callbacks.length;
}
/**
* Run every callback, newest first, awaiting each.
*
* **Reverse registration order is load-bearing.** Providers register as they boot, and they boot
* in topological order, so reversing registration is what gives dependants teardown before their
* dependencies: a `cache` that needs `db` closes before the `db` it is still holding.
*
* Sequential rather than parallel, for the same reason — an order only means something if it is
* waited on.
*
* A failing callback is reported and the next one still runs. One broken teardown must not strand
* the rest or leave the process up. This mirrors `Bus`'s "a subscriber cannot break the system",
* but with the visibility `Bus` lacks: `Bus` swallows silently because no logger existed when it
* was written, and one exists now.
*
* Never throws, and never runs twice — `close()` is called twice by more real applications than
* anyone expects, and a second call must not re-close what the first one closed.
*/
async run(logger: Logger): Promise<void> {
if (this.drained) return;
this.drained = true;
for (let index = this.callbacks.length - 1; index >= 0; index--) {
try {
await this.callbacks[index]();
} catch (error) {
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
}
}
}
}
+312 -60
View File
@@ -1,6 +1,8 @@
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -11,15 +13,71 @@ export interface Link {
close(): void;
}
/** Backoff bounds for reconnection. `false` disables reconnecting entirely. */
export interface ReconnectOptions {
/** Delay before the first retry; doubles from here (default: 500ms). */
initialDelayMs?: number;
/** Ceiling the doubling stops at (default: 30s). */
maxDelayMs?: number;
}
/**
* What to do when a reconnecting teapot answers with a manifest that no longer backs the graph.
*
* Only `'refuse'` exists. It is a named strategy rather than implicit behaviour so that hot graph
* reconciliation can arrive later as `'reconcile'` *additively* — peers run on separate deploy
* cadences, and silently changing what the default means is the worst kind of breaking change.
*/
export type ManifestPolicy = 'refuse';
/**
* A connection failure the peer decided, rather than one the network caused.
*
* The distinction is what boot retry needs: a refused secret or a version mismatch will fail
* identically forever, so retrying one spends a deploy's patience to reach the same error. It is
* derived from whether the socket ever *opened* — a peer that accepted the connection and then hung
* up before the manifest rejected us on purpose; one that never accepted it may simply not be up.
*/
export function isPermanentRefusal(error: unknown): boolean {
return (error as { meshRefused?: boolean } | undefined)?.meshRefused === true;
}
/** Tag an error as a decision by the peer, so the caller does not retry it. */
function refused(message: string): Error {
const error = new Error(message) as Error & { meshRefused: boolean };
error.meshRefused = true;
return error;
}
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
type PendingEntry = {
/** The token or route asked for. Kept so an error can be reported by name — the frame only carries the id. */
name: string;
resolve: (v: unknown) => void;
reject: (e: unknown) => void;
timer: ReturnType<typeof setTimeout>;
};
/** Mutable per-link state: which socket is current, and whether the application hung up for good. */
interface LinkState {
socket: WsSocket | undefined;
closed: boolean;
retry: ReturnType<typeof setTimeout> | undefined;
}
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
interface Session {
socket: WsSocket;
manifest: Manifest;
heartbeat: { stop: () => void; markAlive: () => void };
}
const DEFAULT_INITIAL_DELAY_MS = 500;
const DEFAULT_MAX_DELAY_MS = 30_000;
/**
* Reject and clear every in-flight RPC — used when the link closes.
* Reject and clear every in-flight RPC — used when a session ends.
* 503, not a bare Error: 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. A bare Error renders as a 500.
*/
@@ -34,7 +92,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc(
socket: WsSocket,
socket: WsSocket | undefined,
pending: Map<string, PendingEntry>,
id: string,
kind: 'scope' | 'route',
@@ -44,8 +102,9 @@ function sendRpc(
): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known.
if (!socket.isOpen) {
// before failing anyway — the caller pays for a verdict already known. This is also the
// window a reconnecting link sits in: down, and answering immediately.
if (!socket?.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
}
@@ -57,30 +116,11 @@ function sendRpc(
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
}
/** Assemble the client-facing Link once the manifest arrives. */
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
// ids only need to be unique within this link: `pending` is per-connection, so a
// per-link counter suffices (no module-global sequence, no test-order coupling).
let counter = 0;
return {
manifest,
rpc(kind, name, ctx) {
const id = String(counter++);
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
},
close() {
socket.close();
},
};
}
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
function settleRpcResponse(
pending: Map<string, PendingEntry>,
@@ -95,7 +135,10 @@ function settleRpcResponse(
if (frame.ok) {
entry.resolve(frame.result);
} else {
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
// `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report
// "0" or "1" where every other emitter reports what failed — including the teapot's own
// emit for the same call, which made the two sides of one failure impossible to line up.
bus?.emit('mesh:rpc:error', { name: entry.name, error: frame.error });
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
}
}
@@ -118,7 +161,8 @@ const CLOSE_HEARTBEAT_TIMEOUT = 4011;
* A TCP connection can die without either side noticing — a dropped route, a killed container,
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
* turns that into an immediate 503 from the dead-link guard, emits `mesh:disconnect`, and starts
* the reconnect backoff.
*
* The interval is unref'd, so a heartbeat never holds the process open by itself.
*/
@@ -144,25 +188,24 @@ function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void;
};
}
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
/** Handle for the in-flight handshake, so the frame loop can settle the session promise. */
interface Handshake {
url: string;
socket: WsSocket;
pending: Map<string, PendingEntry>;
timeoutMs: number;
bus?: Bus;
resolve: (link: Link) => void;
resolve: (session: Session) => void;
reject: (error: unknown) => void;
onManifest: () => void;
onManifest: (socket: WsSocket) => Session['heartbeat'];
onPong: () => void;
}
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else hand back the session. */
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
if (frame.v !== MESH_PROTOCOL_VERSION) {
hs.socket.close();
hs.reject(
new Error(
refused(
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
@@ -170,12 +213,15 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
return;
}
hs.onManifest();
hs.bus?.emit('mesh:connect', { name: hs.url });
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
const heartbeat = hs.onManifest(hs.socket);
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
// the graph is refused after this point, and announcing a connection we are about to hang up on
// would tell an operator the opposite of what happened.
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
}
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
async function readFrames(hs: Handshake): Promise<void> {
for await (const data of hs.socket.inbound) {
let frame: Frame;
@@ -192,49 +238,61 @@ async function readFrames(hs: Handshake): Promise<void> {
}
}
/**
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
*/
export function connectLink(args: {
/** Everything a link needs to open one session, shared by the first connect and every retry. */
interface SessionArgs {
url: string;
secret: string;
timeoutMs?: number;
heartbeatMs?: number;
timeoutMs: number;
heartbeatMs: number;
pending: Map<string, PendingEntry>;
bus?: Bus;
Ctor?: SocketCtor;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
const pending = new Map<string, PendingEntry>();
let manifest = false;
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
onEnd: () => void;
}
return new Promise<Link>((resolve, reject) => {
/**
* Open one authenticated session: connect, handshake, and resolve once the manifest arrives.
*
* `onEnd` fires when this session's socket aborts — on a clean close and on an error alike — and is
* where the supervisor rejects in-flight RPCs and decides whether to retry. It fires for a session
* that never handshook too, which is what turns a refused connection into a scheduled retry rather
* than a silent stall.
*/
function openSession(args: SessionArgs): Promise<Session> {
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
let heartbeat: Session['heartbeat'] | undefined;
let handshook = false;
let accepted = false;
return new Promise<Session>((resolve, reject) => {
const connectTimer = setTimeout(() => {
socket.close();
reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs);
}, args.timeoutMs);
const hs: Handshake = {
url: args.url,
socket,
pending,
timeoutMs,
pending: args.pending,
bus: args.bus,
resolve,
reject,
onManifest: () => {
manifest = true;
onManifest: (established) => {
handshook = true;
clearTimeout(connectTimer);
// started only once authenticated: an unauthenticated peer should not be pinging
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
heartbeat = startHeartbeat(established, args.heartbeatMs);
return heartbeat;
},
onPong: () => heartbeat?.markAlive(),
};
opened.then(
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
() => {
accepted = true;
socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }));
},
(error) => reject(error),
);
@@ -245,9 +303,16 @@ export function connectLink(args: {
() => {
clearTimeout(connectTimer);
heartbeat?.stop();
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`);
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
if (!handshook) {
// Opened and then hung up before answering: the teapot refused this peer — a bad secret,
// or a version it would not speak. Never opened: it may just not be listening yet.
const message = `mesh handshake failed: ${args.url}`;
reject(accepted ? refused(message) : new Error(message));
}
args.onEnd();
},
{ once: true },
);
@@ -257,3 +322,190 @@ export function connectLink(args: {
});
});
}
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
function scopeKeys(manifest: Manifest): Set<string> {
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
}
/**
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
*/
function routeKeys(manifest: Manifest): Set<string> {
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
}
/**
* What the boot manifest had that a returning one does not.
*
* The graph was validated at boot against the first manifest and is already serving. A token that
* vanished cannot be validated away after the fact, so a manifest missing anything this link
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
*/
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const scopes = scopeKeys(returned);
const routes = routeKeys(returned);
const missing: string[] = [];
for (const scope of booted.scopes) {
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
}
for (const route of booted.routes) {
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
missing.push(`route '${route.method} ${route.pattern}'`);
}
}
return missing;
}
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
function backoffBounds(
reconnect: boolean | ReconnectOptions | undefined,
): { initial: number; max: number } | undefined {
if (reconnect === false) return undefined;
const opts = typeof reconnect === 'object' ? reconnect : {};
return {
initial: opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS,
max: opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,
};
}
/**
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
* arrives. The returned `Link` outlives any single socket: when a session drops, the link keeps its
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
*
* `Ctor` is injectable to exercise both client implementations on a single runtime.
*/
export function connectLink(args: {
url: string;
secret: string;
timeoutMs?: number;
heartbeatMs?: number;
bus?: Bus;
Ctor?: SocketCtor;
/** Reconnect after a dropped session (default: on). `false` restores the old fail-once behaviour. */
reconnect?: boolean | ReconnectOptions;
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy;
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
onReconnect?: () => void;
logger?: Logger;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
const bounds = backoffBounds(args.reconnect);
const pending = new Map<string, PendingEntry>();
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
let refusalLogged = '';
const link: Link = {
// replaced with the real manifest before this object escapes; a reconnect never changes it,
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
manifest: { scopes: [], routes: [] },
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
// the application hung up would leave a process that cannot exit.
state.closed = true;
clearTimeout(state.retry);
state.socket?.close();
},
};
// ids only need to be unique within this link: `pending` is per-link, so a per-link counter
// suffices (no module-global sequence, no test-order coupling).
let counter = 0;
const sessionArgs = (onEnd: () => void): SessionArgs => ({
url: args.url,
secret: args.secret,
timeoutMs,
heartbeatMs,
pending,
bus: args.bus,
Ctor: args.Ctor,
onEnd,
});
/** Schedule the next attempt, doubling from `initial` up to `max` with jitter. */
const scheduleRetry = (attempt: number): void => {
if (state.closed || !bounds) return;
const capped = Math.min(bounds.initial * 2 ** attempt, bounds.max);
// Full jitter: peers that went down together must not come back in lockstep and stampede
// the teapot the moment it returns.
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
state.retry.unref?.();
};
/** End the current session: nothing can be delivered on it, so fail what was waiting. */
const endSession = (attempt: number): void => {
state.socket = undefined;
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`);
scheduleRetry(attempt);
};
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => {
const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) {
session.heartbeat.stop();
session.socket.close();
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
// link keeps retrying rather than giving up.
const fingerprint = missing.join('|');
if (fingerprint !== refusalLogged) {
refusalLogged = fingerprint;
args.logger?.warn(
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
return false;
}
refusalLogged = '';
state.socket = session.socket;
args.bus?.emit('mesh:connect', { name: args.url });
if (reconnected) args.onReconnect?.();
return true;
};
const attemptReconnect = async (attempt: number): Promise<void> => {
if (state.closed) return;
try {
const session = await openSession(sessionArgs(() => endSession(attempt)));
if (state.closed) {
session.socket.close(); // hung up while this attempt was in flight
return;
}
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
} catch {
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
if (!state.socket && !state.retry) scheduleRetry(attempt);
}
};
return openSession(sessionArgs(() => endSession(0))).then((session) => {
link.manifest = session.manifest;
adopt(session, 0, false);
return link;
});
}
+117 -3
View File
@@ -1,18 +1,46 @@
/**
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
* cadences — possibly on different runtimes — so the frame shapes are a contract between
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
* refuse each other on mismatch rather than misparsing downstream.
* green-tea versions, not an internal detail. Peers refuse each other on mismatch rather
* than misparsing downstream.
*
* **This is a compatibility boundary, not a changelog.** Bump it only when a peer running the
* old version would *misparse a frame or misbehave silently*:
*
* - removing or renaming a field, or changing its type or meaning;
* - adding a **required** field;
* - adding a frame type that expects an answer — an old peer cannot decode it, drops it as
* undecodable, and the sender waits for a reply that will never come.
*
* Adding an **optional** field is not one of those: `decode` validates only the fields a frame
* type requires and passes extras through untouched, so an old peer ignores what it does not
* know and keeps answering. That is degraded, not broken, and does not earn a bump.
*
* Bumping per change would make the number mean "work happened" rather than "we are
* incompatible", which is the one thing it is here to say.
*/
export const MESH_PROTOCOL_VERSION = 1;
/** Serialized request context sent across the mesh for a scope or route RPC. */
/**
* Serialized request context sent across the mesh for a scope or route RPC.
*
* `correlation` and `url` are optional by protocol, not by intent: a teapot running an older
* green-tea simply ignores them, which costs the correlation of that hop and nothing else.
*/
export interface RequestEnvelope {
method: string;
params: Record<string, string>;
query: Record<string, string>;
body: unknown;
headers: Record<string, string | string[] | undefined>;
/** The requested URL, so a teapot's handler sees the same path its caller did. */
url?: string;
/**
* The caller's request identity, so a request that crosses the mesh keeps one id end to end.
* Without it every hop opens a new investigation, in the one place a distributed trace is
* the whole point.
*/
correlation?: { requestId?: string; traceId?: string };
}
/** Manifest entry for an exported scope token and its lifetime. */
@@ -87,6 +115,92 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
},
};
/** How much of a value the transport check walks before it stops looking. */
const TRANSPORT_SCAN_BUDGET = 10_000;
/** Names what a value is, for an error a reader can act on: `Pool`, `Map`, `Date`, `function`. */
function describe(value: unknown): string {
if (typeof value === 'function') return 'a function';
const name = (value as object).constructor?.name;
return name ? `a ${name} instance` : 'an object with no prototype';
}
/**
* Find the first part of `value` that cannot survive the wire, or `undefined` if all of it can.
*
* The wire is JSON, so the mesh transports **data, never behaviour**. Before this check, exporting a
* value with methods — a connection pool, a client, a `Map` — serialized to `{}` and arrived looking
* alive: truthy, an object, and missing every method. The failure then surfaced as
* `db.query is not a function` at the call site, arbitrarily far from the export that caused it.
*
* The rule is an allowlist rather than a denylist, on purpose. `Date` is refused too: it would
* arrive as a string, which is not the type the caller declared and is the same silent difference
* in a smaller costume.
*
* Bounded by a node budget so a large legitimate payload is never turned into an error by the cost
* of checking it — past the budget the value is assumed fine, since the shapes this catches are
* structural and show up immediately.
*/
export function untransportable(value: unknown, path = 'result'): Offender | undefined {
return walk(value, path, { left: TRANSPORT_SCAN_BUDGET });
}
/** What could not cross, and where it sat in the value. */
type Offender = { path: string; what: string };
/** Remaining nodes the scan may visit, shared across the whole walk. */
type Budget = { left: number };
/** Values JSON cannot represent at all, whatever they are nested in. */
function isBehaviour(kind: string): boolean {
return kind === 'function' || kind === 'symbol' || kind === 'bigint';
}
/**
* Whether a container survives the round trip as itself: a plain object or a null-prototype bag.
* Anything else is a class instance whose identity JSON discards — `Pool`, `Map`, `Set`, `Date`.
*/
function isPlainContainer(node: object): boolean {
const proto = Object.getPrototypeOf(node);
return proto === Object.prototype || proto === null;
}
/** Walk labelled children in order, returning the first offender. */
function walkEntries(entries: Array<[string, unknown]>, budget: Budget): Offender | undefined {
for (const [at, item] of entries) {
const found = walk(item, at, budget);
if (found) return found;
}
return undefined;
}
/** One node of the scan: reject behaviour and class instances, otherwise descend. */
function walk(node: unknown, at: string, budget: Budget): Offender | undefined {
if (budget.left-- <= 0 || node === null) return undefined;
const kind = typeof node;
if (isBehaviour(kind)) return { path: at, what: describe(node) };
if (kind !== 'object') return undefined;
if (Array.isArray(node)) {
return walkEntries(
node.map((item, index) => [`${at}[${index}]`, item] as [string, unknown]),
budget,
);
}
if (!isPlainContainer(node as object)) return { path: at, what: describe(node) };
return walkEntries(
Object.entries(node as Record<string, unknown>).map(([key, item]) => [`${at}.${key}`, item] as [string, unknown]),
budget,
);
}
/** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string {
return JSON.stringify(frame);
+14 -2
View File
@@ -14,14 +14,26 @@ export interface RemoteRoute {
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
}
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
/**
* Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh.
*
* `url` and `correlation` are read off `ctx.req`, the handler argument the pipeline seeds the
* context with — so a request that crosses to a teapot arrives carrying the id it already had,
* and its events on the far side join the same trace instead of starting a new one.
*/
export function envelopeFrom(ctx: any): RequestEnvelope {
const req = ctx?.req;
const correlation = { requestId: req?.requestId, traceId: req?.traceId };
return {
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
method: req?.method ?? ctx?.method ?? 'GET',
params: ctx?.params ?? {},
query: ctx?.query ?? {},
body: ctx?.body,
headers: ctx?.headers ?? {},
url: req?.url,
// omitted rather than sent empty: an envelope with no identity should look like one
...(correlation.requestId || correlation.traceId ? { correlation } : {}),
};
}
+53 -1
View File
@@ -9,6 +9,7 @@ import { isHttpError } from '../signals';
import {
encode,
decode,
untransportable,
MESH_PROTOCOL_VERSION,
type Manifest,
type RequestEnvelope,
@@ -19,6 +20,28 @@ import {
/** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control';
/**
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
*
* The teacup has always bounded its side of the handshake; the teapot had no equivalent, so a peer
* could connect and simply never send `hello`, holding a socket indefinitely without proving
* anything. Generous on purpose — this is a deadline against silence, not a latency budget.
*/
const HANDSHAKE_TIMEOUT_MS = 10_000;
/**
* Largest control frame the teapot will parse, in characters.
*
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
* documented ceiling on the platform sockets Deno and Bun provide).
*
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
* overhead of the envelope around it.
*/
const MAX_FRAME_CHARS = 4_000_000;
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
export function buildManifest(args: {
providers: string[]; // exported provider tokens (app-scope)
@@ -133,6 +156,19 @@ async function handleRpc(
try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
// Checked here, on the side that still holds the real value. Past `encode` the evidence is
// gone: JSON turns a pool into `{}`, which arrives looking alive and fails at the call site.
const offender = untransportable(result);
if (offender) {
const error: any = new Error(
`mesh cannot transport '${name}': ${offender.path} is ${offender.what}. ` +
'The wire is JSON, so a mesh export carries data, never behaviour — export what the ' +
'handle produces rather than the handle.',
);
error.status = 500;
throw error;
}
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) {
@@ -151,19 +187,34 @@ async function serveFrames(
exportedRoutes: Set<string>,
): Promise<void> {
let authed = false;
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
// says nothing is indistinguishable from a slow one until this fires.
const handshakeTimer = setTimeout(() => {
if (!authed) socket.close(1008, 'mesh handshake timeout');
}, HANDSHAKE_TIMEOUT_MS);
handshakeTimer.unref?.();
try {
for await (const data of socket.inbound) {
const raw = String(data);
// Checked before `decode`, because decoding is the expensive part being defended.
if (raw.length > MAX_FRAME_CHARS) {
socket.close(1009, 'mesh frame too large');
break;
}
let frame: Frame;
try {
frame = decode(String(data));
frame = decode(raw);
} catch {
continue; // undecodable frames are ignored, as before
}
if (!authed) {
authed = handleHandshake(socket, frame, deps);
if (authed) clearTimeout(handshakeTimer);
continue;
}
@@ -183,6 +234,7 @@ async function serveFrames(
} catch {
/* socket failed; the disconnect emit below is the same signal a clean close gives */
} finally {
clearTimeout(handshakeTimer);
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
}
}
+2 -2
View File
@@ -1,6 +1,7 @@
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
import { Readable } from 'stream';
import { HttpError } from './signals';
import { nodeRequire } from './node-require';
/** A single uploaded file part decoded from a multipart body. */
export interface UploadedFile {
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
try {
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('busboy');
return nodeRequire('busboy');
} catch {
return null;
}
+44
View File
@@ -0,0 +1,44 @@
// src/node-require.ts — one `require` that survives being published as source.
type Require = <T>(id: string) => T;
interface NodeProcess {
cwd?: () => string;
getBuiltinModule?: (id: string) => unknown;
}
let cached: Require | null | undefined;
function resolveRequire(): Require | undefined {
// The CJS build has a native one, and tsup gives the ESM build one through a `createRequire`
// banner (tsup.config.ts). Both npm paths stop here.
if (typeof require === 'function') return require as Require;
// JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`.
// `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all
// three do it *synchronously* — which is the whole requirement, since every caller here sits on
// a sync path that a dynamic `import()` could not serve.
const proc = (globalThis as { process?: NodeProcess }).process;
const nodeModule = proc?.getBuiltinModule?.('node:module') as
{ createRequire?: (from: string) => Require } | undefined;
if (!nodeModule?.createRequire || !proc?.cwd) return undefined;
// Resolve from the application's directory rather than from this file: served from JSR this
// module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer
// dependency such as `busboy` is installed in the app that asked for it.
return nodeModule.createRequire(`${proc.cwd()}/`);
}
/**
* Loads a Node builtin or an installed package, synchronously.
*
* Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely
* out of reach. Every caller already guards for that and reports it in its own terms; what they
* must not do is report it when the module is in fact reachable, which is what a bare `require`
* caused on JSR by failing with `ReferenceError` before any of them was consulted.
*/
export function nodeRequire<T>(id: string): T {
if (cached === undefined) cached = resolveRequire() ?? null;
if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`);
return cached<T>(id);
}
+26 -7
View File
@@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep {
@@ -113,9 +114,10 @@ export async function runPipeline(args: {
bus: Bus;
transport: Transport;
onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation;
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args;
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
@@ -137,16 +139,33 @@ export async function runPipeline(args: {
const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError(
let status: number | undefined;
try {
const rendered = renderError(
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
logger,
);
status = rendered.status;
return rendered;
} finally {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
//
// Emitted after the render rather than before it, because the status is only decided there:
// `onError` may turn any throw into any status, so deriving one from the error would be a
// guess that a custom renderer makes wrong.
//
// In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
}
}
}
+32 -4
View File
@@ -1,4 +1,5 @@
import { Bus } from './bus';
import type { TeardownFn } from './lifecycle';
/** A step or provider a plugin contributes to the graph. */
export interface ScopeNode {
@@ -13,18 +14,45 @@ export interface ScopeNode {
export interface ScopeApi {
add(node: ScopeNode): void;
}
/** The capabilities handed to a plugin: event subscription and node registration only. */
/**
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
*
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
*
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
* would turn a one-way observation channel into something any node can forge events on.
* `@needs('bus')` fails at boot and says so.
*/
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
/**
* Run something before the app closes — closing a pool, stopping a timer, flushing a buffer.
*
* Takes no arguments: whatever needs closing is already in the closure of the plugin that opened
* it. It is awaited, unlike a `bus.on` listener, and a failure is logged rather than swallowed.
*/
onShutdown(fn: TeardownFn): void;
}
/** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void;
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void {
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
// Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
//
// "Isolation is structural" means this list and nothing else — it is a guarantee about the
// *registration surface*, not about the request context. A plugin's step receives the live
// context like any other step and can overwrite keys in it (`src/pipeline.ts`, `Object.assign`),
// which is a separate, pre-existing question this list has never covered.
//
// `onShutdown` is the first capability here the framework must *wait* for: nothing a plugin did
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
}
+26 -5
View File
@@ -1,5 +1,7 @@
// src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */
export interface TlsOptions {
key: Buffer | string;
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
return headers;
}
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
if (spec === '*') return true;
if (typeof spec === 'function') return spec(origin);
if (Array.isArray(spec)) return spec.includes(origin);
return spec === origin;
if (typeof spec !== 'function') return spec === origin;
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
// before the region where errors convert to a response, so a throw here would leave the request
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
// has not said yes, and a broken allowlist must never widen into an open one.
try {
return spec(origin);
} catch (error) {
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
origin,
err: error instanceof Error ? error.message : String(error),
});
return false;
}
}
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers {
const headers: Headers = {};
const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) {
@@ -112,8 +128,13 @@ export function resolveCors(
export function corsPreflightHeaders(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): Headers {
const headers = resolveCors(opts, req);
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
// response carries. Re-deriving here would consult `origins` a second time for the same request —
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
// preflight-only keys below belong to this 204, not to the shared object.
const headers: Headers = { ...resolved };
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
', ',
+29 -2
View File
@@ -1,6 +1,7 @@
import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
}
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
return onError?.(error, req) ?? errorToResponse(error);
export function renderError(
error: unknown,
req: ErrorRequest,
onError?: ErrorRenderer,
logger?: Logger,
): ErrorResponse {
if (!onError) return errorToResponse(error);
// `onError` is user code, it runs on the request path, and it runs *after something already went
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
// occurs, the code written to report it fails, and the process ends instead of degrading.
//
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
// custom renderer and no matching route is one request away from exiting.
//
// A renderer that throws falls back to 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. The renderer's own failure is reported separately, because it is a different error
// from the request's and a reader chasing the wrong one loses an afternoon.
try {
return onError(error, req) ?? errorToResponse(error);
} catch (rendererError) {
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
rendering: error instanceof Error ? error.message : String(error),
});
return errorToResponse(error);
}
}
+8 -9
View File
@@ -3,6 +3,7 @@
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
import { nodeRequire } from './node-require';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
@@ -58,12 +59,12 @@ export interface ViewsContext {
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
* filesystem should hear about it here rather than at the first request. */
function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('node:path') as typeof import('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
@@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver {
let nodePath: typeof import('node:path');
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
fs = require('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
fs = nodeRequire('node:fs');
nodePath = nodeRequire('node:path');
} catch {
throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
+6 -2
View File
@@ -603,7 +603,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
// This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
@@ -618,7 +622,7 @@ describe('rooms auto-provide', () => {
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
});
});
+43
View File
@@ -76,3 +76,46 @@ describe('renderMarkdown', () => {
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
});
});
describe('renderMarkdown runtime matrix', () => {
const base = {
env: { date: '2026-09-01', commit: 'abc1234', node: 'v22', os: 'darwin', cpu: 'M4', ram: '69 GB', pinned: false },
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
scenarios: [],
stepScaling: [],
secureCost: [],
};
it('renders one column per runtime and one row per scenario', () => {
const md = renderMarkdown({
...base,
runtimes: [
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
{ runtime: 'bun', scenario: 'JSON hello', reqSec: 120_000 },
],
} as never);
expect(md).toContain('## green-tea across runtimes');
expect(md).toContain('| Scenario | node | bun |');
expect(md).toContain('| JSON hello | 90,000 | 120,000 |');
});
it('marks a runtime that produced no number rather than printing a zero', () => {
// A skipped runtime must not read as "it ran and scored nothing".
const md = renderMarkdown({
...base,
runtimes: [
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
{ runtime: 'deno', scenario: 'Route param', reqSec: 80_000 },
],
} as never);
expect(md).toContain('| JSON hello | 90,000 | — |');
expect(md).toContain('| Route param | — | 80,000 |');
});
it('omits the section entirely when no runtime was measured', () => {
expect(renderMarkdown({ ...base, runtimes: [] } as never)).not.toContain('across runtimes');
expect(renderMarkdown(base as never)).not.toContain('across runtimes');
});
});
+205
View File
@@ -0,0 +1,205 @@
// Independent providers boot concurrently; dependent ones still wait.
//
// The graph already proved which providers cannot constrain each other — that is what the topo
// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies
// instead of its longest chain, for no ordering anyone declared.
//
// Timing is asserted structurally rather than by clock: "all three entered before any left" is
// the same claim as "they overlapped" and does not get flaky on a loaded CI box.
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { Get, Module, Provider, Route, type Ctor } from '../src/metadata';
import { createApp } from '../src/app';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
}
/** Boots the app by serving one request — providers are lazy until something is actually served. */
async function boot(module: Ctor, logger = silentLogger()): Promise<void> {
const app = createApp({ modules: [module], logger });
await app.fetch(new Request('http://x/ping'));
await app.close();
}
describe('provider boot concurrency', () => {
it('overlaps providers that do not depend on each other', async () => {
const log: string[] = [];
const independent = (name: string): Ctor => {
@Provider({ provides: name })
class P {
async provide() {
log.push(`${name}:in`);
await sleep(10);
log.push(`${name}:out`);
return { [name]: name };
}
}
return P;
};
@Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] })
class M {}
await boot(M);
// Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit.
expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']);
expect(log).toHaveLength(6);
});
it('still waits for a provider its dependant needs', async () => {
const log: string[] = [];
@Provider({ provides: 'base' })
class Base {
async provide() {
log.push('base:in');
await sleep(10);
log.push('base:out');
return { base: 1 };
}
}
@Provider({ provides: 'derived', needs: ['base'] })
class Derived {
provide(ctx: { base: number }) {
log.push('derived:in');
return { derived: ctx.base + 1 };
}
}
// Declared out of order on purpose: the wait is the graph's doing, not the array's.
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] })
class M {}
await boot(M);
expect(log).toEqual(['base:in', 'base:out', 'derived:in']);
});
it('gives a dependant every value from its level, not just the one that finished first', async () => {
@Provider({ provides: 'slow' })
class Slow {
async provide() {
await sleep(15);
return { slow: 'slow' };
}
}
@Provider({ provides: 'fast' })
class Fast {
provide() {
return { fast: 'fast' };
}
}
let seen: Record<string, unknown> = {};
@Provider({ provides: 'joined', needs: ['slow', 'fast'] })
class Joined {
provide(ctx: Record<string, unknown>) {
seen = { slow: ctx.slow, fast: ctx.fast };
return { joined: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] })
class M {}
await boot(M);
expect(seen).toEqual({ slow: 'slow', fast: 'fast' });
});
it('tears down in reverse boot order even though boot is concurrent', async () => {
const disposed: string[] = [];
const independent = (name: string, delay: number): Ctor => {
@Provider({ provides: name })
class P {
async provide() {
await sleep(delay);
return { [name]: name };
}
dispose() {
disposed.push(name);
}
}
return P;
};
// `c` finishes first and `a` last — completion order is the reverse of declaration order, so a
// teardown registered as each one lands would come out in a different order than this.
@Module({
mountpoint: '/',
controllers: [Ctl],
providers: [independent('a', 20), independent('b', 10), independent('c', 1)],
})
class M {}
await boot(M);
expect(disposed).toEqual(['c', 'b', 'a']);
});
it('fails the boot on a required provider, and still registers its siblings for teardown', async () => {
const disposed: string[] = [];
@Provider({ provides: 'ok' })
class Ok {
async provide() {
await sleep(10); // still in flight when its sibling rejects
return { ok: true };
}
dispose() {
disposed.push('ok');
}
}
@Provider({ provides: 'broken' })
class Broken {
provide(): never {
throw new Error('no pool');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
// The sibling booted — it was already in flight — so whatever it opened has to be closeable.
await app.close();
expect(disposed).toEqual(['ok']);
});
it('degrades an optional provider without taking its level down', async () => {
const logger = silentLogger();
@Provider({ provides: 'flaky', optional: true })
class Flaky {
provide(): never {
throw new Error('nope');
}
}
@Provider({ provides: 'solid' })
class Solid {
provide() {
return { solid: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] })
class M {}
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/ping'));
expect(app.degraded()).toEqual(['flaky']);
await app.close();
});
});
+101
View File
@@ -0,0 +1,101 @@
// Reconnection under the real Bun runtime.
//
// Separate from the Node and Deno suites deliberately. Bun's WebSocket lifecycle is a third
// implementation — its socket events land on a server-level handler rather than the socket — and a
// link that swaps its socket underneath a live graph is precisely where three implementations
// stop behaving the same. Defining this on Node and hoping is not enough.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { runtime: 'bun' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
function freePort(): number {
const probe = Bun.serve({ port: 0, fetch: () => new Response('') });
const { port } = probe;
probe.stop(true);
return port;
}
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveBun(app, { port });
return {
stop: async () => {
server.stop(true);
await app.close();
},
};
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
const port = freePort();
let teapot = startTeapot(port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
heartbeatMs: 50,
timeoutMs: 2000,
},
});
try {
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
expect(before.status).toBe(200);
await teapot.stop();
await settle(100);
// the down window answers immediately rather than waiting out timeoutMs
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
teapot = startTeapot(port);
await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
expect(after.status).toBe(200);
expect((await after.json()).auth).toEqual({ token: 'xyz' });
} finally {
await teacup.close();
await teapot.stop();
}
});
+20
View File
@@ -49,3 +49,23 @@ test('serveBun close() drains an in-flight request rather than cutting it', asyn
expect(await inFlight).toEqual({ ok: true });
});
// D7 of the teardown design: proving the Node path works proves nothing here, because app.close()
// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses.
test('serveBun close() runs registered teardown', async () => {
const closed: string[] = [];
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
})],
});
const server = serveBun(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
expect(closed).toEqual(['plugin', 'hook']);
});
+73
View File
@@ -0,0 +1,73 @@
// The three legitimate ways to reach the bus, exercised together in one app.
//
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
// from inside the graph all still work, and only `emit` stays where it was.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Route, Get, Module, needs } from '../src/index';
import type { Events, Plugin } from '../src/index';
@Route('/b')
class Ctl {
@Get('/x') x(@needs('events') events: Events) {
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
// about, and nothing here does that.
return { hasOn: typeof events.on === 'function' };
}
}
describe('reaching the bus', () => {
it('works from outside, from a plugin and from the graph, all at once', async () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
// 1. from outside: the public `app.bus`, which keeps `emit` too.
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
// 3. from the graph: the handler receives `events` and reports its shape.
const res = await app.fetch(new Request('http://x/b/x'));
expect(await res.json()).toEqual({ hasOn: true });
expect(fromOutside).toEqual(['/b/x']);
expect(fromPlugin).toEqual(['/b/x']);
await app.close();
});
it('keeps emit outside the graph and outside plugins, and only there', async () => {
let injected: Events | undefined;
const seen: string[] = [];
@Route('/e')
class Grab {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Grab] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
// The graph's slice cannot forge an event...
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
// ...while the application that owns the app still can, which is what `app.bus` is for.
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
app.bus.emit('plugin:mounted', { name: 'from the owner' });
expect(seen).toEqual(['from the owner']);
await app.close();
});
});
+51
View File
@@ -0,0 +1,51 @@
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
// `scripts/changelog-section.mjs` writes the body of every GitHub release. It is the only place where
// a mistake is invisible until it is already published, so its boundaries are pinned here rather than
// checked by eye at release time.
const SCRIPT = resolve(process.cwd(), 'scripts/changelog-section.mjs');
const section = (version: string, tag?: string): string =>
execFileSync('node', [SCRIPT, version, ...(tag ? [tag] : [])], { encoding: 'utf8' });
const changelog = readFileSync(resolve(process.cwd(), 'CHANGELOG.md'), 'utf8');
const released = [...changelog.matchAll(/^## \[(\d[^\]]*)\]/gm)].map(([, v]) => v);
describe('changelog section extraction', () => {
it('finds every released version', () => {
expect(released.length).toBeGreaterThan(0);
for (const version of released) {
expect(section(version).trim(), version).not.toBe('');
}
});
it('stops at the next version, so a section never carries the one below it', () => {
for (const version of released) {
expect(section(version), version).not.toMatch(/^## \[/m);
}
});
// The oldest section is the one at risk: nothing follows it but the `[label]: url` block that
// defines the compare links, which belongs to no version and once ended up inside it.
it('stops at the link-reference block', () => {
for (const version of released) {
expect(section(version), version).not.toMatch(/^\[[^\]]+\]:\s+\S/m);
}
});
// A release body resolves relative links against the release page, not the repository, so every
// link has to be absolute by the time it is published.
it('rewrites relative links against the tag', () => {
for (const version of released) {
const links = [...section(version, `v${version}`).matchAll(/\]\(([^)\s]+)\)/g)].map(([, url]) => url);
expect(links.filter((url) => !url.startsWith('http')), version).toEqual([]);
}
});
it('fails rather than publishing an empty body for a version it cannot find', () => {
expect(() => section('0.0.0-nonexistent')).toThrow();
});
});
+164
View File
@@ -0,0 +1,164 @@
// Executes the circuit-breaker recipe published at
// https://green-tea.expressive-tea.io/docs/guides/circuit-breaker/
//
// The recipe lives in the documentation repository, which imports nothing from here, so nothing
// fails when the two drift apart. This is the smallest thing that makes the page's load-bearing
// claims executable rather than merely written: that breaker state survives across requests (which
// is why it is a provider and not a step), that the window re-opens, and that a failed trial in
// half-open re-opens immediately instead of earning the threshold again.
//
// Keep the class below identical to the page. If you change one, change both.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import { Provider, Module, Route, Get } from '../src/metadata';
import { createApp } from '../src/app';
import { HttpError } from '../src/signals';
import { needs } from '../src/params';
// ---- the recipe, verbatim ---------------------------------------------------------------------
type BreakerState = 'closed' | 'open' | 'half-open';
class CircuitBreaker {
#state: BreakerState = 'closed';
#failures = 0;
#openedAt = 0;
constructor(
private readonly threshold: number,
private readonly resetMs: number,
private readonly now: () => number = Date.now,
) {}
get state(): BreakerState {
return this.#state;
}
async call<T>(operation: () => Promise<T>): Promise<T> {
if (this.#state === 'open') {
if (this.now() - this.#openedAt < this.resetMs) {
throw new HttpError(503, 'billing is unavailable');
}
this.#state = 'half-open';
}
try {
const result = await operation();
this.#state = 'closed';
this.#failures = 0;
return result;
} catch (error) {
this.#failures++;
if (this.#state === 'half-open' || this.#failures >= this.threshold) {
this.#state = 'open';
this.#openedAt = this.now();
}
throw error;
}
}
}
interface BillingApi {
charge(userId: string): Promise<{ ok: true }>;
}
@Provider({ provides: 'billing', needs: ['billingApi'] })
class GuardedBilling {
#breaker = new CircuitBreaker(3, 30_000);
provide({ billingApi }: { billingApi: BillingApi }) {
return {
billing: {
charge: (userId: string) => this.#breaker.call(() => billingApi.charge(userId)),
},
billingBreaker: this.#breaker,
};
}
}
// ---- the test ---------------------------------------------------------------------------------
describe('circuit-breaker recipe', () => {
it('opens after the threshold and short-circuits, sharing state across requests', async () => {
let calls = 0;
@Provider({ provides: 'billingApi' })
class FailingBilling {
provide() {
return {
billingApi: {
charge: async () => {
calls++;
throw new Error('upstream down');
},
} satisfies BillingApi,
};
}
}
@Route('/')
class Ctl {
@Get('/pay')
async pay(@needs('billing') billing: { charge(id: string): Promise<unknown> }) {
try {
await billing.charge('u1');
return { ok: true };
} catch (error) {
return { failed: (error as Error).message };
}
}
}
@Module({ mountpoint: '/', providers: [FailingBilling, GuardedBilling], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const hit = async () => (await (await app.fetch(new Request('http://x/pay'))).json()) as { failed: string };
// Three real attempts trip it; the fourth never reaches the upstream. The breaker survives
// across requests, which is the whole reason it is a provider and not a step.
expect((await hit()).failed).toBe('upstream down');
expect((await hit()).failed).toBe('upstream down');
expect((await hit()).failed).toBe('upstream down');
expect(calls).toBe(3);
expect((await hit()).failed).toBe('billing is unavailable');
expect(calls).toBe(3); // short-circuited — upstream was not called again
await app.close();
});
it('half-opens after the reset window and closes again on success', async () => {
let clock = 0;
let fail = true;
const breaker = new CircuitBreaker(2, 1000, () => clock);
const call = () =>
breaker.call(async () => {
if (fail) throw new Error('down');
return 'ok';
});
await expect(call()).rejects.toThrow('down');
await expect(call()).rejects.toThrow('down');
expect(breaker.state).toBe('open');
await expect(call()).rejects.toThrow('billing is unavailable'); // still inside the window
clock = 2000;
fail = false;
await expect(call()).resolves.toBe('ok');
expect(breaker.state).toBe('closed');
});
it('re-opens when the trial request in half-open fails', async () => {
let clock = 0;
const breaker = new CircuitBreaker(1, 1000, () => clock);
await expect(breaker.call(async () => Promise.reject(new Error('down')))).rejects.toThrow('down');
expect(breaker.state).toBe('open');
clock = 2000;
await expect(breaker.call(async () => Promise.reject(new Error('down')))).rejects.toThrow('down');
expect(breaker.state).toBe('open'); // one failed trial is enough, threshold not restarted
});
});
+4 -1
View File
@@ -29,7 +29,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
});
const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App);
// `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
const handleSignals = <T,>(closer: T): T => closer;
serveDeno({ upgrade, handleSignals } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
+53
View File
@@ -0,0 +1,53 @@
// The teapot's frame loop under Deno, driven by a raw client rather than by another green-tea.
//
// The two guards here are close-code behaviour, and close codes are exactly where the runtimes
// have already differed once — a client may only send 1000 or 3000-4999, which is why the mesh
// heartbeat uses 4011 instead of 1011. Server-side closes deserve the same suspicion.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Step, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run() {
return { auth: { ok: true } };
}
}
@Module({ mountpoint: '/api', steps: [Auth] })
class TeapotModule {}
async function startTeapot() {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
let port = 0;
const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
await new Promise((r) => setTimeout(r, 50));
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
}
/** Opens a raw control-channel socket and resolves with how it ended. */
function rawClient(port: number, send: string): Promise<{ code: number }> {
return new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`);
ws.onopen = () => ws.send(send);
ws.onclose = (event) => resolve({ code: event.code });
ws.onerror = () => reject(new Error('socket errored'));
});
}
Deno.test('mesh on Deno: the teapot hangs up on an oversized control frame', async () => {
const teapot = await startTeapot();
try {
// over the 4,000,000-character cap, and sent by a peer that has not authenticated
const oversized = `{"type":"hello","v":1,"secret":"${'a'.repeat(4_000_001)}"}`;
const { code } = await rawClient(teapot.port(), oversized);
assertEquals(code, 1009);
} finally {
await teapot.stop();
}
});
+101
View File
@@ -0,0 +1,101 @@
// Reconnection under the real Deno runtime.
//
// This exists separately from the Node suite because the teacup's WebSocket client is a different
// implementation here — Deno's global `WebSocket`, not the `ws` package — and a link that swaps its
// socket underneath a live graph is exactly the kind of thing that works on one and not the other.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
function freePort(): number {
const probe = Deno.listen({ port: 0 });
const { port } = probe.addr as Deno.NetAddr;
probe.close();
return port;
}
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
async function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
stop: async () => {
await server.shutdown();
await app.close();
},
};
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async () => {
const port = freePort();
let teapot = await startTeapot(port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
heartbeatMs: 50,
timeoutMs: 2000,
},
});
try {
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(before.status, 200);
await teapot.stop();
await settle(100);
// the down window answers immediately rather than waiting out timeoutMs
const down = await teacup.fetch(new Request('http://x/api/local/who'));
assertEquals(down.status, 503);
teapot = await startTeapot(port);
await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
assertEquals(after.status, 200);
assertEquals((await after.json()).auth, { token: 'xyz' });
} finally {
await teacup.close();
await teapot.stop();
}
});
+21
View File
@@ -63,3 +63,24 @@ Deno.test('a caller-supplied signal still aborts the server', async () => {
ac.abort();
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
});
// D7 of the teardown design: a teardown must run on every runtime that has a shutdown, and it must
// run from the close() the runtime actually uses. app.close() returns at its no-server guard here,
// so proving the Node path works proves nothing about this one — hence a Deno assertion of its own.
Deno.test('serveDeno close() runs registered teardown', async () => {
const closed: string[] = [];
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
})],
});
const server = serveDeno(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
});
+53
View File
@@ -0,0 +1,53 @@
// `createApp({ handleSignals: true })` under the real Deno runtime.
//
// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno
// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed —
// so an app that closed itself and forgot to unregister would hang here and nowhere else.
//
// Run with: npm run test:deno
import { assert, assertEquals } from 'jsr:@std/assert';
const HARNESS = 'test/interop/_signal-app-deno.ts';
async function run(): Promise<{ code: number; lines: string[] }> {
const child = new Deno.Command('deno', {
args: ['run', '--allow-all', '--no-check', HARNESS],
stdout: 'piped',
stderr: 'inherit',
}).spawn();
const lines: string[] = [];
let buffered = '';
let signalled = false;
const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader();
const pump = (async () => {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffered += value;
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!signalled && line.includes('"ready"')) {
signalled = true;
child.kill('SIGTERM');
}
}
}
})();
const status = await child.status;
await pump;
return { code: status.code, lines };
}
Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => {
const { code, lines } = await run();
assert(
lines.some((l) => l.includes('"disposed"')),
`dispose() never ran — got: ${lines.join(' | ')}`,
);
assertEquals(code, 0);
});
+76
View File
@@ -0,0 +1,76 @@
// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it.
//
// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire`
// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has
// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a
// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a
// green suite. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Route, Get, Html, Module } from '../../src/index.ts';
// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`.
const dir = 'test/fixtures/views';
@Route('/')
class Views {
@Get('/dash') @Html('dash.html') dash() {}
@Get('/user') @Html('user.html', { template: true }) user() {
return { name: 'Deno' };
}
}
@Module({ mountpoint: '/', controllers: [Views] })
class M {}
Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/dash'));
assertEquals(res.status, 200);
assertEquals(await res.text(), '<h1>Dash</h1>');
await app.close();
});
Deno.test('@Html template mode renders', async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/user'));
assertStringIncludes(await res.text(), 'Hi Deno');
await app.close();
});
// Deno has a filesystem, so `static` must not report the runtime as the reason for anything.
Deno.test('static: true builds a resolver instead of blaming the runtime', async () => {
const app = createApp({ modules: [], static: dir });
const res = await app.fetch(new Request('http://x/asset.txt'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'served');
await app.close();
});
// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy`
// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that
// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one
// diagnosis guaranteed to send a reader to reinstall a package they already have.
Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => {
const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts');
@R('/')
class Upload {
@Post('/up') up(@body() b: { fields: Record<string, string>; files: Record<string, { filename: string }> }) {
return { name: b.fields.name, filename: b.files.file.filename };
}
}
@Mod({ mountpoint: '/', controllers: [Upload] })
class UploadMod {}
const app = create({ modules: [UploadMod] });
const form = new FormData();
form.set('name', 'joe');
form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png');
const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form }));
assertEquals(res.status, 200);
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close();
});
+73
View File
@@ -80,3 +80,76 @@ describe('HttpError body', () => {
server.close();
});
});
// `onError` is user code, on the request path, running *after something already went wrong*. An
// unguarded throw here was the worst-timed crash in the framework: the error occurs, the code
// written to report it fails, and the process ends instead of degrading. It was also easy to
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
// route was one request away from exiting.
describe('an onError that throws', () => {
const exploding: ErrorRenderer = () => {
throw new Error('renderer exploded');
};
@Route('/x')
class Boom {
@Get('/boom') boom() {
throw new HttpError(503, 'Service Unavailable');
}
}
@Module({ mountpoint: '/', controllers: [Boom] })
class BoomModule {}
it('falls back to the built-in rendering rather than losing the response', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/x/boom'));
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
});
// The path that needed no thrown handler at all.
it('survives a 404, which the renderer also produces', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/nothing-here'));
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
});
it('reports the renderer as the thing that failed, not the request', async () => {
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
const logger = {
debug() {},
info() {},
warn() {},
error(msg: string, fields?: Record<string, unknown>) {
logged.push({ msg, fields });
},
};
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
await app.fetch(new Request('http://x/x/boom'));
expect(logged).toHaveLength(1);
expect(logged[0].msg).toMatch(/onError/);
// Both errors named, because a reader chasing the wrong one loses an afternoon.
expect(logged[0].fields?.err).toBe('renderer exploded');
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
});
it('answers over a real Node server instead of exiting the process', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const server = await app.listen(0);
const port = (server.address() as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
expect(res.status).toBe(503);
// Still serving — the point of the whole test.
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
await app.close();
});
});
+1
View File
@@ -0,0 +1 @@
served
+1
View File
@@ -0,0 +1 @@
<h1>Dash</h1>
+1
View File
@@ -0,0 +1 @@
<h1>Hi {{ name }}</h1>
+29 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, test } from 'vitest';
import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph';
import { topoSort, topoLevels, GraphNode, subgraphFor, nearest } from '../src/graph';
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
({ name, needs, provides, origin: 'test' });
@@ -42,6 +42,34 @@ describe('subgraphFor', () => {
});
});
describe('topoLevels', () => {
const levels = (ordered: GraphNode[]): string[][] => topoLevels(ordered).map((l) => l.map((n) => n.name));
it('puts nodes that cannot constrain each other in the same level', () => {
expect(levels([N('a'), N('b'), N('c')])).toEqual([['a', 'b', 'c']]);
});
it('pushes a node past every producer it needs, not just its first', () => {
// `late` needs a depth-0 and a depth-1 node, so it belongs at 2 — taking the max, not the first.
const ordered = [N('config'), N('db', ['config']), N('late', ['config', 'db'])];
expect(levels(ordered)).toEqual([['config'], ['db'], ['late']]);
});
it('ignores needs nothing here produces, so a seed does not push a node down a level', () => {
expect(levels([N('a'), N('user', ['req', 'params'])])).toEqual([['a', 'user']]);
});
it('leaves no gaps, so every level has something to run', () => {
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
expect(topoLevels(ordered).every((level) => level.length > 0)).toBe(true);
});
it('keeps every node exactly once', () => {
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
expect(topoLevels(ordered).flat().map((n) => n.name).sort()).toEqual(['a', 'b', 'c', 'solo']);
});
});
describe('nearest', () => {
it('suggests a close candidate (edit distance <= 2)', () => {
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
+292 -1
View File
@@ -1,4 +1,8 @@
import { describe, expect, it, test } from 'vitest';
import { describe, expect, it, test, vi } from 'vitest';
import * as net from 'node:net';
import { ServerResponse } from 'node:http';
import { once } from 'node:events';
import { Bus } from '../src/bus';
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
@@ -143,6 +147,185 @@ describe('request hardening', () => {
server.close();
});
it('warns when maxConnections drops a real connection and throttles repeated warnings', async () => {
const logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const server = createHttpServer([], [], undefined, undefined, {
logger,
limits: { maxConnections: 1 },
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const first = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(first, 'connect');
const waitForClose = (socket: net.Socket): Promise<void> =>
new Promise((resolve) => {
socket.on('error', () => undefined);
socket.once('close', () => resolve());
});
const second = net.createConnection({ host: '127.0.0.1', port: address.port });
const third = net.createConnection({ host: '127.0.0.1', port: address.port });
const secondClosed = waitForClose(second);
const thirdClosed = waitForClose(third);
try {
await Promise.all([secondClosed, thirdClosed]);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('maxConnections (1) reached \u2014 dropped connection from'),
expect.objectContaining({
maxConnections: 1,
remoteAddress: '127.0.0.1',
}),
);
} finally {
first.destroy();
second.destroy();
third.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
started = resolve;
});
const bus = new Bus();
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
bus.on('request:end', (event) => {
ended.push(event);
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{
limits: { maxConcurrentRequests: 1 },
cors: { origins: 'https://example.com' },
},
);
await new Promise<void>((resolve) => server.listen(0, resolve));
const first = fetch(`${getUrl(server)}/slow`);
await firstStarted;
const rejected = await fetch(`${getUrl(server)}/slow`, {
headers: { origin: 'https://example.com' },
});
expect(rejected.status).toBe(503);
expect(rejected.headers.get('content-type')).toBe('application/json');
expect(rejected.headers.get('retry-after')).toBe('1');
expect(rejected.headers.get('connection')).toBe('close');
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
expect(ended).toHaveLength(1);
expect(ended[0]).toMatchObject({
method: 'GET',
status: 503,
});
expect(ended[0].requestId).toBeTruthy();
release();
const firstResponse = await first;
expect(firstResponse.status).toBe(200);
const afterRelease = await fetch(`${getUrl(server)}/slow`);
expect(afterRelease.status).toBe(200);
server.close();
});
it('releases a request slot when the client disconnects before the handler settles', async () => {
let started!: () => void;
const handlerStarted = new Promise<void>((resolve) => {
started = resolve;
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/hang',
transport: 'buffer',
handler: async () => {
started();
await new Promise(() => {});
return { status: 200, headers: {}, body: 'never' };
},
},
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
[],
undefined,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const responseClosed = new Promise<void>((resolve) => {
server.once('request', (_req, res) => {
res.once('close', resolve);
});
});
const client = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(client, 'connect');
client.write('GET /hang HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n');
await handlerStarted;
client.destroy();
await responseClosed;
const afterDisconnect = await fetch(`${getUrl(server)}/ok`);
expect(afterDisconnect.status).toBe(200);
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
const server = createHttpServer(
@@ -170,4 +353,112 @@ describe('request hardening', () => {
expect(await res.json()).toEqual({ a: '1', b: 'two' });
server.close();
});
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
const warn = vi.fn();
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[],
undefined,
undefined,
{
cors: {
origins: () => {
throw new Error('lookup failed');
},
},
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any,
},
);
await new Promise<void>((r) => server.listen(0, r));
// Only a request carrying an Origin reaches the predicate — which is why a suite that forgets
// the header watches this crash in production instead.
const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } });
expect(res.status).toBe(200);
expect(res.headers.get('access-control-allow-origin')).toBeNull();
expect(warn).toHaveBeenCalled();
// The security headers still land: one broken predicate must not strip the rest.
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
server.close();
});
// `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a
// tenant query. Running one twice for a GET and three times for a preflight charges the caller's
// latency budget and their backend for an answer whose inputs did not change in between.
it('consults a cors.origins predicate once per request, not once per header computation', async () => {
let calls = 0;
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ cors: { origins: () => { calls++; return true; } } },
);
await new Promise<void>((r) => server.listen(0, r));
const origin = { origin: 'https://a.com' };
const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin });
expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetch(`${getUrl(server)}/ping`, {
method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
// No Origin header never reaches the predicate at all — that part was already right.
calls = 0;
await fetch(`${getUrl(server)}/ping`);
expect(calls).toBe(0);
server.close();
});
// `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of
// apps used to pay a closure and an EventEmitter registration per request for a feature that is
// off. Small in absolute terms, and on the hot path, which is why it is asserted rather than
// trusted: a `res.once('close')` is exactly the kind of line that comes back.
it('registers no per-request close listener when no request budget is configured', async () => {
const closeListeners: string[] = [];
// Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only
// needs to see the event name before handing the call straight back to the real one.
const proto = ServerResponse.prototype as unknown as {
once(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
};
const realOnce = proto.once;
const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) {
if (event === 'close') closeListeners.push('close');
return realOnce.call(this, event, listener);
});
try {
const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]);
await new Promise<void>((r) => unlimited.listen(0, r));
expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200);
expect(closeListeners).toHaveLength(0);
unlimited.close();
// With a budget set, the listener is what releases the slot on a client disconnect, so it
// has to come back — the guard is about the unset case, not about dropping the feature.
const limited = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ limits: { maxConcurrentRequests: 4 } },
);
await new Promise<void>((r) => limited.listen(0, r));
expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200);
expect(closeListeners.length).toBeGreaterThan(0);
limited.close();
} finally {
spy.mockRestore();
}
});
});
+29
View File
@@ -0,0 +1,29 @@
// Not a test — a Deno app with `handleSignals: true`, spawned by test/deno/signals.test.ts.
// Deno's test runner only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists because Deno is where the signal API actually differs: `Deno.addSignalListener` and
// `Deno.exit` rather than `process.on`/`process.exit`, and a listener that holds the process open
// until it is removed. Node passing says nothing about any of that.
import 'npm:reflect-metadata';
import { createApp, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Module({ mountpoint: '/', controllers: [] })
class Mod {}
// A hook rather than a provider's `dispose()`: on Deno nothing boots until the first request, so an
// unvisited app has no provider to dispose and the run would pass without proving anything. The
// hook registers at `createApp`, which makes "teardown ran" mean "close() was reached".
const app = createApp({
modules: [Mod],
handleSignals: true,
hooks: [{ onShutdown: () => console.log(JSON.stringify({ disposed: true })) }],
});
// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen`
// synchronously from inside `Deno.serve`, so a parent that signals on that line races the handler
// registration that happens a few statements later and wins.
const server = serveDeno(app, { port: 0, onListen: () => {} });
console.log(JSON.stringify({ ready: true }));
void server;
+41
View File
@@ -0,0 +1,41 @@
// Not a test — a Node app with `handleSignals: true`, spawned by shutdown-signals.test.ts.
//
// Signal handling can only be told apart from doing nothing by a real process that really gets a
// real signal: an in-process test would have to fire the handler by hand, and the handler's whole
// job is to exit the process it is running in.
//
// Prints one JSON line per event on stdout: {"ready":port}, then {"disposed":n} per dispose call.
import 'reflect-metadata';
import { createApp, Provider, Route, Get, Module } from '../../src/index';
const SLOW = Number(process.env.DISPOSE_DELAY_MS ?? 0);
let disposals = 0;
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { name: 'db' } };
}
async dispose() {
if (SLOW) await new Promise((r) => setTimeout(r, SLOW));
disposals++;
console.log(JSON.stringify({ disposed: disposals }));
}
}
@Route('/')
class Api {
@Get('/ping') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Api], providers: [Db] })
class Mod {}
const app = createApp({ modules: [Mod], handleSignals: process.env.HANDLE_SIGNALS !== 'false' });
void app.listen(0).then((server) => {
console.log(JSON.stringify({ ready: (server.address() as { port: number }).port }));
});
+185
View File
@@ -0,0 +1,185 @@
// The `request:start` / `request:end` pairing, asserted across every terminal path there is.
//
// The guarantee held by accident until `maxConcurrentRequests` arrived: `request:start` had a
// single emitter, so nothing could break it. It has more than one now, and a guarantee upheld by
// there being only one place to get it wrong is not a guarantee — it is a coincidence with good
// timing. This file is what makes the next terminal path fail loudly instead of quietly.
//
// Adding a response shape? Add a row. That is the whole maintenance contract.
import { describe, expect, it } from 'vitest';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import { buildFetch } from '../src/http/web';
interface Seen {
starts: string[];
ends: Array<{ requestId?: string; status?: number }>;
}
function watch(bus: Bus): Seen {
const seen: Seen = { starts: [], ends: [] };
bus.on('request:start', (e) => seen.starts.push(e.requestId ?? ''));
bus.on('request:end', (e) => seen.ends.push({ requestId: e.requestId, status: e.status }));
return seen;
}
const ok = async () => ({ status: 200, headers: {}, body: 'ok' });
const boom = async () => {
throw new Error('kaboom');
};
/** Every shape of request the framework can answer, and how to provoke it. */
const SHAPES: Array<{
name: string;
status: number;
routes: Parameters<typeof buildFetch>[0];
opts?: Parameters<typeof buildFetch>[1];
request: () => Request;
}> = [
{
name: 'matched handler',
status: 200,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/ok'),
},
{
name: 'unmatched route',
status: 404,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/nope'),
},
{
name: 'handler throws',
status: 500,
routes: [{ method: 'GET', pattern: '/boom', transport: 'buffer', handler: boom }],
request: () => new Request('http://x/boom'),
},
{
name: 'body over maxBodyBytes',
status: 413,
routes: [{ method: 'POST', pattern: '/echo', transport: 'buffer', handler: ok }],
opts: { limits: { maxBodyBytes: 8 } },
request: () => new Request('http://x/echo', { method: 'POST', body: 'x'.repeat(500) }),
},
{
name: 'CORS preflight',
status: 204,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
opts: { cors: { origins: '*' } },
request: () =>
new Request('http://x/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}),
},
];
describe('every terminal path emits request:start before request:end', () => {
for (const shape of SHAPES) {
it(`${shape.name} → ${shape.status}`, async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(shape.routes, { ...shape.opts, bus });
const res = await fetchHandler(shape.request());
expect(res.status).toBe(shape.status);
expect(seen.starts).toHaveLength(1);
expect(seen.ends).toHaveLength(1);
// Same request, not two that happened to arrive together — the id is what a consumer keys on.
expect(seen.ends[0].requestId).toBe(seen.starts[0]);
});
}
// The path that broke the pairing, and the reason this file exists. It never reaches `handle()`,
// so the emitter every row above goes through never sees it.
it('shed over maxConcurrentRequests → 503', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/slow', transport: 'buffer', handler: async () => (await blocked, ok()) }],
{ bus, limits: { maxConcurrentRequests: 1 } },
);
const first = fetchHandler(new Request('http://x/slow'));
const shed = await fetchHandler(new Request('http://x/slow'));
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
});
// The Node adapter sheds through its own code path, so passing on `buildFetch` proves nothing
// about it — the two were separate emitters before they shared one.
it('shed over maxConcurrentRequests → 503, on the Node adapter', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const firstStarted = new Promise<void>((r) => (started = r));
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((r) => server.listen(0, r));
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/slow`;
const first = fetch(url);
await firstStarted;
const shed = await fetch(url);
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
server.close();
});
// The invariant stated as a count rather than per row. Scoped to the enumerated shapes on
// purpose — the two shed paths have their own tests above, because they are the ones that need
// a blocked handler to provoke and the ones that broke it in the first place.
it('leaves no enumerated shape with an end whose start is missing', async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
{ bus, cors: { origins: '*' } },
);
for (const shape of SHAPES) {
const h = buildFetch(shape.routes, { ...shape.opts, bus });
await h(shape.request());
}
await fetchHandler(new Request('http://x/ok'));
expect(seen.ends).not.toHaveLength(0);
for (const end of seen.ends) expect(seen.starts).toContain(end.requestId);
expect(seen.starts).toHaveLength(seen.ends.length);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect, vi } from 'vitest';
import { TeardownRegistry, type TeardownFn } from '../src/lifecycle';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
describe('TeardownRegistry', () => {
it('runs callbacks newest first, so a dependant tears down before its dependency', async () => {
const order: string[] = [];
const registry = new TeardownRegistry();
// Providers register as they boot, and they boot in topological order — so `db` registering
// before `cache` is what a `cache` needing `db` actually looks like here.
registry.add(() => void order.push('db'));
registry.add(() => void order.push('cache'));
await registry.run(silentLogger());
expect(order).toEqual(['cache', 'db']);
});
it('awaits each callback before starting the next', async () => {
const order: string[] = [];
const registry = new TeardownRegistry();
registry.add(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
order.push('slow');
});
registry.add(() => void order.push('fast'));
await registry.run(silentLogger());
// 'fast' is registered last so it runs first; 'slow' must still have finished by return.
expect(order).toEqual(['fast', 'slow']);
});
it('logs a throwing callback and still runs the rest', async () => {
const logger = silentLogger();
const order: string[] = [];
const registry = new TeardownRegistry();
registry.add(() => void order.push('first'));
registry.add(() => {
throw new Error('boom');
});
registry.add(() => void order.push('third'));
await expect(registry.run(logger)).resolves.toBeUndefined();
expect(order).toEqual(['third', 'first']);
expect(logger.warn).toHaveBeenCalledOnce();
expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/boom/);
});
it('treats a rejecting async callback the same as a throwing one', async () => {
const logger = silentLogger();
const registry = new TeardownRegistry();
registry.add(() => Promise.reject(new Error('async boom')));
registry.add(() => Promise.resolve());
await expect(registry.run(logger)).resolves.toBeUndefined();
expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/async boom/);
});
it('does not re-run callbacks on a second close()', async () => {
let runs = 0;
const registry = new TeardownRegistry();
registry.add(() => void runs++);
await registry.run(silentLogger());
await registry.run(silentLogger());
expect(runs).toBe(1);
});
it('resolves when nothing is registered, and reports an empty size', async () => {
const registry = new TeardownRegistry();
expect(registry.size).toBe(0);
await expect(registry.run(silentLogger())).resolves.toBeUndefined();
});
it('reports how many callbacks are registered', () => {
const registry = new TeardownRegistry();
const noop: TeardownFn = () => {};
registry.add(noop);
registry.add(noop);
expect(registry.size).toBe(2);
});
});
+139
View File
@@ -0,0 +1,139 @@
import { describe, it, expect } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run() {
return { auth: { ok: true } };
}
}
@Module({ mountpoint: '/api', steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('auth') auth: any) {
return { auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const collect = () => {
const lines: string[] = [];
return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } };
};
describe('mesh boot retry', () => {
it('waits for a teapot that starts late, rather than failing the deploy', async () => {
const port = await new Promise<number>((resolve) => {
const probe = require('node:net').createServer();
probe.listen(0, () => {
const { port: p } = probe.address();
probe.close(() => resolve(p));
});
});
const { lines, logger } = collect();
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }],
timeoutMs: 500,
bootTimeoutMs: 4000,
},
});
// the teapot arrives *after* the teacup has already started trying
const pending = teacup.fetch(new Request('http://x/api/local/who'));
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
await new Promise((r) => setTimeout(r, 300));
const server = await teapot.listen(port);
try {
const res = await pending;
expect(res.status).toBe(200);
expect(lines.some((l) => l.includes('of boot budget left'))).toBe(true);
} finally {
await teacup.close();
await teapot.close();
server.close();
}
}, 15_000);
it('still fails the boot once the budget is spent — a needed provider is not optional', async () => {
const { lines, logger } = collect();
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
timeoutMs: 200,
bootTimeoutMs: 600,
},
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
expect(lines.some((l) => l.includes('giving up after'))).toBe(true);
} finally {
await teacup.close();
}
}, 15_000);
it('does not retry a wrong secret — the teapot refused, and it will refuse again', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;
const { lines, logger } = collect();
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'WRONG' }],
timeoutMs: 500,
bootTimeoutMs: 30_000,
},
});
try {
const started = Date.now();
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
// with a 30s budget, retrying would have taken 30s to reach the same error
expect(Date.now() - started).toBeLessThan(3000);
expect(lines.some((l) => l.includes('refused this peer'))).toBe(true);
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
} finally {
await teacup.close();
await teapot.close();
server.close();
}
}, 40_000);
it('bootTimeoutMs: 0 makes one attempt, as before', async () => {
const { lines, logger } = collect();
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
timeoutMs: 200,
bootTimeoutMs: 0,
},
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
} finally {
await teacup.close();
}
}, 15_000);
});
+246
View File
@@ -0,0 +1,246 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { envelopeFrom } from '../../src/mesh/teacup';
import { createMeshControl } from '../../src/mesh/teapot';
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
import { Bus } from '../../src/bus';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('auth') auth: any) {
return { auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/** Drives a control handler with a scripted socket, capturing what it sends and how it closes. */
function fakeSocket() {
const queue: string[] = [];
let push: ((v: string) => void) | undefined;
let done = false;
const sent: string[] = [];
const closes: Array<{ code?: number; reason?: string }> = [];
return {
sent,
closes,
feed: (frame: string) => (push ? push(frame) : queue.push(frame)),
end: () => {
done = true;
push?.('');
},
socket: {
get isOpen() {
return !done;
},
abort: new AbortController().signal,
send: (data: string) => sent.push(data),
close: (code?: number, reason?: string) => {
closes.push({ code, reason });
done = true;
},
terminate: () => undefined,
inbound: {
async *[Symbol.asyncIterator]() {
while (!done) {
if (queue.length) {
yield queue.shift()!;
continue;
}
const next = await new Promise<string>((resolve) => (push = resolve));
if (done) return;
yield next;
}
},
},
},
};
}
describe('envelopeFrom', () => {
it('carries the url and the caller correlation off ctx.req', () => {
const envelope = envelopeFrom({
req: { method: 'POST', url: '/orders/7?x=1', requestId: 'req-1', traceId: 'trace-1' },
params: { id: '7' },
query: { x: '1' },
headers: { 'x-token': 'abc' },
body: { total: 10 },
});
expect(envelope.url).toBe('/orders/7?x=1');
expect(envelope.correlation).toEqual({ requestId: 'req-1', traceId: 'trace-1' });
expect(envelope.method).toBe('POST');
});
it('omits correlation entirely when the caller has none, rather than sending an empty one', () => {
expect(envelopeFrom({ req: { method: 'GET', url: '/x' } })).not.toHaveProperty('correlation');
});
});
describe('mesh rpc errors', () => {
it('reports the token that failed, not the wire id', async () => {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
let authed = false;
ws.on('message', (data) => {
const frame = decode(data.toString());
if (!authed && frame.type === 'hello') {
authed = true;
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
return;
}
if (frame.type === 'rpc-req') {
ws.send(encode({ type: 'rpc-res', id: frame.id, ok: false, error: { message: 'nope', status: 403 } }));
}
});
});
const port = (wss.address() as { port: number }).port;
const bus = new Bus();
const seen: string[] = [];
bus.on('mesh:rpc:error', (payload) => seen.push(String(payload.name)));
const link = await connectLink({ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x', bus });
await expect(link.rpc('scope', 'billing', env)).rejects.toMatchObject({ status: 403 });
// used to be "0" — the per-link counter — which no operator could match to anything
expect(seen).toEqual(['billing']);
link.close();
wss.close();
});
});
describe('teapot hardening', () => {
const control = () =>
createMeshControl({
secret: 'good',
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
resolveScope: async () => 'value',
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
});
it('hangs up on an oversized frame before parsing it', async () => {
const fake = fakeSocket();
const running = control().handle(fake.socket as never);
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
await running;
expect(fake.closes[0]?.code).toBe(1009);
// never answered: the frame died before decode, so no manifest went out
expect(fake.sent).toEqual([]);
});
it('serves normally when a frame is under the cap', async () => {
const fake = fakeSocket();
const running = control().handle(fake.socket as never);
fake.feed(encode({ type: 'hello', v: V, secret: 'good' }));
await new Promise((r) => setTimeout(r, 10));
fake.end();
await running;
expect(JSON.parse(fake.sent[0]).type).toBe('manifest');
});
});
describe('correlation across the mesh', () => {
it("the teapot's own events carry the caller's request id, not one it opened itself", async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;
// what the teapot reports about its *own* work — the far end of the trace
const far: Array<string | undefined> = [];
teapot.bus.on('request:step:leave', (payload) => far.push(payload.requestId));
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
});
try {
// the id a gateway would have set; core adopts it rather than minting a new one
const res = await teacup.fetch(
new Request('http://x/api/local/who', { headers: { 'x-request-id': 'from-the-gateway' } }),
);
expect(res.status).toBe(200);
expect(far.length).toBeGreaterThan(0);
// before this change the teapot saw no id at all, so a request crossing the mesh
// became two unrelated investigations
expect(new Set(far)).toEqual(new Set(['from-the-gateway']));
} finally {
await teacup.close();
await teapot.close();
server.close();
}
});
});
describe('cleartext secret warning', () => {
it('warns for a remote ws:// teapot, and stays quiet for loopback', async () => {
const remote: string[] = [];
const logger = { debug() {}, info() {}, warn: (m: string) => remote.push(m), error() {} };
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;
// loopback: there is no network path, so nothing to warn about
const local = createApp({
modules: [TeacupModule],
experimental: true,
logger,
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
});
try {
await local.fetch(new Request('http://x/api/local/who'));
expect(remote.filter((m) => m.includes('not encrypted'))).toEqual([]);
} finally {
await local.close();
await teapot.close();
server.close();
}
});
it('warns when the secret would cross a network in cleartext', async () => {
const warned: string[] = [];
const logger = { debug() {}, info() {}, warn: (m: string) => warned.push(m), error() {} };
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger,
// unreachable on purpose: the warning is emitted before the connection is attempted,
// because it is about what would be sent, not about what succeeded
mesh: { teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], timeoutMs: 300 },
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
} finally {
await teacup.close();
}
expect(warned.some((m) => m.includes('not encrypted') && m.includes('wss://'))).toBe(true);
});
});
+177
View File
@@ -0,0 +1,177 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink, missingFromManifest } from '../../src/mesh/link';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/**
* A teapot bound to a fixed port so it can be killed and restarted at the same URL — which is the
* whole point here: reconnection means returning to the *same* teapot, not finding another one.
* Its manifest is swappable so a restart can come back exporting something different.
*/
function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true }) {
const wss = new WebSocketServer({ port });
wss.on('connection', (ws) => {
let authed = false;
ws.on('message', (d) => {
const frame = decode(d.toString());
if (!authed) {
if (frame.type === 'hello' && frame.secret === 'good') {
authed = true;
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
} else ws.close(1008);
return;
}
if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: answer }));
});
});
return new Promise<{ close: () => Promise<void> }>((resolve) => {
wss.on('listening', () =>
resolve({
close: () =>
new Promise<void>((done) => {
for (const client of wss.clients) client.terminate();
wss.close(() => done());
}),
}),
);
});
}
/** A free port, taken by opening and immediately closing a server on port 0. */
async function freePort(): Promise<number> {
const probe = new WebSocketServer({ port: 0 });
await new Promise((r) => probe.on('listening', r));
const port = (probe.address() as { port: number }).port;
await new Promise((r) => probe.close(r));
return port;
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
describe('mesh reconnection', () => {
it('reconnects to the same teapot and serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
await teapot.close();
await settle(50);
// the window where the link is down answers immediately rather than after timeoutMs
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
await settle(300);
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
link.close();
await teapot.close();
});
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const warnings: string[] = [];
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
await teapot.close();
await settle(50);
// comes back exporting nothing — the graph was validated against 'auth' at boot
teapot = await teapotOn(port, { scopes: [], routes: [] });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
// logged once per distinct manifest, not once per attempt
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
link.close();
await teapot.close();
});
it('stops reconnecting once the application closes the link', async () => {
const port = await freePort();
const teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
await teapot.close();
link.close();
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
// which is what would leave app.close() with a process that cannot exit
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
await revived.close();
});
it('reconnect: false keeps the old fail-once behaviour', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
await teapot.close();
teapot = await teapotOn(port, SCOPES);
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
link.close();
await teapot.close();
});
});
describe('missingFromManifest', () => {
const booted: Manifest = {
scopes: [
{ token: 'auth', scope: 'request' },
{ token: 'config', scope: 'app' },
],
routes: [{ method: 'GET', pattern: '/svc/:id' }],
};
it('accepts an identical manifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]);
});
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
const wider: Manifest = {
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
};
expect(missingFromManifest(booted, wider)).toEqual([]);
});
it('accepts a route parameter that was only renamed', () => {
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
expect(missingFromManifest(booted, renamed)).toEqual([]);
});
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
const flipped: Manifest = {
scopes: [
{ token: 'auth', scope: 'app' },
{ token: 'config', scope: 'app' },
],
routes: booted.routes,
};
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
});
it('reports a missing route by method and pattern', () => {
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
});
});
+91
View File
@@ -0,0 +1,91 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Route, Get, Module, needs } from '../../src/index';
import { untransportable } from '../../src/mesh/protocol';
describe('untransportable', () => {
it('passes the shapes JSON actually round-trips', () => {
expect(untransportable({ a: 1, b: 'x', c: true, d: null, e: [1, { f: 2 }] })).toBeUndefined();
expect(untransportable([])).toBeUndefined();
expect(untransportable('plain')).toBeUndefined();
expect(untransportable(Object.create(null))).toBeUndefined();
});
it('names the class whose identity JSON would discard, and where it sits', () => {
class RemotePool {
query() {
return 1;
}
}
expect(untransportable({ db: new RemotePool() })).toEqual({ path: 'result.db', what: 'a RemotePool instance' });
expect(untransportable({ seen: new Map() })).toEqual({ path: 'result.seen', what: 'a Map instance' });
// refused rather than quietly delivered as a string, which is the same silent difference smaller
expect(untransportable({ at: new Date() })).toEqual({ path: 'result.at', what: 'a Date instance' });
});
it('finds behaviour nested in arrays and objects', () => {
expect(untransportable({ list: [1, { run: () => 1 }] })).toEqual({
path: 'result.list[1].run',
what: 'a function',
});
});
it('gives up rather than rejecting a payload too large to check', () => {
const huge: Record<string, unknown> = {};
for (let i = 0; i < 11_000; i++) huge[`k${i}`] = i;
huge.late = () => 1; // past the budget: assumed fine rather than turned into an error
expect(untransportable(huge)).toBeUndefined();
});
});
class Pool {
query(sql: string) {
return `ran:${sql}`;
}
}
@Provider({ provides: 'db', export: true })
class Db {
provide() {
return { db: new Pool() };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class TeapotModule {}
@Route('/local')
class Ctl {
@Get('/use')
use(@needs('db') db: any) {
return { got: typeof db };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class TeacupModule {}
describe('exporting a handle over the mesh', () => {
it('fails with a message naming the token, instead of delivering an empty object', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'x' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] },
});
try {
// before this guard: HTTP 200 with `{}` — an object that passes any truthiness check and
// then throws "db.query is not a function" somewhere else entirely
await expect(teacup.fetch(new Request('http://x/api/local/use'))).rejects.toThrow(
/mesh cannot transport 'db'[\s\S]*Pool instance/,
);
} finally {
await teacup.close();
await teapot.close();
server.close();
}
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it, vi } from 'vitest';
// The `engines` floor is `>=18`, and the global `crypto` only arrived unflagged in Node 19. That gap
// shipped once: `correlateRequest` compiled cleanly against an ambient declaration and then threw
// `ReferenceError: crypto is not defined` on the first request of every Node 18 process.
//
// CI's Node 18 job is what caught it, and this test is what makes it catchable without one — every
// developer machine and every other runtime has the global, so the bug is invisible where it is
// written. Stubbing the global away reproduces the floor's condition on any Node.
//
// If the floor ever moves above 18, this test and the fallback it guards can both go.
describe('correlateRequest without a global crypto (Node 18)', () => {
it('falls back to node:crypto instead of throwing ReferenceError', async () => {
vi.stubGlobal('crypto', undefined);
vi.resetModules();
const { correlateRequest } = await import('../src/http/core');
const a = correlateRequest({});
const b = correlateRequest({});
expect(a.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
expect(a.requestId).not.toBe(b.requestId);
expect(correlateRequest({ 'x-request-id': 'from-gateway' }).requestId).toBe('from-gateway');
vi.unstubAllGlobals();
});
});
+95
View File
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { EventPayload } from '../src/bus';
import { UNMATCHED_ROUTE } from '../src/index';
@Provider({ provides: 'db' })
class Db {
@@ -175,6 +176,100 @@ describe('failure reporting', () => {
expect(requestFailures).toHaveLength(1);
expect(requestFailures[0].route).toBe('/bad/go');
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
// Carries what was actually sent, so an error counter can break down by status without
// joining back to the `request:end` that follows it.
expect(requestFailures[0].status).toBe(500);
});
// The cardinality trap: `name` carries the path that arrived, which is bounded by nothing at all.
// A consumer labelling on `route` gets one bounded series for every path that was never a route;
// one labelling on `name` gets a series per scanner probe.
it('labels an unmatched request with a bounded route, on both events', async () => {
const app = createApp({ modules: [BadModule] });
const unmatched: EventPayload[] = [];
const ends: EventPayload[] = [];
app.bus.on('route:unmatched', (p) => unmatched.push(p));
app.bus.on('request:end', (p) => ends.push(p));
for (const probe of ['/aaa', '/aab', '/aac']) await app.fetch(new Request(`http://x${probe}`));
expect(unmatched).toHaveLength(3);
expect(ends).toHaveLength(3);
// Three distinct paths, one series.
expect(new Set(unmatched.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
expect(new Set(ends.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
// `name` still carries the concrete path, which is what makes it useful in a log and unusable
// as a label.
expect(new Set(unmatched.map((e) => e.name)).size).toBe(3);
// It cannot collide with a pattern a user can declare.
expect(UNMATCHED_ROUTE.startsWith('/')).toBe(false);
});
it('leaves a matched route labelled with its pattern, not the marker', async () => {
const app = createApp({ modules: [BadModule] });
const ends: EventPayload[] = [];
app.bus.on('request:end', (p) => ends.push(p));
await app.fetch(new Request('http://x/bad/go'));
expect(ends[0].route).toBe('/bad/go');
});
// The three-event overlap, asserted rather than described: one failing request, three events,
// one requestId. A consumer that counts `request:failed` and `request:end` as separate outcomes
// counts this request twice — which is the mistake the payload docs now name.
it('emits start, failed and end for one failing request, all sharing a requestId', async () => {
const app = createApp({ modules: [BadModule] });
const seen: Array<{ event: string; payload: EventPayload }> = [];
for (const event of ['request:start', 'request:failed', 'request:end'] as const)
app.bus.on(event, (payload) => seen.push({ event, payload }));
await app.fetch(new Request('http://x/bad/go'));
expect(seen.map((s) => s.event)).toEqual(['request:start', 'request:failed', 'request:end']);
expect(new Set(seen.map((s) => s.payload.requestId)).size).toBe(1);
// `request:end` is the terminal one and the only one that fires for every request shape; it is
// what a request counter counts.
expect(seen[2].payload.status).toBe(500);
});
// `onError` may turn any throw into any status, so a status derived from the error rather than
// from the render would be a guess that a custom renderer makes wrong.
it('reports the status a custom onError produced, not the one the error implied', async () => {
const app = createApp({
modules: [BadModule],
onError: () => ({ status: 418, headers: {}, body: 'teapot' }),
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(418);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(418);
});
// A renderer that throws must not swallow the event — the failure still happened, and losing the
// only record of it because the reporting of it broke is the worst possible trade. The status is
// the built-in renderer's, since that is what the request actually got.
it('still reports the failure when onError itself throws', async () => {
const app = createApp({
modules: [BadModule],
onError: () => {
throw new Error('renderer exploded');
},
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(500);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(500);
// The request's error, not the renderer's — they are different errors and the event names the
// one the request suffered.
expect((failures[0].error as Error).message).toBe('step exploded');
});
});
+37 -2
View File
@@ -1,6 +1,9 @@
import { expect, test, vi } from 'vitest';
import { Bus } from '../src/bus';
import { mountPlugin, Plugin, ScopeApi } from '../src/plugin';
import type { TeardownFn } from '../src/lifecycle';
const noTeardown = (): ((fn: TeardownFn) => void) => () => {};
test('plugin can observe via bus.on and add to its own scope', () => {
const bus = new Bus();
@@ -14,7 +17,7 @@ test('plugin can observe via bus.on and add to its own scope', () => {
const mounted = vi.fn();
bus.on('plugin:mounted', mounted);
mountPlugin(logger, bus, scope);
mountPlugin(logger, bus, scope, noTeardown());
expect(added).toEqual(['log']);
expect(mounted).toHaveBeenCalled();
@@ -26,5 +29,37 @@ test('plugin api does NOT expose bus.emit', () => {
const plugin: Plugin = (api) => {
expect((api.bus as any).emit).toBeUndefined();
};
mountPlugin(plugin, bus, scope);
mountPlugin(plugin, bus, scope, noTeardown());
});
test('plugin can register a teardown, and it reaches the registry', () => {
const bus = new Bus();
const registered: TeardownFn[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {});
};
mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn));
expect(registered).toHaveLength(1);
});
// D3's no-break guarantee, asserted rather than assumed: `Plugin`'s signature did not change, so a
// plugin written before this capability existed must mount and behave exactly as it did.
test('a plugin that never calls onShutdown behaves exactly as before', () => {
const bus = new Bus();
const added: string[] = [];
const registered: TeardownFn[] = [];
const legacy: Plugin = (api) => {
api.bus.on('stream:open', () => {});
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) });
};
const mounted = vi.fn();
bus.on('plugin:mounted', mounted);
mountPlugin(legacy, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn));
expect(added).toEqual(['thing']);
expect(mounted).toHaveBeenCalled();
expect(registered).toHaveLength(0);
});
+141
View File
@@ -0,0 +1,141 @@
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
//
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
// one the whole app injects.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Events } from '../src/index';
@Route('/r')
class Ctl {
@Get('/x') x() {
return { ok: true };
}
}
describe('reserved framework tokens', () => {
for (const token of ['logger', 'rooms', 'events']) {
it(`refuses a provider that declares '${token}'`, () => {
@Provider({ provides: token })
class Shadow {
provide() {
return { [token]: { mine: true } };
}
}
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(
new RegExp(`'${token}' is reserved by the framework`),
);
});
}
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
@Step({ provides: 'bus' })
class Shadow {
run() {
return { bus: { mine: true } };
}
}
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
});
it('leaves every other name alone', () => {
@Provider({ provides: 'buses' })
class Fine {
provide() {
return { buses: 1 };
}
}
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
describe("@needs('bus')", () => {
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
@Route('/b')
class Bad {
@Get('/x') x(@needs('bus') _bus: unknown) {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Bad] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
});
});
describe("@needs('events')", () => {
it('hands over on() and nothing else — no emit to forge events with', async () => {
let injected: Events | undefined;
@Route('/e')
class Observer {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Observer] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
expect(typeof injected?.on).toBe('function');
expect(Object.keys(injected!)).toEqual(['on']);
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
});
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
const seen: string[] = [];
@Provider({ provides: 'watcher', needs: ['events'] })
class Watcher {
#off?: () => void;
provide(ctx: { events: Events }) {
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
return { watcher: true };
}
dispose() {
this.#off?.();
}
}
@Route('/e')
class Observed {
@Get('/y') y(@needs('watcher') _w: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/y'));
expect(seen).toEqual(['/e/y']);
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
// emitting after close and watching nothing arrive — clearing the array and finding it empty
// would prove only that clearing works.
await app.close();
seen.length = 0;
app.bus.emit('request:end', { name: 'after close', route: '/after' });
expect(seen).toEqual([]);
});
});
+17
View File
@@ -119,6 +119,23 @@ describe('matchRoute precedence', () => {
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it('keeps registration order between patterns of equal specificity', () => {
// The tie-break the ordering rests on. Ranking is settled once when the table is built, and the
// sort that settles it is stable — which is what preserves the behaviour the scan used to get
// by refusing to replace its best on an equal rank. A sort that reordered equals would change
// which of two same-shape routes answers, silently and only for the ones that collide.
const routes = [route('GET', '/a/:first'), route('GET', '/a/:second')];
expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:first');
expect(matchRoute([...routes].reverse(), 'GET', '/a/x')?.def.pattern).toBe('/a/:second');
});
it('decodes a parameter once per position, however many candidates the scan walks', () => {
// Not an optimisation detail: the decoded value each candidate sees must be the same one, so
// memoising per request cannot change which route matches or what it receives.
const routes = [route('GET', '/a/:x/zzz'), route('GET', '/a/:y/b')];
expect(matchRoute(routes, 'GET', '/a/a%20b/b')?.params).toEqual({ y: 'a b' });
});
it('returns undefined when no pattern matches the path', () => {
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
});
+28 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security';
describe('buildSecurityHeaders', () => {
@@ -51,6 +51,33 @@ describe('resolveCors', () => {
const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any);
expect(r['access-control-allow-origin']).toBeUndefined();
});
// An `origins` predicate is the whole reason the option takes a function: an allowlist in Redis, a
// tenant lookup, a regex over a parsed URL. Every one of those has a failure mode, and it runs on
// the request path — so a throw must not leave the boundary.
describe('a predicate that throws', () => {
const boom = () => {
throw new Error('lookup failed');
};
it('denies the origin rather than escaping the request path', () => {
expect(() => resolveCors({ origins: boom }, req('https://a.com') as any)).not.toThrow();
expect(resolveCors({ origins: boom }, req('https://a.com') as any)).toEqual({});
});
it('fails closed even when credentials are on — a broken allowlist is not an open one', () => {
const r = resolveCors({ origins: boom, credentials: true }, req('https://a.com') as any);
expect(r['access-control-allow-origin']).toBeUndefined();
expect(r['access-control-allow-credentials']).toBeUndefined();
});
it('reports the failure through the logger instead of swallowing it', () => {
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
resolveCors({ origins: boom }, req('https://a.com') as any, logger as any);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn.mock.calls[0][0]).toMatch(/cors/i);
});
});
});
describe('isValidOrigin', () => {
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect, afterEach } from 'vitest';
import { spawn, type ChildProcess } from 'node:child_process';
import { createApp, Module } from '../src';
@Module({ mountpoint: '/', controllers: [] })
class Empty {}
let app: ReturnType<typeof createApp> | undefined;
let child: ChildProcess | undefined;
afterEach(async () => {
await app?.close();
app = undefined;
child?.kill('SIGKILL');
child = undefined;
});
const disposed = (r: { lines: string[] }) => r.lines.filter((l) => l.includes('"disposed"'));
const handled = (r: { lines: string[] }) => r.lines.some((l) => l.includes('received — closing'));
const listeners = () => process.listenerCount('SIGINT') + process.listenerCount('SIGTERM');
describe('handleSignals registration', () => {
it('registers nothing by default — a library must not own when the process exits', async () => {
const before = listeners();
app = createApp({ modules: [Empty] });
await app.listen(0);
expect(listeners()).toBe(before);
});
it('registers SIGINT and SIGTERM when asked, and takes both back off in close()', async () => {
const before = listeners();
const opted = createApp({ modules: [Empty], handleSignals: true });
await opted.listen(0);
expect(listeners()).toBe(before + 2);
// Not tidiness: on Deno a live signal listener holds the process open, so an app that closed
// itself and expected to exit would hang. Node is where it is observable.
await opted.close();
expect(listeners()).toBe(before);
});
});
/** Boots the harness app, waits for its `ready` line, and resolves once it has exited. */
function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwice = false) {
return new Promise<{ code: number | null; signal: NodeJS.Signals | null; lines: string[] }>((resolve, reject) => {
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
// because it is the one form that works on both the Node 18 floor CI builds against and the
// current release.
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
env: { ...process.env, ...env },
stdio: ['ignore', 'pipe', 'inherit'],
});
child = proc;
const lines: string[] = [];
let ready = false;
let buffered = '';
proc.stdout.on('data', (chunk: Buffer) => {
buffered += chunk.toString();
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!ready && line.includes('"ready"')) {
ready = true;
proc.kill(signal);
if (sendTwice) setTimeout(() => proc.kill(signal), 20);
}
}
});
proc.on('error', reject);
proc.on('exit', (code, exitSignal) => resolve({ code, signal: exitSignal, lines }));
});
}
// These need a real process because the handler's job is to exit the one it runs in — firing it by
// hand in the test runner would either take the runner down or prove nothing.
describe('handleSignals end to end', () => {
it('SIGTERM runs teardown and exits 0', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
it('SIGINT does the same — Ctrl-C is not a different kind of shutdown', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGINT');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
// The escape hatch, and the reason `close()` unregisters before it starts draining: a second
// signal finds no handler and gets the platform default. Ctrl-C twice ends a stuck teardown
// rather than waiting out the whole shutdown budget.
it('lets a second signal end a shutdown that is still draining', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { DISPOSE_DELAY_MS: '2000' }, true);
expect(handled(r)).toBe(true); // the first signal was ours
expect(disposed(r)).toHaveLength(0); // the second one did not wait for the 2s dispose
expect(r.code).not.toBe(0);
});
it('leaves the process to its default fate when handleSignals is off', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { HANDLE_SIGNALS: 'false' });
expect(handled(r)).toBe(false); // nothing of ours ran at all
expect(disposed(r)).toHaveLength(0);
expect(r.code).not.toBe(0);
});
});
+146
View File
@@ -0,0 +1,146 @@
// `id:` on the wire, and the `Last-Event-ID` round-trip it exists to enable.
//
// `EventSource` reconnects on its own — that is the reason to pick SSE over a raw WebSocket. Until
// an `id:` was written the browser had nothing to send back, so every reconnect restarted the
// iterable from its beginning and lost the gap in silence. green-tea carries the marker both ways
// and stores nothing: what the gap means is the handler's call, because only the source knows
// whether it is replayable.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import { ndjsonEncoder, sse, sseEncoder } from '../src/encoders';
import { Module, Route, Sse } from '../src/metadata';
import { header } from '../src/params';
import { createApp } from '../src/app';
const frame = (item: unknown): string => String(sseEncoder.encode(item));
describe('sse() framing', () => {
it('writes id: before data:', () => {
expect(frame(sse({ t: 1 }, { id: '7' }))).toBe('id: 7\ndata: {"t":1}\n\n');
});
it('writes every field it was given, fields before data', () => {
expect(frame(sse({ t: 1 }, { id: '7', event: 'tick', retry: 5000 }))).toBe(
'retry: 5000\nevent: tick\nid: 7\ndata: {"t":1}\n\n',
);
});
it('leaves a plain item exactly as it was', () => {
// The whole point of the marker: an app that never calls sse() sees no change on the wire.
expect(frame({ t: 1 })).toBe('data: {"t":1}\n\n');
});
it('keeps an empty id, which is how the spec resets the client s last event id', () => {
expect(frame(sse({ t: 1 }, { id: '' }))).toBe('id: \ndata: {"t":1}\n\n');
});
it('cannot be talked into extra fields by a newline in the payload', () => {
// JSON.stringify escapes the newline, so the data line stays single by construction.
expect(frame({ note: 'a\nid: 99' })).toBe('data: {"note":"a\\nid: 99"}\n\n');
});
});
describe('sse() rejects a field that would break the frame', () => {
// An id is exactly the value most likely to come from a request — a cursor, a page token — so
// this is a boundary, not a formatting nicety. Stripping would resume from the wrong place
// silently, which is the bug this feature exists to close.
for (const [label, id] of [
['newline', 'a\nid: 99'],
['carriage return', 'a\rid: 99'],
['NUL', 'a\0b'],
] as const) {
it(`throws on a ${label} in id`, () => {
expect(() => sse({ t: 1 }, { id })).toThrow(/may not contain a newline or a NUL/);
});
}
it('throws on a newline in event', () => {
expect(() => sse({ t: 1 }, { event: 'a\ndata: fake' })).toThrow(/'event' may not contain/);
});
it('throws on a fractional retry, which a browser would ignore', () => {
expect(() => sse({ t: 1 }, { retry: 1.5 })).toThrow(/whole number of milliseconds/);
});
});
describe('ndjson', () => {
it('unwraps the payload and drops the SSE fields', () => {
// A `negotiate` route yields the same items to both encoders. NDJSON has no frame to carry
// id/event/retry and no resumption protocol to use them, so the client gets what it asked for.
expect(String(ndjsonEncoder.encode(sse({ t: 1 }, { id: '7' })))).toBe('{"t":1}\n');
});
it('leaves a plain item alone', () => {
expect(String(ndjsonEncoder.encode({ t: 1 }))).toBe('{"t":1}\n');
});
});
describe('the Last-Event-ID round trip', () => {
const app = (): ReturnType<typeof createApp> => {
@Route('/')
class Ctl {
// Reading the header needs nothing new — the envelope has always carried it. What was
// missing was the `id:` that gives the browser something to put in it.
@Sse('/feed') feed(@header('last-event-id') from: string) {
const start = from ? Number(from) + 1 : 1;
return (async function* () {
for (let n = start; n < start + 2; n++) yield sse({ n }, { id: String(n) });
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
return createApp({ modules: [M] });
};
it('serves ids, and resumes from the one the client sends back', async () => {
const feed = app();
const first = await (await feed.fetch(new Request('http://x/feed'))).text();
expect(first).toBe('id: 1\ndata: {"n":1}\n\nid: 2\ndata: {"n":2}\n\n');
// What EventSource does by itself on reconnect, spelled out.
const resumed = await (
await feed.fetch(new Request('http://x/feed', { headers: { 'last-event-id': '2' } }))
).text();
expect(resumed).toBe('id: 3\ndata: {"n":3}\n\nid: 4\ndata: {"n":4}\n\n');
});
it('serves the same bytes over the Node adapter', async () => {
// A different write path — `pipeStream` to a socket rather than a web ReadableStream — so
// passing on `fetch` proves nothing about the runtime most apps deploy on.
const feed = app();
const server = await feed.listen(0);
const { port } = server.address() as import('net').AddressInfo;
const res = await fetch(`http://127.0.0.1:${port}/feed`, { headers: { 'last-event-id': '9' } });
expect(res.headers.get('content-type')).toBe('text/event-stream');
expect(await res.text()).toBe('id: 10\ndata: {"n":10}\n\nid: 11\ndata: {"n":11}\n\n');
await feed.close();
});
it('refuses an id that would inject fields, rather than writing it', async () => {
@Route('/')
class Ctl {
@Sse('/bad') bad() {
return (async function* () {
yield sse({ t: 1 }, { id: 'cursor\ndata: injected' });
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const broken = createApp({ modules: [M] });
const errors: unknown[] = [];
broken.bus.on('stream:error', (e) => errors.push(e.error));
const body = await (await broken.fetch(new Request('http://x/bad'))).text();
// Not `toContain`: the rejection quotes the offending value, so the text appears inside the
// error payload — escaped, on one line. The claim is that no *field* was injected.
expect(body.split('\n')).not.toContain('data: injected');
expect(body).toContain('event: error');
expect(errors).toHaveLength(1);
});
});
+161
View File
@@ -0,0 +1,161 @@
// A stream's lifecycle must not depend on which adapter is serving it.
//
// `pipeStream` (Node) 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`. A consumer counting `stream:error` saw
// zero on three of the four runtimes, and the client got a truncated body indistinguishable from a
// clean end. Both halves are silent, which is what made it worth its own issue.
//
// Both adapters are driven from the same route table here on purpose: a table asserting one and
// then the other is how the two drift again.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import { buildFetch } from '../src/http/web';
import type { RouteDef } from '../src/http/types';
const events = (bus: Bus): string[] => {
const seen: string[] = [];
for (const name of ['stream:open', 'stream:close', 'stream:error'] as const)
bus.on(name, () => seen.push(name));
return seen;
};
const route = (handler: () => AsyncIterable<unknown>): RouteDef[] => [
{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: handler() }) },
];
const clean = route(async function* () {
yield { t: 1 };
});
const broken = route(async function* () {
yield { t: 1 };
throw new Error('source died');
});
/** Serves one request through the Node adapter and returns the body it wrote. */
async function overNode(routes: RouteDef[], bus: Bus): Promise<string> {
const server = createHttpServer(routes, [], bus, undefined, {});
await new Promise<void>((r) => server.listen(0, r));
const { port } = server.address() as { port: number };
try {
return await (await fetch(`http://127.0.0.1:${port}/feed`)).text();
} finally {
server.close();
}
}
/** Serves one request through the Fetch adapter and returns the body it wrote. */
async function overFetch(routes: RouteDef[], bus: Bus): Promise<string> {
return await (await buildFetch(routes, { bus })(new Request('http://x/feed'))).text();
}
const ADAPTERS = [
{ name: 'node', serve: overNode },
{ name: 'fetch', serve: overFetch },
] as const;
describe('stream lifecycle events, on every adapter', () => {
for (const adapter of ADAPTERS) {
it(`${adapter.name}: opens and closes a stream that ends normally`, async () => {
const bus = new Bus();
const seen = events(bus);
expect(await adapter.serve(clean, bus)).toBe('data: {"t":1}\n\n');
expect(seen).toEqual(['stream:open', 'stream:close']);
});
it(`${adapter.name}: reports a source that throws, and frames it for the client`, async () => {
const bus = new Bus();
const seen = events(bus);
const errors: unknown[] = [];
bus.on('stream:error', (e) => errors.push(e.error));
const body = await adapter.serve(broken, bus);
// Framed rather than dropped: an SSE consumer can see this, where a truncated body is
// indistinguishable from the connection dropping.
expect(body).toContain('data: {"t":1}\n\n');
expect(body).toContain('event: error');
expect(body).toContain('source died');
expect(seen).toEqual(['stream:open', 'stream:error', 'stream:close']);
expect((errors[0] as Error).message).toBe('source died');
});
it(`${adapter.name}: names the route pattern, not the path that arrived`, async () => {
const bus = new Bus();
const names: string[] = [];
bus.on('stream:open', (e) => names.push(e.name));
await adapter.serve(clean, bus);
expect(names).toEqual(['/feed']);
});
}
for (const adapter of ADAPTERS) {
it(`${adapter.name}: correlates every stream event with the request that opened it`, async () => {
// The split is deliberate — `request:end` fires when the handler returns, not when the
// stream it produced finishes, so an hour-long SSE connection and a 2ms reply never share a
// latency distribution. That only works if the two can be joined, and this is the join key.
const bus = new Bus();
const ids = new Set<string | undefined>();
const traces = new Set<string | undefined>();
const routes = new Set<string | undefined>();
for (const name of ['stream:open', 'stream:close'] as const)
bus.on(name, (e) => {
ids.add(e.requestId);
traces.add(e.traceId);
routes.add(e.route);
});
await adapter.serve(clean, bus);
expect([...ids]).toHaveLength(1);
expect([...ids][0]).toMatch(/^[0-9a-f-]{36}$/); // one id, and it is the request's
// Bounded by the route table, which is what makes it the field to label a metric on.
expect([...routes]).toEqual(['/feed']);
expect([...traces]).toEqual([undefined]); // absent, not invented, when no traceparent arrived
});
}
it('fetch: adopts the gateway s x-request-id rather than opening a second identity', async () => {
const bus = new Bus();
const ids: Array<string | undefined> = [];
bus.on('stream:open', (e) => ids.push(e.requestId));
bus.on('stream:close', (e) => ids.push(e.requestId));
await (
await buildFetch(clean, { bus })(
new Request('http://x/feed', { headers: { 'x-request-id': 'from-the-gateway', traceparent: 'tp-1' } }),
)
).text();
expect(ids).toEqual(['from-the-gateway', 'from-the-gateway']);
});
it('fetch: closes once when the client cancels mid-stream', async () => {
// The exit `pipeStream` gets from `res.on('close')` and the ReadableStream gets from `cancel`.
// Latched, because a cancel can also land after the body has already ended.
const bus = new Bus();
const seen = events(bus);
let released!: () => void;
const blocked = new Promise<void>((r) => (released = r));
const endless = route(async function* () {
yield { t: 1 };
await blocked;
});
const res = await buildFetch(endless, { bus })(new Request('http://x/feed'));
const reader = res.body!.getReader();
await reader.read();
await reader.cancel();
released();
expect(seen).toEqual(['stream:open', 'stream:close']);
});
});
+215
View File
@@ -0,0 +1,215 @@
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { Provider, Module, Route, Get } from '../src/metadata';
import { createApp } from '../src/app';
import type { Plugin } from '../src/plugin';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
}
describe('shutdown teardown', () => {
it('awaits a plugin onShutdown before close() resolves', async () => {
const order: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('plugin torn down');
});
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
await app.close();
order.push('close returned');
expect(order).toEqual(['plugin torn down', 'close returned']);
});
it('runs a hook onShutdown without the app declaring a plugin', async () => {
const seen: string[] = [];
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void seen.push('hook') }],
logger: silentLogger(),
});
await app.listen(0);
await app.close();
expect(seen).toEqual(['hook']);
});
it('calls a provider dispose(), and skips a provider without one', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
async dispose() {
closed.push('db');
}
}
@Provider({ provides: 'plain' })
class Plain {
provide() {
return { plain: {} };
}
}
@Module({ mountpoint: '/', providers: [Db, Plain], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual(['db']);
});
// D5, and the reason dispose() is registered as a provider boots rather than as it is collected.
it('tears a dependant down before the dependency it needs', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
dispose() {
closed.push('db');
}
}
@Provider({ provides: 'cache', needs: ['db'] })
class Cache {
provide() {
return { cache: {} };
}
dispose() {
closed.push('cache');
}
}
// Declared dependency-last on purpose: the order must come from the graph, not the array.
@Module({ mountpoint: '/', providers: [Cache, Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual(['cache', 'db']);
});
it('does not dispose a provider that failed to boot', async () => {
const closed: string[] = [];
@Provider({ provides: 'broken', optional: true })
class Broken {
provide(): unknown {
throw new Error('cannot connect');
}
dispose() {
closed.push('broken');
}
}
@Module({ mountpoint: '/', providers: [Broken], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual([]);
});
it('logs a failing teardown, runs the rest, and still resolves', async () => {
const logger = silentLogger();
const closed: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {
throw new Error('teardown boom');
});
api.onShutdown(() => void closed.push('survivor'));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger });
await app.listen(0);
await expect(app.close()).resolves.toBeUndefined();
expect(closed).toEqual(['survivor']);
expect(vi.mocked(logger.warn).mock.calls.some((c) => /teardown boom/.test(c[0]))).toBe(true);
});
it('does not let a hanging teardown push close() past its deadline', async () => {
const plugin: Plugin = (api) => {
api.onShutdown(() => new Promise<void>(() => {})); // never settles
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
const startedAt = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - startedAt).toBeLessThan(1500);
});
it('rejects a reservation larger than the budget it comes out of', () => {
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M], shutdownTimeoutMs: 1000, teardownTimeoutMs: 2000 })).toThrow(
/cannot exceed shutdownTimeoutMs/,
);
});
it('tears down an app that was never listen()ed, since its providers still booted', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
dispose() {
closed.push('db');
}
}
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.fetch(new Request('http://x/ping')); // boots providers, no server
await app.close();
expect(closed).toEqual(['db']);
});
it('drains only once when close() is called twice', async () => {
let runs = 0;
const plugin: Plugin = (api) => {
api.onShutdown(() => void runs++);
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
await app.close();
await app.close();
expect(runs).toBe(1);
});
});
+68
View File
@@ -0,0 +1,68 @@
// Every extension point the docs tell a user to write must be *typeable* from the package, not just
// callable. A decorator whose argument type is not exported can be passed a literal and nothing
// else — the shape has to be redeclared inline, or borrowed off a value with
// `typeof JsonTransformer`, which works and reads like a trick because it is one.
//
// This file's job is to fail to compile if one of them stops being exported.
import { test, expect } from 'vitest';
import {
JsonTransformer,
type TransformerFn,
type Plugin,
type PluginApi,
type ScopeApi,
type ScopeNode,
type Hooks,
type TeardownFn,
type ErrorRenderer,
type StreamEncoder,
} from '../../src';
// @Transformer(fn) — the case that started this. Prometheus scrapes text, so a /metrics route
// needs its own transformer, and this is the annotation that was impossible to write.
const prometheusText: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' },
body: String(value),
});
// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the
// arrow, and nothing typed its argument.
function subscribe(api: PluginApi): void {
api.bus.on('request:end', () => {});
api.onShutdown(flush);
}
const flush: TeardownFn = () => {};
function contribute(scope: ScopeApi): void {
const node: ScopeNode = { kind: 'provider', name: 'metrics', needs: [], provides: ['metrics'], run: () => ({}) };
scope.add(node);
}
const metricsPlugin: Plugin = (api) => {
subscribe(api);
contribute(api.scope);
};
// createApp({ hooks }) — declared as a value, which is the point of the option.
const hooks: Hooks[] = [{ onShutdown: flush }];
// The two neighbouring extension points, already exported. Here so a future barrel edit that drops
// one is caught by the same test rather than by a user.
const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' });
const encoder: StreamEncoder = {
headers: {},
encode: (item) => String(item),
encodeError: (err) => String(err),
};
test('every extension point is typeable from the package barrel', () => {
expect(prometheusText('x').body).toBe('x');
expect(typeof metricsPlugin).toBe('function');
expect(hooks).toHaveLength(1);
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
expect(encoder.encode(1)).toBe('1');
// The workaround the missing export forced, kept as a reminder of what it replaced.
expect(typeof JsonTransformer).toBe('function');
});
+18
View File
@@ -19,6 +19,24 @@ class Views {
class M {}
const app = createApp({ modules: [M], views: dir });
// Checked alongside the `onError` guard: `viewEngine` is the other user callback on a render path,
// and whether it had a boundary was not something to assume. It does — the pipeline's own catch
// covers it, so a broken engine is a 500 rather than a dead process. Asserted so it stays that way.
describe('a viewEngine that throws', () => {
it('renders a 500 instead of escaping the request', async () => {
const broken = createApp({
modules: [M],
views: dir,
viewEngine: () => {
throw new Error('engine exploded');
},
});
const res = await broken.fetch(new Request('http://x/user'));
expect(res.status).toBe(500);
expect(await res.json()).toEqual({ error: 'Internal Server Error' });
});
});
describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str'));
+182 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { asReadableStream, toBodyInit } from '../src/http/web';
import { Bus } from '../src/bus';
import { asReadableStream, buildFetch, toBodyInit } from '../src/http/web';
import { sseEncoder } from '../src/encoders';
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
@@ -46,4 +47,184 @@ describe('asReadableStream', () => {
await new Promise((r) => setTimeout(r, 10));
expect(returned).toBe(true);
});
});
describe('buildFetch request gate', () => {
it('rides out a transient CORS predicate failure without leaking a gate slot', async () => {
// A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again
// inside `handle()`, so the predicate is consulted more than once per request.
let lookupDown = true;
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
{
limits: { maxConcurrentRequests: 2 },
cors: {
origins: () => {
if (lookupDown) throw new Error('transient CORS failure');
return true;
},
},
},
);
const request = () =>
new Request('http://localhost/ok', {
headers: { origin: 'https://example.com' },
});
// While the lookup is down the origin is denied — the request is answered, just without the
// header that would let the browser read it. A failed lookup has not said yes.
for (let i = 0; i < 2; i++) {
const denied = await fetchHandler(request());
expect(denied.status).toBe(200);
expect(denied.headers.get('access-control-allow-origin')).toBeNull();
}
// Once the lookup recovers the origin is allowed again, which also proves the two failures
// returned their slots: a budget of 2 that leaked would have shed this one.
lookupDown = false;
const recovered = await fetchHandler(request());
expect(recovered.status).toBe(200);
expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com');
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
started = resolve;
});
const bus = new Bus();
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
bus.on('request:end', (event) => {
ended.push(event);
});
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
{
bus,
limits: { maxConcurrentRequests: 1 },
cors: { origins: 'https://example.com' },
},
);
const first = fetchHandler(new Request('http://localhost/slow'));
await firstStarted;
const rejected = await fetchHandler(
new Request('http://localhost/slow', {
headers: { origin: 'https://example.com' },
}),
);
expect(rejected.status).toBe(503);
expect(rejected.headers.get('content-type')).toBe('application/json');
expect(rejected.headers.get('retry-after')).toBe('1');
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
expect(ended).toHaveLength(1);
expect(ended[0]).toMatchObject({
method: 'GET',
status: 503,
});
expect(ended[0].requestId).toBeTruthy();
release();
expect((await first).status).toBe(200);
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
expect(afterRelease.status).toBe(200);
});
it('consults a cors.origins predicate once per request on the fetch path too', async () => {
let calls = 0;
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }],
{ cors: { origins: () => { calls++; return true; } } },
);
const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } }));
expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetchHandler(new Request('http://localhost/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}));
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(calls).toBe(1);
});
it('releases the slot when a streaming handler returns', async () => {
async function* stream() {
yield { n: 1 };
await new Promise(() => {});
}
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/stream',
transport: 'sse',
handler: async () => ({ stream: stream() }),
},
],
{ limits: { maxConcurrentRequests: 1 } },
);
const first = await fetchHandler(
new Request('http://localhost/stream', {
headers: { accept: 'text/event-stream' },
}),
);
expect(first.status).toBe(200);
// The first response stream is still open, but its request slot should
// already be released once handle() has returned.
const second = await fetchHandler(
new Request('http://localhost/stream', {
headers: { accept: 'text/event-stream' },
}),
);
expect(second.status).toBe(200);
await first.body?.cancel();
await second.body?.cancel();
});
});
+42
View File
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core';
import { channel } from '../src/channel';
import { HttpError } from '../src/signals';
import { Bus } from '../src/bus';
import type { WsRouteDef } from '../src/http/types';
/** A controllable fake WsSocket that records sends and closes. */
@@ -110,3 +111,44 @@ describe('runWsConnection (neutral core)', () => {
expect(matchWsRoute(routes, '/nope')).toBeUndefined();
});
});
describe('runWsConnection correlation', () => {
const def: WsRouteDef = {
pattern: '/ws',
open: async () =>
(async function* () {
yield 'hi';
})(),
};
const opened = async (headers: WsRequest['headers']): Promise<Record<string, unknown>[]> => {
const bus = new Bus();
const seen: Record<string, unknown>[] = [];
for (const name of ['stream:open', 'stream:close'] as const)
bus.on(name, (e) => seen.push({ ...e }));
const { socket } = fakeSocket();
await runWsConnection(socket, { ...req, headers }, { def, params: {} }, bus);
return seen;
};
it('gives the connection one identity, not one per emitter', async () => {
const seen = await opened({});
expect(seen).toHaveLength(2);
expect(seen[0].requestId).toMatch(/^[0-9a-f-]{36}$/);
expect(seen[1].requestId).toBe(seen[0].requestId);
});
it('adopts a gateway s x-request-id and carries traceparent through', async () => {
// An upgrade is an HTTP request with headers like any other: a service behind a proxy must not
// open a second identity for a connection that already has one.
const seen = await opened({ 'x-request-id': 'gw-1', traceparent: 'tp-1' });
expect(seen.map((e) => e.requestId)).toEqual(['gw-1', 'gw-1']);
expect(seen.map((e) => e.traceId)).toEqual(['tp-1', 'tp-1']);
});
it('labels the route pattern and names the transport', async () => {
const [open] = await opened({});
expect(open.route).toBe('/ws');
expect(open.transport).toBe('ws');
});
});
+1 -1
View File
@@ -15,5 +15,5 @@
"forceConsistentCasingInFileNames": true
},
"include": ["src", "test", "example"],
"exclude": ["test/deno", "test/bun", "test/edge"]
"exclude": ["test/deno", "test/bun", "test/edge", "test/interop/_signal-app-deno.ts"]
}