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
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
Stage → Verdaccio / publish-stg (push) Successful in 25s
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 / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (bun) (pull_request) Successful in 16s
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 / runtimes (edge) (pull_request) Successful in 12s
CI / build (pull_request) Successful in 29s
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 / build (push) Successful in 28s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 23s
CI / dco (push) Has been skipped
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 (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (bun) (pull_request) Successful in 17s
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 / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
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 (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
`bootProviders` was a `for...of` with an `await` inside, so three providers that share
nothing took the sum of their latencies rather than the longest one. Measured on the
issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after.

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

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

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

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

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

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

Closes #71

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:32:17 -05:00
chrnx 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 / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (edge) (pull_request) Successful in 12s
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 (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
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 (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 21s
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

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

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

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

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

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

Closes #77.

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

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

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

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

Closes #66.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:15:35 -05:00
chrnx e5d5fb801a feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 30s
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 / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 20s
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 / 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 / build (push) Successful in 28s
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 / runtimes (deno) (pull_request) Successful in 19s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 13s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 12s
Promote → GitHub / push-github (push) Failing after 6s
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 / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (bun) (pull_request) Successful in 13s
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 / 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
CI / runtimes (bun) (pull_request) Successful in 14s
`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 / 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) (pull_request) Successful in 15s
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 (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 / runtimes (edge) (pull_request) Successful in 12s
CI / dco (push) Has been skipped
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 / runtimes (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
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 / 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
CI / runtimes (bun) (pull_request) Successful in 15s
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 / runtimes (bun) (push) Successful in 14s
CI / runtimes (edge) (push) Successful in 12s
CI / build (push) Successful in 25s
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 (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 18s
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 (deno) (pull_request) Successful in 18s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
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 (bun) (push) Successful in 13s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 23s
CI / runtimes (edge) (pull_request) Successful in 12s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
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 / 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 / dco (pull_request) Successful in 4s
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
CI / runtimes (edge) (push) Successful in 12s
2026-08-17 23:22:22 +00:00
chrnx 51608b0631 chore: back-merge main so promotions can go back to fast-forward-only
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
CI / runtimes (bun) (pull_request) Successful in 13s
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 bfe8b66127 ci: run the JSR gate on every push, not only on a release tag
release.yml has always run `deno publish --dry-run` before publishing to
either registry, and keeps doing so — that copy is the last thing standing
between a tag and a JSR version number that can never be replaced.

It runs too late to be feedback, though. A slow type in the public API or a
Deno type error lands on main in silence and surfaces while cutting a
release, which is the same "least time to judge a fix" the audit steps are
already ordered to avoid. The workflow made that argument for advisories and
not for the registry that type-checks us.

This matters more in the next few commits than it did in the last hundred:
Task 2.5 adds Hooks, TeardownFn and PluginApi.onShutdown, and exported types
are exactly what the slow-types check polices.

It is a second compiler over the same source rather than a packaging
formality. `npm run typecheck` is tsc with this repo's config; this is Deno's
checker with Deno's lib, and it is what found the BodyInit hole on the fetch
path that tsc accepted. JSR serves src/ directly, so what it rejects is what
a JSR consumer would have received.

Measured at 0.68s against 2.0s for the whole vitest suite, so it goes in the
runtimes job's Deno leg, which already installs Deno.

test:all covers the same ground locally. npm test stays Node-only on purpose
— it is the loop you run constantly, and booting three more runtimes into it
would tax every run to catch what CI already catches on every push. Verified
end to end: 393 vitest, 9 Deno, 5 Bun, edge, and the dry run, in 6.1s.

It passes --allow-dirty and CI does not, deliberately: locally you are
checking work in progress, and in CI a checkout that is not clean is worth
failing on.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:21:43 -05:00
chrnx 78b5034936 docs(plans): drop 4.5.3 — the decorator warning is already documented, and the reason given for it was wrong
Two corrections to the phase added an hour ago.

The task asked for documentation that exists. README.md:233 "Why legacy
decorators" and concepts/the-graph.md:43 in the docs repository both already
carry the argument, and carry it better: parameter decorators are
deliberately absent from the TC39 Stage 3 proposal, so a handler taking
`@param('id') id: string` is only expressible with legacy decorators, and
Stage 3 means the replacement is not finalized either. Writing a third,
shorter version of that in Honest scope would have made it worse.

The task also justified itself with a claim that is false. It said the
framework depends on emitDecoratorMetadata. It does not:
`grep -rn 'design:type\|design:paramtypes' src/` returns nothing. The flag is
set in tsconfig.json and deno.json, but no design:* reflection is read
anywhere in src/ — argument positions are recorded explicitly. Both documents
already state this, which is how the error surfaced.

What survives is a note rather than a task, because the warning arrives in CI
together with the new gate and would otherwise read as something the gate
found.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:19:41 -05:00
chrnx a5c1fda886 docs(plans): add Phase 4.5 — move the JSR gate off the tag
Task 2.5 adds public API, and exported types are what JSR's slow-types check
polices. Writing that surface with no JSR gate on pull requests means finding
out at release time whether the shape is publishable, so the phase is
numbered as an insertion and says it runs first.

The first reading of this was wrong and the correction is the useful part:
release.yml already runs `deno publish --dry-run`, before either registry
ships, and a dry run passes today with the slow-types check included. The gap
is not a missing gate, it is when it runs — only on a version tag, so a
Deno-typecheck break or a slow type lands on main in silence and surfaces
while cutting a release. That is the moment release.yml's own npm-audit
comment identifies as having the least time to judge a fix; the workflow
makes that argument for advisories and not for JSR.

Measured rather than assumed: the dry run takes 0.68s against 2.0s for the
whole vitest suite, so it goes in the runtimes job's Deno leg, which already
installs Deno, and needs no more thought than that.

npm test stays Node-only. The runtimes job already covers Deno, Bun and edge
on every push, so they are not unguarded — what is missing is one command a
contributor can run before pushing, which is test:all.

Also recorded: every dry run warns that experimentalDecorators is deprecated
and may be removed. Nothing to fix, no workaround worth inventing early, but
it is a dependency on a deprecated compiler option in a runtime we publish
to, and it belongs in Honest scope rather than in a warning nobody reads.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:44:43 -05:00
chrnx e778f62902 docs(plans): settle D8 as a reservation, and plan the implementation
D8 was the one decision left open: the teardown shares close()'s budget and
may never exceed timeoutMs, but whether lowering teardownTimeoutMs reserves
its slice or merely caps it was never stated.

It reserves. A cap only bounds how long teardown may run and does nothing
about the case the decision exists for — a drain that spends the whole
budget leaves teardown zero milliseconds and the connection stays open.
Reserving is what makes the option a guarantee rather than a ceiling on
something that may never get to run.

The plan orders the work so nothing is observable until close() is wired in
Task 4, and puts the Deno/Bun parity at Task 5 rather than last, because it
is the task most likely to surface something the design did not foresee and
finding that out early is worth more than a tidy sequence.

Two notes carried into it for whoever executes it. Provider dispose() is
registered as the provider boots rather than as it is collected, so the
reverse-topological order D5 asks for falls out of the registry's reverse
registration rule instead of needing a second sort. And the Deno and Bun
suites are not part of npm test, so that task cannot be called done on the
strength of vitest passing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:40:32 -05:00
chrnx 9f72604cbb docs(plans): design the shutdown teardown surface, before any code
Task 2.5 has been open since it was raised while deciding #15, deliberately:
it needs public API, and the API freeze is the next milestone.

Three things the design settles that the task description did not anticipate.

Teardown reaches the graph through hooks, PluginApi and a provider dispose(),
but all three are doors into one registry with one order and one failure
policy. Shipping the plugin half now and providers later would freeze two
mechanisms with different semantics around the less common case: the thing
that holds a database connection is a provider, not a plugin. The hooks
framing also means PluginApi's signature never changes, so nothing breaks at
all, which widening it directly would not have achieved.

Callbacks receive nothing. State lives in the closure that registered it, so
no handle crosses a scope and no container, app reference or transport is
needed. That is what makes this a registry rather than an event bus.

It fires from each runtime's real close, not app.close(), which returns at
its no-server guard on everything except Node. Edge cannot participate at all
and that is documented as a capability difference rather than hidden.

Recorded while verifying: "isolation is structural" protects the registration
surface, not the runtime context. A plugin's step can already overwrite
context keys, and a plugin mounting before provideBuiltins can replace the
logger and rooms builtins. Pre-existing and unrelated to teardown, noted so
the finding outlives the conversation that produced it.

D8, the shared timeout budget, is marked open rather than settled: whether
lowering teardownTimeoutMs reserves its slice or merely caps it was not
decided, and the two differ in whether a slow drain can starve teardown of
the time it needs.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 10:32:23 -05:00
chrnx 101c4fe65a chore: move the documentation site out to its own repository
website/ is now github.com/Expressive-Tea/green-tea-docs, carrying its own
history — 31 commits, extracted with `git subtree split`, not squashed into
an import that pretends the pages appeared all at once.

What this repository gives up is real and worth naming: the site had no
deploy pipeline at all, and CI here was the only thing proving it still
built. That is why the new repository got a build gate and a tagged release
before this deletion landed, rather than after.

Removed with it: the three website steps in ci.yml (including the second
setup-node that re-pinned 22.12 purely for the docs build — the core job
stays on 18, the minimum supported version), the two package.json scripts,
and the .astro/ and website/dist/ ignore rules that now belong over there.

SECURITY.md pointed at `website/` as an out-of-scope path; it now points at
the repository, since the path no longer exists to be out of scope.

The split trades a CI coupling for a drift risk — nothing fails now when
the docs and the API disagree. Both READMEs state the rule that replaces
the build: a change to public API updates the page documenting it. That is
the weakest of the options considered, and it is written down rather than
assumed.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:35:06 -05:00
chrnx 5fafe97bc5 docs: correct the observability cost, and record why three earlier numbers were wrong
The published figure was -3.9%. It was measured sequentially rather than
interleaved, and the machine drifts 12% across a session as it warms, so run
order was indistinguishable from effect. Two later attempts to correct it were
also wrong: 0.8% had the same flaw, and -6.8% compared 7bd11bf against HEAD,
which differ by observability *and* three performance fixes pulling the other
way, then reported their net as if it were one of them.

Measured properly, alternating round by round between 7bd11bf and 523e318 (the
last commit before those fixes): +7.0% of the framework's own per-request work,
about 0.29us, roughly 2% of a request over a real socket. Ranges do not overlap.

The guide no longer quotes absolute throughput from this laptop. The reference
numbers come from a two-box setup, and single-box loopback figures invite a
comparison that is not valid.

D7's shape survives: the cost is fixed per request, not per step, because
per-step work is skipped when nothing subscribes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 23:03:07 -05:00
chrnx 8d8ef7ed09 perf(http): look injected header keys up directly instead of rebuilding a Set
mergeInjectedHeaders rebuilt a lowercased Set of the injected header keys on
every response: an array from Object.keys, a mapped array from toLowerCase, and
a Set from that. Three allocations to answer a question the object already
answers.

The lowercasing was the redundant part. Every key `injected` can hold is written
as a lowercase literal in src/security.ts — buildSecurityHeaders and resolveCors
are its only sources — so the mapped array was a copy of the keys it started
with.

hasOwnProperty rather than `in`: a handler may legitimately send a header named
constructor or toString, and `in` would find those on Object.prototype and drop
them silently.

146.4ns to 55.9ns in isolation; -3.2% end to end over five interleaved rounds,
with all five pairs favouring the change.

Third of three fixes from the same profile, and all three are one pattern:
work done unconditionally for a case that rarely or never applies — validating
encoding that is almost never malformed, parsing a query string that is not
there, lowercasing keys that already were.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:57:37 -05:00
chrnx 0c5decbeae perf(router): skip query parsing when there is no query string
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.

92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.

Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.

Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:55:46 -05:00
chrnx 86dd3fe9b6 perf(router): stop decoding every path segment to throw the result away
normalizeRequestPath ran on every request and validated percent-encoding by
splitting the path and calling decodeURIComponent on each segment, discarding
every result — matching is done on the raw path. Two array allocations and one
decodeURIComponent per segment, per request, to prove that a string nobody
decodes could be decoded.

Measured in isolation: 95.8ns for /hello, 342.7ns for a six-segment route. The
guard costs 15.7ns and 6.7ns for the same two paths.

Same validation. decodeURIComponent throws on the first malformed % sequence
wherever it appears, so one call on the whole string catches what per-segment
calls caught, and %2F inside a segment decodes fine either way. Only the throw
was ever used. The existing tests for malformed encoding and repeated slashes
pass unchanged.

Found by sweeping all 178 commits between fe1831a and the observability work
after the regenerated benchmark showed green-tea down ~20% since July while
raw-http, fastify and nestjs-fastify reproduced their July numbers within 1.4%
on the same run. The sweep put a +11.8% step at 9a61ba8 "complete HEAD and
OPTIONS semantics", which is where this function entered the request path.

Effect: -6.2% in-process request latency, from twelve interleaved measurements
whose ranges do not overlap (OLD 4.253-4.425us, FIX 4.035-4.151us). A first
attempt measured with-then-without and produced the opposite sign, so the
interleaving is load-bearing, not ceremony. Expect roughly 2% over a real
socket, which is below that harness's own noise floor.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:44:35 -05:00
chrnx 523e3184b0 docs(plans): record that the timing model was wrong in shape, not just magnitude
D7 predicted ~0.25% per step and called it invisible. Measured over a real
socket it is -3.9% on JSON hello and -2.1% on a three-step pipeline: the route
with *fewer* steps loses more, which falsifies a per-step model rather than
just its constant. Per-step work is skipped when nothing subscribes, so what
remains is a fixed per-request cost that a shallow route amortises over less.

The decision survived, for a better reason than it was made with: there is
nothing per-step left to make optional.

Also records the two regressions that measurement caught and reasoning did not,
both larger than anything the design anticipated — a second async frame in
handle() at 0.43us per request, and a closure allocated per request inside
correlateRequest at 0.16us. On this path an extra promise costs more than any
amount of bookkeeping.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 15:07:39 -05:00
chrnx 92987d0a24 docs(observability): document the contract, and retire the sentence that denied it
Task 8. README.md led its Honest scope section with "No observability layer,
either." — the single most load-bearing sentence in the CTO assessment, and now
false. It says what exists instead, and keeps being explicit about what does
not: no metrics registry and no OpenTelemetry exporter in core, because core has
one runtime dependency and intends to keep it.

Adds a guide covering the parts that are contracts rather than implementation
details, since those are the ones a reader gets wrong: route labels carry the
pattern and never the concrete path (labelling metrics on raw URLs is how you
take down a metrics backend), request:end fires when the handler returns rather
than when a stream closes, and streams emit lifecycle events only.

The plugins guide was titled "Plugins & observability" and carried a partial
event list that had already drifted. It now covers plugins and points at the
guide for the vocabulary, with the correlation note it was missing.

Includes the measured cost, because a performance claim without a number is
marketing: -3.9% on JSON hello, -2.1% on a three-step pipeline, and the reason
the shallower route loses more.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 15:06:54 -05:00
chrnx e052d5ba8f feat(observability): request-level events, and request logging that reads them
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.

handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.

route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.

logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.

The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.

Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:51:33 -05:00
chrnx 7b0a3d4e24 docs(observability): record why randomUUID is the fast option, not the lazy one
Benchmarked the alternatives rather than leaving the question open. Every
supported runtime already batches entropy behind randomUUID, so the intuitive
replacements lose: Math.random() twice into base36 is 3.5x slower at 265ns
because the string work dominates, an unbatched getRandomValues is 472ns, and
a uint32 pool through toString(36) is 114ns.

The only cross-runtime improvement is a hand-rolled entropy pool with a hex
lookup table at 50ns, which saves 26ns — 0.26% of a real 10.19us request. Not
worth owning an entropy pool for. Buffer.toString('hex') matches it but is
Node-only, which this file cannot be.

Table left in the code so the next person does not re-run it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:45:17 -05:00
chrnx dabab1812b perf(observability): hoist a per-request closure out of correlateRequest
The `first` helper was declared inside correlateRequest, so it was allocated on
every request. It captures nothing, so module scope is where it always
belonged.

Measured at 0.16us against a ~4.4us in-process request — 45% of the entire
remaining observability overhead, from one line. Total overhead is now +0.24us
rather than +0.44us, which against the 10.19us of a real socketed request is
~2.4%.

Ablation of what is left, so the next person does not repeat it: randomUUID is
0.16us of the 0.24 and the other 0.08 is the header read, the extra properties
and three hasListeners lookups. Building the correlation literal per request
costs nothing measurable — V8 keeps it on the stack — so do not go optimising
that one.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:42:13 -05:00
chrnx 633ef58032 perf(observability): do not build event payloads for an empty room
The correlation work regressed the in-process hot path from 4.52us to 5.43us
per request, ~20%. The design predicted 0.25% per step and was wrong by more
than an order of magnitude, so recording what the measurement actually said:

  spreading correlation into payloads   ~197ns   <- the cost
  crypto.randomUUID()                   ~170ns in place
  try/catch inside the step loop          ~2.6ns <- not the cost

emit() cannot avoid the first: its argument is already built by the time it is
called. Only the caller can decline to build it, so Bus.hasListeners lets it,
and runSteps hoists the check out of the loop since listeners are registered at
boot. An application subscribing to nothing now pays a branch instead of four
payloads and three clock reads for an audience of nobody.

That recovers half. 4.96us remains against 4.52us — ~10% in process, ~4.5%
against the 10.19us of a real socketed request. Two ways to shave the rest were
measured and both rejected in comments: a lazy requestId is defeated by the
first spread, and a boot-prefix counter is 5x cheaper but trades the standard
identifier shape for ~1.7%. Neither earns its complexity yet.

The remaining cost is the feature, not an accident: correlation only exists if
something carries it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:26:16 -05:00
chrnx 2c47ee8896 feat(observability): correlate and time the lifecycle event stream
Tasks 1-3 of the observability plan. The Bus already had 19 emission points;
what it lacked was any way to tell which request an event belonged to, which
made the whole stream unusable under concurrency.

Every per-request event now carries requestId, traceId, route, method and
transport, and request:step:leave carries durationMs — a field that has been
declared in EventPayload since the beginning with nothing ever writing it.

Identity is derived in the adapters rather than in handle(), because both read
and size-check the body first: a 413 is answered without handle() ever seeing
the request, so generating there would leave exactly the failures an operator
most wants to correlate with nothing to correlate them by. An incoming
x-request-id is adopted rather than replaced, and traceparent is carried
verbatim — core implements no propagation spec.

Timing takes N+1 readings for N steps, since one step's end is the next one's
start. Measured at 25.2ns per step against a ~10.19us request.

request:step:error now names the step that actually failed. It reported
name: 'pipeline' before, discarding the one fact it exists to carry, because it
was emitted from the outer catch where that is all that is known. The outer
catch emits request:failed instead: one marks the span, the other the trace.

route carries the matched pattern and never the concrete path. Labelling a
metric on raw URLs gives unbounded cardinality and takes down the metrics
backend rather than the app, so it is a contract, with a test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:20:44 -05:00
chrnx 7bd11bff27 docs(plans): implementation plan for the observability contract
Eight tasks from the reviewed design, ordered so the correction lands before
anything consumes it — a logger built on uncorrelated events would grow its own
notion of request identity, which is the failure the design exists to prevent.

Two placement details worth having settled in writing. requestId is generated
in the adapters rather than in handle(), because both read and size-check the
body first, so a 413 never reaches handle() — generating there would leave
exactly the failures an operator most wants to correlate without an id. And
step timing takes N+1 timestamps for N steps, since one step's end is the next
one's start; the design measured that against the naive 2N.

Task 7 benchmarks the hot path and says outright that if the measurement
disagrees with D7, the design changes rather than the number being quietly
kept.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:08:11 -05:00
chrnx d324ecfcb4 docs(plans): settle the three open questions in the observability design
D6: a request span ends when the handler returns, and stream events carry its
requestId. Ending it at stream close would mix 2ms buffered requests with
hour-long SSE connections in one latency distribution; connection duration is
already readable from stream:open/close once they can be joined. Same boundary
#21 chose for its concurrency gate — the framework should not disagree with
itself about when a request is over.

D7: per-step timing is always on. Measured rather than argued: performance.now()
at step boundaries costs 25.2ns per step against a 10.19us request, or 0.25% —
below the 0.3% run-to-run CV of the project's own benchmark. A flag would buy
two code paths for something the harness cannot detect. The measurement also
settles Date.now(), which is both slower (28.6ns) and coarser.

D8: request logging is a Bus subscriber, wrapped to fall back to console. One
path, composable as #10 asks, and the wrapper closes the hole that emit()
swallows listener failures by design — the Bus keeps its guarantee without
buying it with silence.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 14:06:51 -05:00
chrnx 8c3844e577 docs(plans): design the observability contract for #10
The issue says green-tea ships no logging, metrics or tracing contract. The
mechanism is actually already there — Bus has 19 emission points across boot,
pipeline, streams, mesh and plugins, and plugins already subscribe to it. What
is missing is narrower and worse: no event carries request identity, so under
concurrency step events cannot be attributed; durationMs is declared in the
payload and written by nothing; there are no request-level events for step
events to hang from; and a failing step reports as name: 'pipeline'.

That reframes the work. A logger, a metrics exporter and an OpenTelemetry
bridge are not three features, they are three consumers of one corrected event
stream — which is a sharper reason for #10's 'one design, not six' than the
issue had, and it puts most of the work in bus.ts and pipeline.ts rather than
in new files.

Five decisions settled with their reasoning, including why the logger cannot be
an ordinary provider (it must outlive the graph to report the graph failing to
boot) and why route labels carry the pattern rather than the URL (a metrics
consumer labelling on raw paths takes down the backend, not the app).

Three questions left open for review rather than answered alone, the sharpest
being where a request span ends on a streaming route — the same boundary #21
hit, which should be answered once for both.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:27:36 -05:00
chrnx f97ac8098b docs(plans): record the #15 decision and split out shutdown extensibility
The plan asked Task 2.3 to decide between two answers; the decision and what
the runtimes actually allow now sit in it, so the next reader is not re-deriving
either. The Deno constraint in particular was found by measurement and is not
in any issue.

Adds Task 2.5 for the plugin/provider teardown idea, kept out of the #15 work
on purpose: it needs a new await-aware surface on PluginApi, because the
existing Bus is a synchronous observer by design and cannot be made to hold up
a shutdown without losing the guarantee that makes it safe.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:18:06 -05:00
chrnx e4a2047a1e docs: describe the shutdown deadline, and who owns it per runtime
Closes #18. The three places that still described close() without a timeout —
the createapp reference table, the README bullet and the dependency-injection
inline comment — now say that in-flight work gets 10 seconds, then a warning
and a force-close.

Also documents what #18 deliberately deferred, now that #15 has decided it.
runtimes.md gains the per-runtime story: app.close() is Node-only, the servers
serveDeno()/serveBun() return carry the same close({ timeoutMs }), and edge has
nothing to close. Including the row that matters — Node and Bun cut the
remainder after the deadline, Deno returns and lets the process end it — since
a deadline that means two things is worse than one that admits it.

createApp({ shutdownTimeoutMs }) from #19 gets its row in the options table.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:17:19 -05:00
chrnx 586e14da72 feat(runtimes): a bounded close() on the Deno and Bun adapters
Closes #15, taking the second of the two answers it framed: app.close() stays
Node-only, and each transport that owns a handle offers the same close({
timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun
because they serve through app.fetch and never through listen(), and only the
transport can drain what it accepted. The warning there now names the
replacement instead of pointing at this issue.

The runtimes do not agree, and the code says so rather than averaging them:

Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves
between them like Node's closeAllConnections().

Deno cannot. Its two levers are mutually exclusive — aborting the serve signal
while shutdown() is pending throws BadResource from Deno's own listener,
uncaught and fatal under deno test. Measured on 2.9: abort alone is clean,
abort after shutdown is not. So on Deno the deadline bounds how long close()
waits, not when connections die, and both the type and the timeout warning say
that outright. Silently accepting an option that does less is the failure mode
AGENTS.md rules out.

closeWithDeadline is shared so the two cannot drift into different meanings of
the same timeoutMs, and it resolves on its own timer rather than awaiting the
force call — Bun's stop(true) was measured waiting out a handler with a pending
timer, which is exactly the unbounded wait the deadline exists to prevent.

serveDeno now owns the AbortController it serves with, chaining any caller
signal into it so neither party loses control; a test covers that. The Bun
ambient said stop() returns void, which was simply wrong.

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:03:09 -05:00
chrnx 91f349bef7 ci: publish to JSR from the same tag that publishes to npm
The @green-tea scope is claimed and the package is linked to this repository
on jsr.io, so the OIDC id-token the job already holds for npm Trusted
Publishing authenticates JSR too — no new secret.

Ordered around one asymmetry: npm allows an unpublish within 72 hours, JSR
versions are immutable and can never be replaced. So JSR goes last, where a
failure costs a re-run rather than a version number, and a dry run gates both
before either ships — JSR checks slow types and module structure that npm
never looks at, and finding that out mid-release leaves the tag half-shipped.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:59:45 -05:00
chrnx f96c2ad401 test: pin the JSR manifest to package.json
npm and JSR publish from the same tag but read their identity from different
files. Bump package.json alone and that tag ships one version to npm and the
previous one to JSR, with nothing failing — the drift the deno.json manifest
introduced, closed where the other publication-metadata pins already live.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:47:47 -05:00
chrnx a0fd74da34 ci: run the Deno, Bun and workerd suites on every push
package.json has defined test:deno, test:bun and test:edge for a while and CI
ran none of them, so 'runs everywhere' rested on whoever remembered to run
them locally. AGENTS.md even warned that npm test does not cover the other
runtimes without anything closing that gap.

Its own job rather than more steps on build, so a Bun failure reads as a Bun
failure instead of burying the Node lint output — the same reasoning that
places the audit where it is. fail-fast is off because which *other* runtime
broke is the useful half of the answer.

README and AGENTS.md now say the suites gate a merge, since the claim they
back is the headline one.

Refs: .specs/reports/green-tea-next-beta-trust-release.md section 7
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:46:51 -05:00
chrnx 1c5a908fb9 chore(types): name the decorator shapes so JSR sees no slow types
deno publish --dry-run reported 17 slow types across metadata.ts and
params.ts: two factories with inferred return types, and the fifteen exported
decorators built from them. Naming RouteDecorator and ArgDecorator fixes all
seventeen, since annotating each factory resolves its constants with it.

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

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

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

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:45:47 -05:00
chrnx 30f33b6383 fix(http): narrow buffered bodies to what the runtime's Response accepts
A Node Buffer is a Uint8Array at runtime, but its declared backing store is
ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only
ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This
is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went
unnoticed because every implementation is forgiving about it at runtime.

Re-views rather than copies: this is the buffered-response path, and a copy
per response would cost real throughput on the runtimes that have no other
adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands
back a window into a shared 8 KB pool, and dropping them returns the whole
pool. A direct test covers that; the static-serving one covers the integration.

The type is derived from Response's own constructor because BodyInit is not a
global under lib es2020 plus @types/node, though Response itself is.

Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:45:37 -05:00
chrnx 70bb9902dc ci: scope the publish audit gate to what actually ships
AGENTS.md states the rule and ci.yml implements it: npm audit --omit=dev
blocks, everything else reports. stage.yml and release.yml ran a bare
npm audit, so a dev-only advisory could hold a publish.

That drift stopped work twice. The nanoid advisory reached the tree through
tsup -> postcss -> nanoid, a build-tooling path that ships to nobody, and
fixing it was a precondition for a release it could not affect.

The full audit still runs with continue-on-error, so nothing goes unseen.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:38:20 -05:00
chrnx 9c3bc9574b docs(plans): plan the trust release from the four evaluation reports
The reports in .specs/reports/ were written independently and converge on
observability as the gap that matters most. Two things they demand had no
issue filed at all: CI never runs the Deno/Bun/edge suites that package.json
defines, so the multi-runtime claim has no evidence behind it, and explain()
returns each node's needs without ever naming what produced them.

Sequenced so the cheap phases land first and produce the material the
observability design needs. API freeze stays out: README already declares it
under 'next', and freezing a surface that is still missing its observability
contract would freeze the wrong thing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 12:38:12 -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
chrnx 31cafcc3fa Merge pull request 'chore(deps): bump nanoid to 3.3.18' (#39) from chore/nanoid-advisory into develop
CI / dco (push) Has been skipped
CI / dco (pull_request) Successful in 4s
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 33s
2026-08-12 19:10:36 +00:00
chrnx 4aae9c3e71 chore(deps): bump nanoid to 3.3.18 in both lockfiles
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 33s
Clears Dependabot alert 26. The advisory is real but our exposure is not:
nanoid arrives through postcss, under tsup at the root and under astro in
website/, so it never ships. Production dependencies of the package are
reflect-metadata and nothing else, and `npm audit --omit=dev` was already
green. Reaching the bug needs control of the size argument passed to nanoid,
which postcss calls with a fixed length.

Fixing it anyway because the alert costs more to keep explaining than to
close, and an open badge trains us to skim Dependabot. The next advisory
should be the only one sitting there.

Dependabot files it under website/ as runtime scope because website/package.json
lists astro under dependencies and has no devDependencies at all. Moving them
would stop that mislabelling, but that is a separate change.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-12 14:09:22 -05:00
chrnx 2e4712788b Merge pull request 'Merge contrib: app.close() timeout from an outside contributor' (#38) from contrib into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 34s
2026-08-12 19:03:23 +00:00
chrnx 9d95260706 chore(test): nest the close({ timeoutMs }) case inside its describe block
CI / dco (push) Has been skipped
CI / build (pull_request) Successful in 34s
CI / dco (pull_request) Successful in 4s
CI / build (push) Successful in 35s
The test landed one line below the closing brace of describe('graceful
shutdown'), so it ran at the top level instead of under the block it
belongs to. Placement only; the assertions are untouched.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-12 13:34:07 -05:00
ServeurGoat 3dcf784159 fix: add timeout to app.close()
Signed-off-by: YxnnXriel <yannariel13@gmail.com>
2026-08-12 13:33:10 -05:00
chrnx 7518a5a785 Merge pull request 'release: promote the contributor-facing docs and CI gates to main' (#37) from develop into main
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 34s
CI / dco (push) Has been skipped
2026-08-11 14:48:32 +00:00
chrnx da6099b0e6 Merge pull request 'docs: close the gaps an outside contributor falls into' (#36) from chore/contributor-friction into develop
CI / dco (push) Has been skipped
CI / dco (pull_request) Successful in 4s
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 34s
2026-08-11 14:41:02 +00:00
chrnx f200045fd7 chore: put a project address in the package metadata
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 35s
author had no email and bugs had no address, so the only contact npm could show for a
published package was a GitHub issues URL. bugs.email is a field npm actually reads and
npm bugs surfaces, which makes it the right home for the catch-all.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:32:32 -05:00
chrnx 18d441b3ec docs: set real response times and a disclosure window
3/10 days was a placeholder borrowed from policies written for teams with someone on
rotation. This project is one person, so 5/15 with an escalation address, and an explicit
release from embargo if that also goes unanswered. A reporter facing silence should not
have to guess whether they are allowed to publish.

Adds the 90-day window, which was the real omission: the reporter's question is when they
may disclose, and leaving it unstated invites them to assume CERT/CC's 45.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:07:53 -05:00
chrnx 3714f7befc ci: reject commits without a Signed-off-by
CONTRIBUTING said unsigned commits are rejected and nothing enforced it, so the DCO was
caught by hand at review time. That is a full round-trip for a trailer, on top of however
long the fork's first run waits for approval.

Own job, so it reports separately from the code gates and costs nothing on push. Presence
only: whether a trailer that doesn't match the author is acceptable is a reviewer's call,
whether one exists at all is not.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:03:03 -05:00
chrnx ab58c064d5 docs: document local setup and the runtime suites
CONTRIBUTING went from clone straight to 'make the change' and never said npm install.
That mattered more than it looks: prepare wires core.hooksPath to .githooks, and the
pre-commit hook runs lint and complexity:check. An external contributor without it gets
told by CI what the hook would have told them before the commit existed.

The runtime commands were only in AGENTS.md and the README, so an assistant reading the
repo was better briefed than the person sending the pull request.

Checklist and the CI list now match ci.yml, which had grown complexity:check and build
without either following.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:02:56 -05:00
chrnx 6fa40672c6 docs: add a code of conduct and a security policy
Both were absent. The code of conduct is Contributor Covenant 2.1 verbatim, with
enforcement pointed at compliance@, which sits outside the project team so a report
about a maintainer has somewhere to go that isn't that maintainer.

The security policy exists so an exploitable finding has a route that isn't a public
issue. States the scope, the response times we can actually hold to, and that there is
no bounty, rather than leaving someone to find that out after the work.

Issue chooser now surfaces both, plus support@ for questions that are about the
reporter's own app rather than a bug here.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 09:02:49 -05:00
chrnx 1bb82491bd docs: document the cognitive complexity gate
complexity:check was missing from the list of commands CI runs, so the first
external contributor to trip it hit a failure with no way to have seen it
coming, on a rule the docs never stated.

Says what the number measures and why nesting is what it punishes, so the fix
reads as extracting a helper rather than raising the threshold.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 08:47:57 -05:00
chrnx b08ecb66cc chore: ignore bun.lock
Bun writes it on install but nothing reads it: test:bun runs against the
node_modules npm installed, already pinned by package-lock.json. deno.lock
stays tracked because the Deno tests resolve npm:/jsr: specifiers against
registries, where a lockfile is the only thing making them reproducible.

It reached a pull request once already, at 1278 lines.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-11 08:47:50 -05:00
chrnx 9bff2a52c9 Merge pull request 'docs: contributions merge into develop, they no longer need rebasing' (#29) from docs/agents-merge-not-rebase into develop
CI / build (pull_request) Successful in 34s
CI / build (push) Successful in 34s
Promote → GitHub / push-github (push) Successful in 7s
2026-08-10 13:51:09 +00:00
chrnx 551e79a86c docs: contributions merge into develop, they no longer need rebasing
CI / build (pull_request) Successful in 35s
The rebase existed to keep `main`'s history out of `develop` back when the two
had drifted ten commits apart. Fast-forward-only promotions closed that gap
hours after this file was written, and with `develop` and `main` on the same
commit a merge drags nothing in — so rebasing now only rewrites a
contributor's SHAs and drops `contrib` out of `main`'s ancestry, which is what
forces the force-push at reset time.

Proven on the first contribution through the route: the author's commits are
in `develop` under their original hashes, `main` is still an ancestor, and the
reset ahead is a plain fast-forward.

Hotfixes remain the exception, since they reach `main` without passing through
`develop`, so the rebase guidance stays for that case.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-10 08:50:43 -05:00
chrnx 61bef36d60 Merge pull request 'feat: concurrent connection limits, from the first external contribution' (#28) from contrib into develop
CI / build (push) Successful in 34s
2026-08-10 13:41:08 +00:00
chrnx 024b0a79fd Merge pull request #16 from hgshreyas/feature/max-connections
CI / build (push) Successful in 34s
CI / build (pull_request) Successful in 34s
feat: add concurrent connection limits
2026-08-10 08:32:04 -05:00
hgshreyas 8c781c1258 fix: treat non-positive connection limits as unlimited
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-10 16:14:07 +05:30
chrnx 84a2a29ed6 Merge pull request 'docs: make the base-branch reminder visible in the PR template' (#26) from docs/pr-template-base-branch into develop
CI / build (pull_request) Successful in 34s
Promote → GitHub / push-github (push) Successful in 5s
CI / build (push) Successful in 33s
2026-08-09 16:52:18 +00:00
chrnx 9d8e970c85 docs: make the base-branch reminder visible in the PR template
CI / build (pull_request) Successful in 34s
It sat inside an HTML comment, so it vanished the moment the description
rendered. The second external pull request filled in the checklist and still
targeted `main` — the template was read, the one line that mattered was not.

Now it is a visible blockquote the author is asked to delete, and a checklist
item, so choosing the base is an explicit tick rather than something to skim
past on the way to the boxes.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-09 11:51:56 -05:00
hgshreyas 9e5e5cffe9 feat: add concurrent connection limits
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-09 17:27:47 +05:30
chrnx beec350fcd Merge pull request 'docs: add AGENTS.md and an AI assistance policy' (#24) from docs/agent-guidance into develop
CI / build (pull_request) Successful in 34s
Promote → GitHub / push-github (push) Successful in 5s
CI / build (push) Successful in 34s
Reviewed-on: #24
2026-08-09 05:45:30 +00:00
chrnx 37693246d7 docs: write down the release procedure and where AI assistance stands
CI / build (pull_request) Successful in 34s
Nothing recorded how this repository is actually run, so every rule lived in
one head and had to be rediscovered. AGENTS.md now carries the two-forge
topology, why promotions are fast-forward-only, how to tell a genuinely ahead
branch from pre-rebase duplication, and the runtime and dependency constraints
that reviews keep enforcing by hand. CLAUDE.md points at it rather than
repeating it, so the two cannot drift.

The AI section in CONTRIBUTING is neither a prohibition nor a disclosure rule.
Assistants are welcome and there is nothing to declare. What it asks is that
you read the diff before sending it, because a person reads every line that
lands here and a diff its own author skipped turns their review into
proofreading. The four failure modes listed are the ones this codebase
actually sees — added dependencies, Node-only assumptions, deleted reasoning,
missing tests — and three of the four were live in a real pull request the day
this was written.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-09 00:32:48 -05:00
chrnx 1b8f2f3140 Merge pull request 'docs: document the two-forge flow, add PR and issue templates' (#21) from docs/contribution-flow into develop
CI / build (pull_request) Successful in 34s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 33s
Reviewed-on: #21
2026-08-08 22:42:10 +00:00
chrnx e820954ea8 Merge branch 'develop' into docs/contribution-flow
CI / build (pull_request) Successful in 34s
2026-08-08 22:41:54 +00:00
chrnx 324ddf0d61 Merge pull request 'ci: gate on what we ship, and run the audit after the code checks' (#20) from chore/ci-audit-gate into develop
CI / build (push) Successful in 34s
Reviewed-on: #20
2026-08-08 22:41:34 +00:00
chrnx f2db461187 docs: tell contributors where their changes go, and add the templates
CI / build (pull_request) Failing after 11s
CONTRIBUTING described GitFlow as though there were one forge. There are two,
and nothing said so: an outside contributor reading it had no way to learn
that GitHub is a mirror of `main` and that pull requests belong on `contrib`.
The first external PR duly went to `main`, which was our omission rather than
theirs.

The templates carry the parts that keep being repeated by hand — sign-off,
the local check commands, and the two failures that a graph framework invites:
an implementation growing an option that its public interface never declares,
and behavior that works on Node while silently doing nothing on Deno and Bun.

Blank issues stay enabled. Scope and placement discussions are most of what
gets filed here and they don't fit a bug form.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:47 -05:00
chrnx 55263f2d97 ci: scope the audit gate to shipped dependencies, and run it last
CI / build (pull_request) Successful in 43s
`npm audit` sat fifth of fifteen steps, so any advisory anywhere in the tree
skipped lint, typecheck, tests and build. A high in a vitest transitive was
enough to hide whether the code itself was correct — and for external
contributors, whose runs need approval before they see anything at all, that
turned a red X into no information.

Severity is the wrong axis: a critical in the test runner reaches nobody,
while a high in `reflect-metadata` reaches everyone. Scope is the right one.
Production dependencies block; build tooling reports and moves on.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:46 -05:00
chrnx 506dedb624 ci: run checks on the contrib branch
External contributions land on `contrib`, and a PR targeting a branch absent
from the trigger list gets no checks at all — leaving contributors without the
feedback that would have caught the failure themselves.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-08 17:39:45 -05:00
chrnx 1030109efa Merge pull request 'release: promote docs and audit fixes to main' (#18) from develop into main
CI / build (push) Failing after 11s
Promote → GitHub / push-github (push) Successful in 6s
CI / build (pull_request) Failing after 15s
Reviewed-on: #18
2026-08-07 21:58:41 +00:00
chrnx 08d92f5de7 Merge pull request 'docs: problem-first README, declared observability gap, docs analytics' (#16) from docs/observability-scope-and-analytics into develop
CI / build (push) Successful in 33s
CI / build (pull_request) Successful in 33s
Reviewed-on: #16
2026-08-07 19:27:49 +00:00
chrnx 8babcb9554 Merge pull request 'fix(release): unblock npm provenance publication' (#15) from hotfix/npm-release-provenance into main
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 35s
Reviewed-on: #15
2026-08-03 03:48:19 +00:00
chrnx 6dd23ed874 chore(release): reconcile main before npm fix
CI / build (pull_request) Successful in 33s
Merge the current public main history while preserving develop's mutable Verdaccio staging policy for the npm provenance hotfix.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:45:51 -05:00
chrnx 05e59383f1 Merge pull request 'release: promote 26.8.0-beta.0 to main' (#13) from release/26.8.0 into main
Promote → GitHub / push-github (push) Successful in 6s
CI / build (push) Successful in 35s
Reviewed-on: #13
2026-08-03 02:57:35 +00:00
chrnx 97a146a758 Merge branch 'main' into release/26.8.0
Stage → Verdaccio / publish-stg (push) Failing after 21s
CI / build (pull_request) Successful in 33s
2026-08-03 02:57:15 +00:00
chrnx aa3402bd84 ci(release): stage prereleases from release branches
Stage → Verdaccio / publish-stg (push) Successful in 21s
CI / build (pull_request) Successful in 36s
Keep develop free to accept concurrent changes while Verdaccio validates an immutable release candidate. Audit dependencies and reject stable versions before publishing.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:43:16 -05:00
chrnx 813a29001b Merge pull request 'release: merge docs refresh to main' (#11) from develop into main
Stage → Verdaccio / publish-stg (push) Successful in 22s
CI / build (push) Successful in 23s
Promote → GitHub / push-github (push) Successful in 7s
2026-07-18 21:09:01 +00:00
chrnx 8d923e053c Merge pull request 'release: OIDC publishing + beta dist-tag → main' (#9) from develop into main
CI / build (push) Successful in 24s
Promote → GitHub / push-github (push) Successful in 7s
Stage → Verdaccio / publish-stg (push) Successful in 22s
2026-07-18 20:18:07 +00:00
chrnx 523e302012 Merge pull request 'release: promote stage fix to main' (#7) from develop into main
CI / build (push) Successful in 24s
Stage → Verdaccio / publish-stg (push) Successful in 27s
Promote → GitHub / push-github (push) Successful in 7s
2026-07-18 19:09:16 +00:00
chrnx e068426582 Merge pull request 'release: promote develop → main (staging)' (#5) from develop into main
CI / build (push) Successful in 24s
Promote → GitHub / push-github (push) Successful in 6s
Stage → Verdaccio / publish-stg (push) Failing after 26s
2026-07-18 19:01:48 +00:00
152 changed files with 11042 additions and 9712 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
---
name: Bug report
about: Something behaves differently from what the docs or the types promise
labels: bug
---
## What happened
## What you expected
## Minimal reproduction
The smallest module and route that shows it:
```ts
```
## Environment
- green-tea version:
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- OS:
<!--
If it works on one runtime and not another, say which. That difference is
usually the bug rather than a detail of it.
-->
+14
View File
@@ -0,0 +1,14 @@
# Design questions, scope decisions and "should this live in core?" threads don't fit a
# bug form, and they are most of what gets filed here. Keep the blank option available.
blank_issues_enabled: true
contact_links:
- name: Security vulnerability
url: https://github.com/Expressive-Tea/green-tea/security/advisories/new
about: Report it privately instead. Never in a public issue — see SECURITY.md.
- name: Documentation
url: https://green-tea.expressive-tea.io/docs/
about: How to wire a route, a module, a plugin or a runtime adapter.
- name: Help with your own app
url: mailto:support@expressive-tea.io
about: Implementation questions about your code rather than a bug in green-tea.
+16
View File
@@ -0,0 +1,16 @@
> **Base branch:** on GitHub this must target `contrib`, not `main`. You can still change it above, before you submit — and [here is why](https://github.com/Expressive-Tea/green-tea/blob/main/CONTRIBUTING.md#where-to-send-your-changes). Delete this line once the base is right.
## What this changes
<!-- A sentence or two, on the why rather than the what. -->
Closes #
## Checklist
- [ ] The base branch above is `contrib`
- [ ] Commits are signed off (`git commit -s`)
- [ ] `npm run lint`, `npm run format:check`, `npm run typecheck`, `npm test`, `npm run complexity:check` and `npm run build` pass locally
- [ ] New behavior has a test
- [ ] A new public option or method is also declared in `src/app/types.ts`, and noted in `README.md`
- [ ] Behavior is the same on Node, Deno and Bun — or the difference is deliberate, and said out loud here
+84 -7
View File
@@ -1,10 +1,40 @@
name: CI name: CI
on: on:
push: push:
branches: [develop, main] branches: [develop, main, contrib]
pull_request: pull_request:
branches: [develop, main] branches: [develop, main, contrib]
jobs: jobs:
# Separate job so a missing sign-off reports on its own and doesn't hide behind the code
# gates, and so it costs nothing on push. Checks that the trailer is present, not that it
# matches the author — a mismatch is a judgement call for a reviewer, an absent trailer
# is not, and telling a contributor on their first push beats telling them on review.
dco:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Every commit needs a Signed-off-by
env:
RANGE: ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}
run: |
missing=0
for sha in $(git rev-list --no-merges "$RANGE"); do
if ! git show -s --format='%(trailers:key=Signed-off-by,valueonly)' "$sha" | grep -q '[^[:space:]]'; then
echo "::error::no Signed-off-by: $(git show -s --format='%h %s' "$sha")"
missing=1
fi
done
if [ "$missing" = 1 ]; then
echo "We use the DCO instead of a CLA. See CONTRIBUTING.md."
echo "Fix the whole branch with: git rebase --signoff ${{ github.event.pull_request.base.sha }}"
echo "Then: git push --force-with-lease"
exit 1
fi
echo "All commits signed off."
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -13,16 +43,63 @@ jobs:
with: with:
node-version: '18' node-version: '18'
- run: npm ci - run: npm ci
- run: npm audit
- run: npm run lint - run: npm run lint
- run: npm run format:check - run: npm run format:check
- run: npm run complexity:check - run: npm run complexity:check
- run: npm run typecheck - run: npm run typecheck
- run: npm test - run: npm test
- run: npm run build - run: npm run build
# Supply chain, deliberately after the code gates: an advisory published by a third party
# must never decide whether a contributor gets to see their own lint and typecheck output.
# Only what we ship blocks — with `reflect-metadata` as the sole runtime dependency, a
# production advisory is rare and genuinely reaches users. Build tooling only reports.
- run: npm audit --omit=dev
- run: npm audit
continue-on-error: true
# Runs everywhere is the headline claim, so it gets tested rather than asserted. `npm test` is
# Node only: a change to shared code can pass it and still be broken on Deno or Bun, which is
# exactly why these suites exist separately. Leaving them out of CI meant the claim rested on
# whoever remembered to run them locally.
#
# Its own job, not more steps on `build`, for the reason the audit sits where it does: a Bun
# failure should read as a Bun failure instead of burying the Node lint output.
runtimes:
runs-on: ubuntu-latest
strategy:
# One runtime breaking must not cancel the others — which one else broke is the useful part
# of the answer, and a cancelled job reports as if it had never been asked.
fail-fast: false
matrix:
runtime: [deno, bun, edge]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: '22.12' node-version: '22'
- run: npm ci --prefix website # All three need the dependency tree: the edge suite drives workerd from a Node process, and
- run: npm audit --prefix website # Deno and Bun resolve `reflect-metadata` out of node_modules like any other import.
- run: npm run docs:build - run: npm ci
- if: matrix.runtime == 'deno'
uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@v2
- run: npm run test:${{ matrix.runtime }}
# JSR's gate, moved off the release tag. `release.yml` runs this too and keeps doing so —
# that copy protects an immutable JSR version and is the last thing standing between a tag
# and a version number that can never be replaced. This copy exists because that one runs
# too late to be useful as feedback: a slow type or a Deno type error would otherwise land
# on `main` in silence and surface while cutting a release, which is the same "least time
# to judge a fix" the audit steps above are ordered to avoid.
#
# It is a second compiler over the same source, not a formality. `npm run typecheck` is tsc
# with this repo's tsconfig; this is Deno's checker with Deno's lib, and it is what found
# the `BodyInit` hole on the fetch path that tsc accepted. JSR serves `src/` directly, so
# anything it rejects is something a JSR consumer would have received.
#
# 0.68s against 2.0s for the whole vitest suite. No `--allow-dirty`: a checkout is clean,
# and if it somehow is not, that is worth failing on.
- if: matrix.runtime == 'deno'
run: deno publish --dry-run
+17 -13
View File
@@ -1,13 +1,22 @@
name: Promote → GitHub name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub # Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` to the public GitHub repo — develop and
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's # feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers # would expose every branch).
# its release workflow (production publish). #
# 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: on:
push: push:
branches: [main] branches: [main]
tags: ['v*']
jobs: jobs:
push-github: push-github:
@@ -16,15 +25,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 # full history + tags for a clean push fetch-depth: 0 # full history for a clean push
- name: Push main + tags to GitHub - name: Push main to GitHub
env: env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }} GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: | run: |
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git" 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 "HEAD:refs/heads/main"
git push github "refs/tags/${{ github.ref_name }}"
else
git push github "HEAD:refs/heads/main"
git push github --tags
fi
+89 -5
View File
@@ -12,9 +12,11 @@ jobs:
publish-prod: publish-prod:
if: ${{ github.server_url == 'https://github.com' }} if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
PKG: '@green-tea/core'
permissions: permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance) id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read contents: write # create the GitHub release for this tag
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
@@ -23,13 +25,95 @@ jobs:
registry-url: 'https://registry.npmjs.org' registry-url: 'https://registry.npmjs.org'
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing - run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
- run: npm ci - run: npm ci
# Same scoped gate as ci.yml: only what we ship blocks a publish. With `reflect-metadata`
# as the sole runtime dependency, a blocking advisory here is rare and genuinely reaches
# users; a build-tooling one never does. The full audit still reports.
- run: npm audit --omit=dev
- run: npm audit - run: npm audit
continue-on-error: true
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first. # `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token. # No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest` # A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
# never points at a beta; a stable version publishes under `latest`. # never points at a beta; a stable version publishes under `latest`.
- name: Publish - uses: denoland/setup-deno@v2
with:
deno-version: v2.x
# Gate both registries before either one ships. JSR checks things npm never looks at — slow
# 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: | run: |
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')") VERSION=$(node -p "require('./package.json').version")
echo "dist-tag: $TAG" CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
npm publish --access public --tag "$TAG" # 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
# from deno.json, which `test/package-metadata.test.ts` pins to package.json — JSR has no
# 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: |
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
+18 -2
View File
@@ -1,12 +1,18 @@
name: Stage → Verdaccio name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release # Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag. # 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 # Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version. # 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: on:
push: push:
branches: ['release/**'] branches: ['release/**']
tags: ['v*']
jobs: jobs:
publish-stg: publish-stg:
@@ -18,7 +24,12 @@ jobs:
with: with:
node-version: '22' node-version: '22'
- run: npm ci - run: npm ci
# Same scoped gate as ci.yml: only what we ship blocks a publish. A `tsup` advisory
# reaches nobody, and holding a release candidate for one is how staging stalls on work
# that has nothing to do with the package. The full audit still reports.
- run: npm audit --omit=dev
- run: npm audit - run: npm audit
continue-on-error: true
- name: Validate release candidate - name: Validate release candidate
run: npm run prepublishOnly run: npm run prepublishOnly
- name: Publish prerelease to Verdaccio - name: Publish prerelease to Verdaccio
@@ -27,6 +38,11 @@ jobs:
run: | run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version") 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 case "$VER" in
*-*) ;; *-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;; *) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
+7 -3
View File
@@ -11,9 +11,13 @@ coverage/
.env .env
.env.* .env.*
# Astro (docs site)
.astro/
website/dist/
# Edge (Miniflare) test bundle artifact # Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs test/edge/_worker.mjs
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
# deno.lock IS tracked, and that asymmetry is deliberate — the Deno tests import `npm:` and
# `jsr:` specifiers that Deno resolves against registries, so only a lockfile makes them
# reproducible. Bun resolves the same package.json npm does.
bun.lock
+132
View File
@@ -0,0 +1,132 @@
# AGENTS.md
Guidance for AI coding assistants working in this repository. Claude Code, Codex, Cursor and anything else that reads this file.
If you are an assistant: a person reads every line of what you produce before it lands, and the person submitting it signs off on it. Make that reading worth their time — leave the reasoning visible, don't quietly widen the scope you were asked for, and say what you were unsure about instead of smoothing over it. The "Working with AI assistance" section of `CONTRIBUTING.md` applies to your output.
## What this is
`@green-tea/core` — a type-safe HTTP framework where the API is a dependency graph rather than a middleware chain. You declare what each step needs and provides; the framework computes execution order, fails at boot if something is missing, and can print the whole pipeline. Runs on Node, Deno, Bun and the edge from one codebase.
**Hard constraint: one runtime dependency.** `reflect-metadata`, and nothing else. `busboy` and `ws` are peer dependencies. Anything that would add a third belongs in a plugin, not in core.
## Commands
```bash
npm run lint # eslint
npm run format:check # prettier, src/**/*.ts only
npm run typecheck # must be clean; includes the compile-time-guarantee type test
npm test # vitest
npm run build # tsup
npm run complexity:check
npm run test:deno # the other runtimes are NOT covered by `npm test`
npm run test:bun
npm run test:edge
```
Run the first four before proposing anything as finished. The runtime suites stay separate commands on purpose — a change to shared code that passes `npm test` may still be broken on Deno or Bun — but they are no longer optional: CI runs all three on every push and each one gates a merge. Run them yourself for anything touching `src/http/`, the adapters, or `src/mesh/`, rather than finding out from CI.
## Two forges
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
│
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. 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.
`develop` and `main` on Gitea have direct push disabled with an empty whitelist, so nobody can push to them, admins included. Advance them by opening a PR and merging it.
## Procedure
**Promotions are fast-forward-only.** `develop → main` merges with Gitea's fast-forward-only style, so `main` becomes an exact copy of `develop` and no commit is ever born on `main`. This is not a preference: merge-style promotions created seven of the ten commits of drift that had to be cleaned up in August 2026, because each one lived on `main` and never travelled back. Release boundaries are marked by `v*` tags, not by promotion commits.
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
**Diagnosing "this branch is ahead of main".** Usually it is pre-rebase duplication, not unmerged work: the same content under different SHAs, because contributions are rebased on their way into `develop`. Confirm before acting:
```bash
git diff <branch> <main> -- <suspect file> # empty means the content is already in main
```
Merging such a branch to "recover" the commits duplicates the work and drags stale history along.
**External contributions.** They arrive on GitHub `contrib`. Merge the pull request there, mirror that branch to Gitea, then open a `contrib → develop` pull request and merge it. Merge rather than rebase: because promotions are fast-forward-only, `develop` and `main` are the same commit, so there is no main-only history for a merge to drag in. Rebasing would rewrite the contributor's SHAs for no gain and push `contrib` out of `main`'s ancestry, which then costs a force-push at reset time. Merging keeps their commits reaching `main` under their own name and hash.
The exception is a `hotfix/*`, which lands on `main` without passing through `develop` and leaves the two out of step. Back-merge before taking a contribution through, or rebase that one and accept the force-push. If you do rebase, take the commit range from the pull request itself and never "everything since main": if a second contributor branched from `contrib` after the first one merged, the broad range sweeps up work that isn't theirs.
**After every promotion, reset *both* `contrib` branches to `main`.** GitHub's is where external work lands; Gitea's is its mirror, and the easy one to forget because nothing there refuses the push. Normally this is an ordinary fast-forward, since `contrib` is already inside `main`'s history. It only needs a force-push when SHAs were rewritten on the way in — and GitHub then refuses it even for admins, so that branch's protection has to be lifted and restored around the reset.
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.
**The forges disagree about where workflows come from.** GitHub reads `pull_request` workflows from the base branch, so a workflow fix cannot validate itself and must reach the base before it gates anything. Gitea reads from the head. Likewise, `continue-on-error` steps report as `success` on GitHub, hiding the advisory in the log, but as `failure` with the job still green on Gitea.
GitHub does not run workflows on fork pull requests until a maintainer approves them. A contributor's first push may sit with no checks at all.
## Conventions
- Conventional Commits, focused on the *why*. Every commit signed off (`git commit -s`) — the project uses a DCO, and unsigned commits are rejected. No AI co-authoring attribution.
- 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` **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 ## Environment
- **Date**: 2026-07-07 - **Date**: 2026-09-02
- **Commit**: fe1831a - **Commit**: 8c5855c
- **Node**: v22.22.2 - **Node**: v22.22.2
- **OS**: darwin - **OS**: darwin
- **CPU**: Apple M4 Max (16 cores) - **CPU**: Apple M4 Max (16 cores)
- **RAM**: 69 GB - **RAM**: 69 GB
- **Core-pinned**: no - **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 > **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 > 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 | | 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 | | raw-http | 119,357 | 0.00 | 1.00 | 1.00 | 0.4% | 118,560–120,067 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 | | nestjs-fastify | 98,039 | 0.00 | 1.00 | 2.00 | 1.2% | 96,073–99,680 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 | | fastify | 89,097 | 1.00 | 1.00 | 2.00 | 0.1% | 88,864–89,207 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 | | green-tea | 87,473 | 1.00 | 2.00 | 2.00 | 0.3% | 86,903–87,607 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 | | express | 24,677 | 3.00 | 5.00 | 8.00 | 0.2% | 24,647–24,769 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 | | nestjs-express | 21,879 | 4.00 | 6.00 | 9.00 | 0.2% | 21,845–21,953 |
### Route param ### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | 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 | | raw-http | 120,905 | 0.00 | 1.00 | 1.00 | 0.5% | 119,927–121,713 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 | | nestjs-fastify | 91,849 | 1.00 | 1.00 | 2.00 | 0.3% | 91,825–92,599 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 | | fastify | 88,317 | 1.00 | 1.00 | 2.00 | 0.2% | 87,997–88,439 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 | | green-tea | 86,595 | 1.00 | 2.00 | 2.00 | 0.2% | 86,368–86,880 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 | | express | 24,200 | 3.00 | 5.00 | 8.00 | 0.2% | 24,158–24,260 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 | | nestjs-express | 21,182 | 4.00 | 6.00 | 9.00 | 0.7% | 21,150–21,518 |
### Pipeline (3 steps) (approximation) ### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | 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 | | raw-http | 118,996 | 0.00 | 1.00 | 1.00 | 0.3% | 118,583–119,584 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 | | nestjs-fastify | 89,527 | 1.00 | 2.00 | 2.00 | 1.0% | 87,572–90,028 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 | | fastify | 86,671 | 1.00 | 1.00 | 2.00 | 0.1% | 86,490–86,793 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 | | green-tea | 80,079 | 1.00 | 2.00 | 2.00 | 0.2% | 80,026–80,375 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 | | express | 24,325 | 3.00 | 5.00 | 8.00 | 0.2% | 24,281–24,407 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 | | nestjs-express | 20,872 | 4.00 | 6.00 | 9.00 | 0.2% | 20,801–20,940 |
### POST JSON + validation ### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s | | 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 | | raw-http | 104,288 | 0.00 | 1.00 | 1.00 | 0.4% | 103,776–104,916 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 | | green-tea | 70,298 | 1.00 | 2.00 | 3.00 | 1.0% | 68,972–70,607 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 | | fastify | 65,905 | 1.00 | 2.00 | 3.00 | 0.3% | 65,725–66,367 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 | | nestjs-fastify | 63,318 | 1.00 | 2.00 | 3.00 | 0.9% | 62,454–63,747 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 | | express | 20,297 | 4.00 | 6.00 | 10.00 | 0.5% | 20,158–20,414 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 | | nestjs-express | 18,788 | 5.00 | 7.00 | 10.00 | 0.3% | 18,684–18,862 |
## Step-scaling (green-tea) ## Step-scaling (green-tea)
| Path | Steps | req/s | | Path | Steps | req/s |
| --- | --- | --- | | --- | --- | --- |
| /steps/0 | 0 | 92,282 | | /steps/0 | 0 | 88,108 |
| /steps/3 | 3 | 81,530 | | /steps/3 | 3 | 79,951 |
| /steps/5 | 5 | 71,994 | | /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) ## Cost of secure-by-default (green-tea)
| Label | req/s | | Label | req/s |
| --- | --- | | --- | --- |
| security:false (parity) | 98,093 | | security:false (parity) | 87,473 |
| security:true (default) | 92,998 | | 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 > 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 > `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 `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 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. 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.
+380 -5
View File
@@ -6,11 +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 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. 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 ## [26.8.0-beta.0] - 2026-08-02
### Added ### Added
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded - **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 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 ▸ malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
@@ -30,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. - **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. - **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`). - **`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 (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** 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 supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
`nodejs_compat` does not provide. `nodejs_compat` does not provide.
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest` - **`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. 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 - **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
(`retry-after`, `etag`, …) without a special case in the error renderer. (`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 - **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
@@ -53,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()`. pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
### Fixed ### Fixed
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade; - 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. 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 - Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
@@ -88,6 +460,7 @@ npm treats versions as semver and semver forbids leading zeros.
`request:step:leave`. `request:step:leave`.
### Changed ### Changed
- Root, runtime-only, and website dependency audits are clean after supported package updates and - 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 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. GitHub OIDC release workflow audits immediately before its publish gate.
@@ -112,6 +485,7 @@ First public beta, published under the npm `beta` dist-tag. The API may still
change before the stable release. change before the stable release.
### Added ### Added
- **Transport security** — native TLS termination (https/wss), CORS with a - **Transport security** — native TLS termination (https/wss), CORS with a
guarded preflight and credentials-safe origins, secure-by-default response guarded preflight and credentials-safe origins, secure-by-default response
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
@@ -131,7 +505,7 @@ change before the stable release.
`405 Method Not Allowed` with an `Allow` header when a path exists under a `405 Method Not Allowed` with an `Allow` header when a path exists under a
different method. different method.
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/ - **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
@abort`, plus `@header('name')` as a singular alias of `@headers`. @abort`, plus `@header('name')` as a singular alias of `@headers`.
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast - **Streams** — SSE / ndjson / WebSocket duplex over a multicast
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs. `AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
- **Graph introspection** — `app.explain(route)`, `app.graph()`, - **Graph introspection** — `app.explain(route)`, `app.graph()`,
@@ -153,6 +527,7 @@ change before the stable release.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5, - **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md). 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.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 [26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
+3
View File
@@ -0,0 +1,3 @@
# CLAUDE.md
See [AGENTS.md](./AGENTS.md). It is the same guidance, kept in one place so the two files cannot drift apart.
+89
View File
@@ -0,0 +1,89 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **compliance@expressive-tea.io**. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
If you would rather write to a named person than to an address, the project lead reads
diego.resendez@expressive-tea.io. Reports about a maintainer, including the project lead,
should go to compliance@expressive-tea.io, which is not maintained by the project team.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+112 -4
View File
@@ -2,6 +2,36 @@
Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**. Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**.
## Where to send your changes
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main` and release tags, and nothing else. Which branch you target depends on where you are.
**From GitHub, if you are an outside contributor:** open your pull request against **`contrib`**. Not `main`. `main` on GitHub is a mirror of released code, and merging into it puts the two forges out of sync and breaks the next release push. A maintainer reviews on `contrib` and then carries your commits upstream into Gitea's `develop`, with your authorship and your sign-off intact.
**From Gitea, if you have access:** follow the branch model below.
### Worked example
```bash
# fork Expressive-Tea/green-tea on GitHub, then
git clone git@github.com:<you>/green-tea.git
cd green-tea
git remote add upstream https://github.com/Expressive-Tea/green-tea.git
git fetch upstream
# branch from contrib, not from main
git checkout -b fix/close-timeout upstream/contrib
# ... make the change, add a test ...
git commit -s -m "fix: add a timeout to app.close()"
git push origin fix/close-timeout
```
Then open the pull request with **`contrib`** as the base branch.
`contrib` tracks released code, so it is reset to `main` after each release. If your branch has been open across one, rebase onto the new `contrib` before pushing again.
## Developer Certificate of Origin (DCO) ## Developer Certificate of Origin (DCO)
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork. We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork.
@@ -26,6 +56,34 @@ To sign off a range you forgot to sign:
git rebase --signoff <base> git rebase --signoff <base>
``` ```
Or, for the commit you just made:
```bash
git commit --amend -s
git push --force-with-lease
```
## Working with AI assistance
Use one if it helps. There is no permission to ask for and nothing to declare.
What we do ask is that you read what it hands you before it becomes a pull request. Every line that lands here is reviewed by a person, by hand, and usually that person is one person. A diff its own author hasn't read moves that work onto them, and turns review into proofreading — which is the thing review is worst at.
So go through the diff the way you would go through a stranger's, because that is what it is. If you can't say why a line is there, it isn't ready to send. That's the whole of it.
**What assistants tend to get wrong here in particular** — worth checking before you push:
- They add dependencies. Core has one runtime dependency, and that is a design constraint rather than an oversight.
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` does not cover them.
- They delete comments they read as redundant. In this codebase a comment usually carries reasoning the code can't show on its own.
- They skip the test.
**Where you're unsure, say so** — not as a disclosure, as a pointer. "I'm not confident about the Deno path here" tells a reviewer where to spend their attention, and that is worth more to them than a pull request that merely looks clean.
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the work under this project's license, and that stays true however the text was produced.
If your assistant reads repository instructions, `AGENTS.md` has the conventions and the architecture notes.
## Branch model (GitFlow) ## Branch model (GitFlow)
- `main` — production-ready, protected. No direct pushes. - `main` — production-ready, protected. No direct pushes.
@@ -33,6 +91,7 @@ git rebase --signoff <base>
- `feature/<name>` — branch from `develop`. - `feature/<name>` — branch from `develop`.
- `hotfix/<name>` — branch from `main`. - `hotfix/<name>` — branch from `main`.
- `release/<version>` — release stabilization. - `release/<version>` — release stabilization.
- `contrib` — GitHub only. Where outside contributions land before a maintainer moves them to `develop`.
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.) `main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
@@ -40,17 +99,66 @@ git rebase --signoff <base>
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution. Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
## Before you open an MR ## Local setup
Node 18 or newer, which is what `engines` requires and what CI runs.
```bash ```bash
npm test # all tests must pass npm install
```
That does one thing worth knowing about: the `prepare` script points `core.hooksPath` at
`.githooks/`, which installs a pre-commit gate. The gate formats and lint-fixes your staged
sources automatically, then refuses the commit if `npm run lint` or `npm run complexity:check`
fails. It is there so CI tells you nothing you couldn't have heard locally. Confirm it took:
```bash
git config core.hooksPath # should print .githooks
```
If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you install with
something other than npm, check this before your first commit rather than after.
`npm test` runs the Node suite under Vitest. The other three runtimes have their own commands
and their own toolchains, and none of them run in CI:
```bash
npm run test:deno # needs deno
npm run test:bun # needs bun
npm run test:edge # Miniflare
```
You are not expected to install all three to fix a typo. You are expected to run the one your
change touches, and to say in the pull request which ones you ran.
## Before you open a pull request
Run what CI runs:
```bash
npm run lint
npm run format:check
npm run typecheck # must be clean — this includes the compile-time-guarantee type test npm run typecheck # must be clean — this includes the compile-time-guarantee type test
npm test # all tests must pass
npm run complexity:check
npm run build
``` ```
- Write tests for new behavior (TDD welcome). We use Vitest. - Write tests for new behavior (TDD welcome). We use Vitest.
- `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`. - Keep runtime dependencies at zero beyond `reflect-metadata`.
- New public API needs a doc note in `README.md`. - 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`, **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.
## Reporting issues ## Reporting issues
Open an issue with a minimal reproduction: green-tea version, Node version, and the smallest module/route that shows the problem. Open an issue with a minimal reproduction: green-tea version, runtime and version, and the smallest module/route that shows the problem.
**Except for security.** If what you found is exploitable, do not open an issue — an issue is world-readable the moment you press the button. Email security@expressive-tea.io or use the [private advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new). [`SECURITY.md`](./SECURITY.md) has the scope and what to expect back.
## Code of conduct
By taking part here you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md), which is the Contributor Covenant 2.1. Reports go to compliance@expressive-tea.io.
+68 -12
View File
@@ -7,8 +7,13 @@
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p> <p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
<p align="center"> <p align="center">
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br /> <b>Declare intent. Derive execution.</b><br />
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵 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> </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. - **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. - **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. - **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 ## 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. 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`). - **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. - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
@@ -109,8 +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. - **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. - **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. - **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, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. 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.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links. - **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 })`. 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. - **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. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -243,26 +278,46 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet. **Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about. **Observability is a contract, not an integration.** Core emits a correlated lifecycle event stream — every request gets an id (an incoming `x-request-id` is adopted, not replaced), every event carries it, and each step reports its own duration. `createApp({ logger })` takes any logger; the default writes structured JSON, or a readable line on a TTY. Nothing in core writes to `console`, which is enforced by a lint rule rather than a promise. `createApp({ logRequests: true })` logs a line per request, off by default.
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. **Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**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. **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 ## 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. - **[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. - **[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 ```bash
npm install npm install
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes npm test # vitest (Node only) — the fast loop, ~2s
npm run test:all # everything below, plus the JSR gate — the pre-push check
npm run test:deno # deno test } a change to shared code can pass `npm test`
npm run test:bun # bun test } and still be broken on one of these
npm run test:edge # workerd via miniflare
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test) npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/ (tsup: dual ESM + CJS) npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
``` ```
`npm test` stays Node-only on purpose: it is the loop you run constantly, and booting Deno, Bun and
workerd into it would tax every run to catch what CI already catches on every push. Nothing here is
unguarded — the `runtimes` job runs all three, and `deno publish --dry-run` gates JSR. `test:all` is
for the moment before you push, when you would rather find out locally.
That last one is a second type-checker, not a packaging formality: `npm run typecheck` is `tsc` with
this repository's config, while `deno publish --dry-run` is Deno's checker with Deno's lib plus JSR's
slow-types rules over the public API. JSR serves `src/` directly, so what it rejects is what a JSR
consumer would have received.
## Roadmap ## Roadmap
- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`. - ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
@@ -270,9 +325,10 @@ npm run docs:dev # the documentation site (website/)
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup. - ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`. - ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices. - ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. - ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. Every CI run exercises all four; the Deno, Bun, and workerd suites gate a merge exactly as the Node one does.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving. - ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes. - ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables. - **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
## Versioning ## Versioning
+68
View File
@@ -0,0 +1,68 @@
# Security Policy
## Reporting a vulnerability
Email **security@expressive-tea.io**. Please do not open a public issue for something
exploitable — an issue is world-readable from the moment you press the button, and that is
the one thing a security report cannot be.
Include whatever you have: the version, the runtime, and the smallest app that shows it.
A route, a module and a request is usually enough. If you have a working exploit, send it;
if you only have a suspicion, send that instead of sitting on it.
You can also report privately through GitHub's
[security advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new),
which reaches the same people.
## What happens next
Acknowledgement within **5 working days**. A verdict on whether we agree it is a vulnerability
within **15**. If we agree, you get the fix timeline and a heads-up before the advisory goes
public. If we don't, you get the reasoning rather than silence.
Those numbers are deliberately slower than the 24 to 48 hours you will see quoted elsewhere.
That figure comes from the CERT Guide to Coordinated Vulnerability Disclosure and describes
vendors and coordinators — organizations with someone on rotation. This project is one person.
A number that only holds in a good week is worse than an honest one.
Which is why there is an escape hatch, and you should use it. **If you have no acknowledgement
after 10 working days**, write directly to diego.resendez@expressive-tea.io. If that is also
met with silence, consider yourself released from any embargo and disclose as you see fit. You
will not have done anything wrong: a project that goes quiet on a security report has spent
whatever claim it had on your patience.
## Disclosure window
We ask for **90 days** from your report before public disclosure, or until the fix ships,
whichever comes first. That is the industry default and we are not asking you for more than
anyone else does. If the fix is out in a week, so is the advisory.
If a vulnerability is being actively exploited, the window is however long it takes us to ship,
and we will say so rather than hold you to 90 days while users are being attacked.
We publish a GitHub advisory for anything that affects a released version, and credit you by
the name you ask for. Say so if you would rather not be named.
There is no bug bounty and no money, which we would rather state here than leave you to find
out after the work.
## Supported versions
While the package is in beta, only the most recent `26.x.y-beta.N` receives fixes. There is no
backport channel yet; when the first stable ships, this section gets the real table.
## Scope
In scope: anything in `src/` that ships in the published package — route matching, the request
pipeline, body parsing and its limits, the security headers and CORS handling, TLS setup, the
WebSocket upgrade path, the mesh wire protocol, static file serving and view rendering.
Out of scope: the benchmarks in `bench/`, the documentation site (now its own repository,
[green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)), dev-only tooling, and
anything that requires an attacker to already control your application code. Advisories in
build-time dependencies are worth telling us about, but they are not vulnerabilities in
green-tea and we handle them as ordinary dependency updates.
A denial of service that needs no authentication is in scope. Reports that amount to "this
endpoint is slow under load" generally are not — but if you are unsure which one you have,
send it and let us decide.
+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[]; scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[]; stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; 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'); 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'); 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 { function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |'; const header = '| Label | req/s |';
const divider = '| --- | --- |'; const divider = '| --- | --- |';
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
} }
export function renderMarkdown(data: RenderData): string { export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data; const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
return [ return [
renderLeaderboard(scenarios), renderLeaderboard(scenarios),
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
'', '',
renderScenarios(scenarios), renderScenarios(scenarios),
renderStepScaling(stepScaling), renderStepScaling(stepScaling),
renderRuntimes(runtimes),
renderSecureCost(secureCost), renderSecureCost(secureCost),
renderMethodology(), renderMethodology(),
].join('\n'); ].join('\n');
+206 -144
View File
@@ -1,7 +1,7 @@
{ {
"env": { "env": {
"date": "2026-07-07", "date": "2026-09-02",
"commit": "fe1831a", "commit": "8c5855c",
"node": "v22.22.2", "node": "v22.22.2",
"os": "darwin", "os": "darwin",
"cpu": "Apple M4 Max (16 cores)", "cpu": "Apple M4 Max (16 cores)",
@@ -10,8 +10,8 @@
}, },
"config": { "config": {
"conns": 100, "conns": 100,
"duration": 5, "duration": 10,
"runs": 3, "runs": 5,
"warmup": 1, "warmup": 1,
"pipelining": 1 "pipelining": 1
}, },
@@ -23,11 +23,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 115398.4, "median": 119357.1,
"min": 114822.4, "min": 118560,
"max": 115539.2, "max": 120066.91,
"stddev": 310.09010876768724, "stddev": 484.9030139151553,
"cv": 0.0026905088104554075 "cv": 0.0040636145553490976
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -36,24 +36,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86764.8, "median": 89096.73,
"min": 86496, "min": 88864,
"max": 87123.2, "max": 89207.28,
"stddev": 256.9227813090051, "stddev": 111.97759400880093,
"cv": 0.002960121758353106 "cv": 0.001257219726589825
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 24366.4, "median": 24677.1,
"min": 24283.2, "min": 24646.55,
"max": 24417.6, "max": 24768.73,
"stddev": 55.38455460585383, "stddev": 43.02015834466458,
"cv": 0.002273984274990166 "cv": 0.0017417832565876405
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -62,39 +62,39 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 98092.8, "median": 87473.46,
"min": 98054.4, "min": 86903.28,
"max": 98668.8, "max": 87607.28,
"stddev": 281.0175795212842, "stddev": 280.84365746087286,
"cv": 0.002859589501804015 "cv": 0.0032155347907296527
}, },
"p50": 0, "p50": 1,
"p99": 1, "p99": 2,
"p999": 2 "p999": 2
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 21761.6, "median": 21878.55,
"min": 21697.6, "min": 21845.1,
"max": 21896, "max": 21952.73,
"stddev": 82.67870880032535, "stddev": 41.00873789816055,
"cv": 0.0037952010918943873 "cv": 0.0018731606009975037
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 10 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 95033.6, "median": 98039.28,
"min": 94240, "min": 96072.73,
"max": 95264, "max": 99680,
"stddev": 438.6166536839312, "stddev": 1215.4038343760499,
"cv": 0.00462452048886261 "cv": 0.012396669934655963
}, },
"p50": 1, "p50": 0,
"p99": 1, "p99": 1,
"p999": 2 "p999": 2
} }
@@ -107,11 +107,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 116332.8, "median": 120904.73,
"min": 115974.4, "min": 119927.28,
"max": 116409.6, "max": 121713.46,
"stddev": 189.66281191162406, "stddev": 658.0250991747977,
"cv": 0.001631663389130871 "cv": 0.005441723483024015
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -120,24 +120,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 86278.4, "median": 88317.1,
"min": 86137.6, "min": 87997.1,
"max": 86764.8, "max": 88439.28,
"stddev": 268.69839349476365, "stddev": 182.99174422907566,
"cv": 0.003110165492522174 "cv": 0.00207430857941761
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23835.2, "median": 24200,
"min": 23803.2, "min": 24157.82,
"max": 24046.4, "max": 24259.64,
"stddev": 107.89690552662897, "stddev": 39.43298619176589,
"cv": 0.004515472130491916 "cv": 0.0016290899720752198
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -146,11 +146,11 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 93433.6, "median": 86594.91,
"min": 93152, "min": 86368,
"max": 93612.8, "max": 86880,
"stddev": 189.6628119116206, "stddev": 179.11650003279965,
"cv": 0.002030662686635119 "cv": 0.002068552609808656
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -159,27 +159,27 @@
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20955.2, "median": 21181.82,
"min": 20948.8, "min": 21149.82,
"max": 21201.6, "max": 21517.82,
"stddev": 117.69157432317111, "stddev": 139.0670808494951,
"cv": 0.005594982425799189 "cv": 0.006540068168697097
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 11 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 89312, "median": 91848.73,
"min": 89235.2, "min": 91825.46,
"max": 89529.6, "max": 92599.28,
"stddev": 124.68598780759793, "stddev": 296.55679952413783,
"cv": 0.001395338811201841 "cv": 0.00322222064035544
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
} }
] ]
@@ -192,11 +192,11 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 113491.2, "median": 118996.37,
"min": 112531.2, "min": 118583.28,
"max": 114809.6, "max": 119584,
"stddev": 933.9810324031724, "stddev": 341.82644850274596,
"cv": 0.008220892102882115 "cv": 0.002872466494470492
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
@@ -205,24 +205,24 @@
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 85024, "median": 86670.55,
"min": 84512, "min": 86490.19,
"max": 85177.6, "max": 86792.73,
"stddev": 284.55819947576623, "stddev": 97.03476704769095,
"cv": 0.003351507726431956 "cv": 0.0011197471063834074
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 1,
"p999": 2 "p999": 2
}, },
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 23950.4, "median": 24325.1,
"min": 23902.4, "min": 24281.46,
"max": 24011.2, "max": 24406.55,
"stddev": 44.519758410046, "stddev": 50.44878456414985,
"cv": 0.0018585004345727763 "cv": 0.002073096921615235
}, },
"p50": 3, "p50": 3,
"p99": 5, "p99": 5,
@@ -231,11 +231,11 @@
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 84896, "median": 80078.55,
"min": 84243.2, "min": 80026.19,
"max": 85267.2, "max": 80375.28,
"stddev": 423.2825796347192, "stddev": 126.5427427235537,
"cv": 0.004991414284012342 "cv": 0.00157915416330658
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -244,24 +244,24 @@
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 20824, "median": 20872,
"min": 20804.8, "min": 20800.73,
"max": 20878.41, "max": 20940.37,
"stddev": 31.17605954717337, "stddev": 44.78034640330492,
"cv": 0.001496278247605678 "cv": 0.0021458031999967474
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 11 "p999": 9
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 87328, "median": 89527.28,
"min": 86867.2, "min": 87572.37,
"max": 87660.8, "max": 90027.64,
"stddev": 325.38753646827104, "stddev": 867.875358507201,
"cv": 0.0037278603866430907 "cv": 0.009726340137622384
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -276,24 +276,24 @@
{ {
"framework": "raw-http", "framework": "raw-http",
"reqSec": { "reqSec": {
"median": 100140.8, "median": 104288,
"min": 99846.4, "min": 103776,
"max": 100294.4, "max": 104916.37,
"stddev": 185.88177843875883, "stddev": 371.6125197245094,
"cv": 0.0018570746103533369 "cv": 0.0035614220793380035
}, },
"p50": 0, "p50": 0,
"p99": 1, "p99": 1,
"p999": 2 "p999": 1
}, },
{ {
"framework": "fastify", "framework": "fastify",
"reqSec": { "reqSec": {
"median": 63721.6, "median": 65905.46,
"min": 63574.4, "min": 65725.1,
"max": 63760, "max": 66366.55,
"stddev": 79.99288857281053, "stddev": 217.1439762369652,
"cv": 0.0012560645345785087 "cv": 0.0032914527300013986
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
@@ -302,53 +302,53 @@
{ {
"framework": "express", "framework": "express",
"reqSec": { "reqSec": {
"median": 20097.6, "median": 20297.46,
"min": 20056, "min": 20157.82,
"max": 20174.41, "max": 20413.82,
"stddev": 49.04789518646266, "stddev": 99.50819415505447,
"cv": 0.0024390608203285337 "cv": 0.004902635960088364
}, },
"p50": 4, "p50": 4,
"p99": 6, "p99": 6,
"p999": 12 "p999": 10
}, },
{ {
"framework": "green-tea", "framework": "green-tea",
"reqSec": { "reqSec": {
"median": 77177.61, "median": 70298.19,
"min": 77126.4, "min": 68971.64,
"max": 77254.4, "max": 70606.55,
"stddev": 52.602458962379814, "stddev": 704.8749988359651,
"cv": 0.0006815013839797027 "cv": 0.01008804689681251
}, },
"p50": 1, "p50": 1,
"p99": 2, "p99": 2,
"p999": 2 "p999": 3
}, },
{ {
"framework": "nestjs-express", "framework": "nestjs-express",
"reqSec": { "reqSec": {
"median": 18856, "median": 18787.64,
"min": 18852.8, "min": 18684.37,
"max": 19067.2, "max": 18861.82,
"stddev": 100.32338821143516, "stddev": 57.13389375843402,
"cv": 0.005301010367660728 "cv": 0.0030419312672842124
}, },
"p50": 5, "p50": 5,
"p99": 7, "p99": 7,
"p999": 30 "p999": 10
}, },
{ {
"framework": "nestjs-fastify", "framework": "nestjs-fastify",
"reqSec": { "reqSec": {
"median": 59145.6, "median": 63317.82,
"min": 59004.8, "min": 62453.82,
"max": 59376, "max": 63746.91,
"stddev": 153.00625985741647, "stddev": 543.811870536126,
"cv": 0.002585636725423652 "cv": 0.00860786685722159
}, },
"p50": 1, "p50": 1,
"p99": 3, "p99": 2,
"p999": 3 "p999": 3
} }
] ]
@@ -358,27 +358,89 @@
{ {
"path": "/steps/0", "path": "/steps/0",
"steps": 0, "steps": 0,
"reqSec": 92281.6 "reqSec": 88107.64
}, },
{ {
"path": "/steps/3", "path": "/steps/3",
"steps": 3, "steps": 3,
"reqSec": 81529.61 "reqSec": 79950.55
}, },
{ {
"path": "/steps/5", "path": "/steps/5",
"steps": 5, "steps": 5,
"reqSec": 71993.61 "reqSec": 74126.55
} }
], ],
"secureCost": [ "secureCost": [
{ {
"label": "security:false (parity)", "label": "security:false (parity)",
"reqSec": 98092.8 "reqSec": 87473.46
}, },
{ {
"label": "security:true (default)", "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 autocannon from 'autocannon';
import { spawn, execSync } from 'child_process'; import { spawn, execSync } from 'child_process';
import os from 'os'; import os from 'os';
import { writeFileSync } from 'fs'; import { existsSync, readFileSync, writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios'; import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats'; import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render'; 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 SMOKE = process.env.BENCH_SMOKE === '1';
const CONNS = Number(process.env.BENCH_CONNS ?? 100); const CONNS = Number(process.env.BENCH_CONNS ?? 100);
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10); const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5); const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1); 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 { function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`); process.stderr.write(`[bench] ${msg}\n`);
} }
@@ -23,11 +36,25 @@ interface RunResult {
p999: number; 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( async function spawnServer(
name: string, name: string,
extraEnv: Record<string, string> = {}, extraEnv: Record<string, string> = {},
runtime: 'node' | 'deno' | 'bun' = 'node',
): Promise<{ port: number; kill: () => Promise<void> }> { ): 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 }, env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
}); });
let stderr = ''; let stderr = '';
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
})); }));
const stepScaling: RenderData['stepScaling'] = []; const stepScaling: RenderData['stepScaling'] = [];
const secureCost: RenderData['secureCost'] = []; const secureCost: RenderData['secureCost'] = [];
const runtimes: RenderData['runtimes'] = [];
for (const fw of frameworks) { for (const fw of frameworks) {
log(`booting ${fw}`); 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 commit = execSync('git rev-parse --short HEAD').toString().trim();
const data: RenderData = { const data: RenderData = {
env: { env: {
@@ -160,8 +224,15 @@ async function main(): Promise<void> {
scenarios: scenarioBlocks, scenarios: scenarioBlocks,
stepScaling, stepScaling,
secureCost, 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)); writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
log('wrote BENCHMARKS.md + bench/results.json'); 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);
});
+15
View File
@@ -1,4 +1,19 @@
{ {
"name": "@green-tea/core",
"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
// `@green-tea/core/bun` has to work whichever registry the reader installed from.
"exports": {
".": "./src/index.ts",
"./deno": "./src/deno.ts",
"./bun": "./src/bun.ts",
"./edge": "./src/edge.ts"
},
"publish": {
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
},
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
Generated
+2 -1
View File
@@ -55,7 +55,8 @@
"hyperid": { "hyperid": {
"uuid": "11.1.1" "uuid": "11.1.1"
} }
} },
"undici": "7.29.0"
} }
} }
} }
@@ -0,0 +1,166 @@
# Observability — Design
**Issue:** [#10](https://github.com/Expressive-Tea/green-tea/issues/10) · **Status:** reviewed, all decisions settled · **Constraint:** no new runtime dependency
---
## The diagnosis is not the one in the issue
#10 says green-tea "ships no logging, metrics or tracing contract today", and asks for an injectable logger, structured output, tracing hooks and metrics as one design. The framing is right; the starting point is wrong, and it changes what the work is.
**The mechanism already exists.** `Bus` (`src/bus.ts`) is an in-process event emitter with 19 emission points already wired through boot, the pipeline, streams, WebSockets, mesh and plugins. Plugins already receive `bus.on` — and only `on`, so isolation is structural (`src/plugin.ts:27`).
What is actually missing is narrower and more serious than "there is no logger":
| # | Finding | Where |
|---|---|---|
| 1 | **No event carries request identity.** Under any concurrency, interleaved `request:step:enter` events cannot be attributed to a request. | `src/pipeline.ts:53,56` |
| 2 | **`durationMs` is declared and never set by anything.** There is no timing in the system at all. | `src/bus.ts:22`, zero writers |
| 3 | **No request-level events exist.** No `started`/`completed`/`failed`, so there is no span for step events to hang from. | — |
| 4 | **A failing step is reported as `name: 'pipeline'`**, losing which step broke. | `src/pipeline.ts:98` |
| 5 | **8 `console.warn` calls in core**, unredirectable. | `src/app/index.ts` ×6, `src/deno.ts`, `src/bun.ts` |
So the real statement of the problem is:
> The event stream exists but is **not correlatable and not measured**, which makes it unusable for production observability regardless of what consumes it.
That is *why* #10 is one design and not six — a sharper reason than the issue had. A logger, a metrics exporter and an OpenTelemetry bridge are not three features; they are three **consumers of one corrected event stream**. Fix correlation and timing once, and all three become adapters outside core. Ship them separately and each grows its own private notion of "which request was that", which is the three-mechanisms failure #10 warned about.
**Consequence for sequencing:** most of this work is in `src/bus.ts` and `src/pipeline.ts`, not in new files.
---
## Decisions
### D1 — The logger is a distinct registration, not an ordinary provider
`createApp({ logger })`, not `@Provider({ provides: 'logger' })`.
The deciding constraint is ordering. `boot:provider:start`/`fail` fire *while* the graph is booting (`src/app/index.ts:639-647`), and the optional-provider failure warning at `src/app/index.ts` logs during that same phase. A provider cannot log its own boot failure, and a logger that only exists after the graph resolves cannot report the graph failing to resolve. Shutdown has the same shape: `closeApp` warns after the graph is gone.
The logger is therefore framework infrastructure with a lifetime wider than the graph.
It is *additionally* exposed as an injectable key so steps and handlers reach it with `@needs('logger')` like anything else. One object, two access paths, no second implementation.
**Default:** structured JSON. Human-readable when the process is interactive, decided once at boot rather than per call. **Never a dependency** — the default writes to `console` behind the same interface everyone else implements, which is what lets the 8 direct `console.warn` calls become logger calls without core gaining a logging library.
### D2 — One emitter. Extend `Bus`; do not add a parallel hook system
Per-category hooks would be a second mechanism competing with an emitter that already has 19 call sites and a plugin contract built on it. `LifecycleEvent` grows; nothing new is introduced.
This also keeps the existing guarantee intact: `emit` swallows listener failures (`src/bus.ts:41`) precisely so observers can never break the pipeline. Observability must not acquire the power to take down a request.
**This is exactly why shutdown teardown does not belong here** — see Task 2.5 in the trust-release plan. A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
### D3 — A step failure emits both `request:step:error` and `request:failed`
They answer different questions — *which step broke* and *did this request fail* — and a tracing exporter needs both: one marks the span, the other marks the trace. Emitting only the outer event is what produces a trace that says a request failed with no indication where.
`request:step:error` must also carry the real step name. Emitting `name: 'pipeline'` (`src/pipeline.ts:98`) is a bug, not a design choice, and it is fixed as part of this.
### D4 — Streams and WebSockets emit lifecycle events only, never per-message
`stream:open`/`close`/`error` already exist and are the right granularity. A per-message event on a high-rate SSE or WebSocket stream is a firehose that costs more than it reports, and the cost lands on the workload least able to absorb it.
Anyone who needs per-message visibility instruments their own handler, where they know the message semantics. Same reasoning that keeps WebSocket upgrades outside the concurrency gate in #21.
### D5 — Request identity is generated with `crypto.randomUUID()`, and inherited when offered
No new dependency is available, so no UUID library. `globalThis.crypto.randomUUID` is present on Node, Deno and Bun (verified locally) and is Web Crypto on workerd.
**To validate during implementation:** Node 18 is the floor in `package.json` and CI's `build` job pins `node-version: '18'`, so a gap there fails CI rather than reaching a user. `test:edge` covers workerd the same way.
An incoming `x-request-id` is adopted rather than replaced — a green-tea service behind a gateway must not start a second identity for the same request. A `traceparent` header, if present, is carried as `traceId` untouched; core parses nothing and implements no propagation spec. That belongs in the OpenTelemetry adapter, which owns W3C Trace Context.
---
## The contract
### Events
Existing, unchanged in name: `boot:provider:start|ok|fail`, `request:step:enter|leave|error`, `stream:open|close|error`, `mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
Added:
```
request:start request:end request:failed
route:matched route:unmatched
graph:resolved graph:failed
```
`route:unmatched` rather than the report's `route.not_found`: a 405 is also an unmatched route and is not a 404, and naming the event after one outcome would misreport the other.
### Payload
`EventPayload` gains the correlation and measurement fields it lacks. Every field stays optional — mesh and boot events have no request to name, and forcing a shape on them would mean inventing values.
```ts
interface EventPayload {
name: string;
scope?: string;
error?: unknown;
durationMs?: number; // declared today, written by nothing — this design makes it real
requestId?: string; // the correlation fix
traceId?: string; // inherited from traceparent when present; never synthesized
route?: string; // the matched pattern, not the raw URL — bounded cardinality for metrics
method?: string;
transport?: Transport;
status?: number;
runtime?: 'node' | 'deno' | 'bun' | 'edge';
}
```
`route` is the **pattern** (`/users/:id`), never the concrete path. A metrics consumer that labels a counter with the raw URL produces unbounded cardinality and takes down the metrics backend rather than the app — the framework should not hand a user that shape by default.
### Metrics
No metrics registry in core, and no new event type for them. Per-step timings come from `durationMs` on the events already defined; a metrics adapter subscribes and aggregates. The graph already knows every node, which is what makes this close to free — but the timing instrumentation is measured before it is declared free, per Trust Release §6, and stays opt-in if the measurement says otherwise.
---
## Out of scope, deliberately
- **OpenTelemetry itself.** A separate `@green-tea/opentelemetry` package. Core exposes the stream; it never imports an exporter, and never depends on one.
- **Log shipping, sampling, redaction.** Consumer concerns. Core hands over structured records.
- **Trace context propagation.** Carried, not parsed. The adapter owns W3C Trace Context.
- **Shutdown teardown for plugins/providers.** Task 2.5, a different guarantee — see D2.
---
### D6 — A request span ends when the handler returns, and stream events carry its `requestId`
A streaming route returns from `handle()` in milliseconds while the connection lives for minutes or hours. `request:end` fires at the handler's return, so latency histograms measure time-to-first-byte and stay meaningful instead of mixing 2 ms buffered requests with hour-long SSE connections in one distribution. Connection duration is already available from `stream:open`/`stream:close`, which now carry the same `requestId` so a consumer can join the two.
This is the same boundary #21 chose for its concurrency gate — release when `handle()` returns, treat long-lived streams like upgrades. Answering it differently in the two places would mean the framework disagreed with itself about when a request is over.
### D7 — Per-step timing is always on, measured at step boundaries
Measured before deciding, on the box `BENCHMARKS.md` was produced on:
| Approach | Cost per step | Share of one request |
|---|---:|---:|
| `performance.now()` ×2 per step | 45.3 ns | 0.44% |
| **`performance.now()` at step boundaries (N+1 calls for N steps)** | **25.2 ns** | **0.25%** |
| `Date.now()` ×1 | 28.6 ns | — |
Baseline: 98,093 req/s ≈ 10.19 µs per request.
Two things follow. `Date.now()` loses on both axes — slower *and* coarser — so `performance.now()` is unambiguous. And a step's end is the next step's start, so a pipeline of N steps needs N+1 timestamps rather than 2N, halving the cost.
At 0.25% per step the overhead sits **below the 0.3% run-to-run CV of the project's own benchmark**, so it is not measurable in the harness that would have to justify a flag. Making it opt-in would buy two code paths and a configuration surface in exchange for something nobody can observe. Always on.
> **Correction, after implementation.** This decision survived; its reasoning did not. The measured cost is **+7.0% of the framework's own per-request work** (~0.29 µs, ~2% over a real socket), and it is *fixed per request* rather than per step — per-step work is skipped entirely when nothing subscribes. "Always on" is still right, and for a better reason: there is nothing per-step left to make optional.
>
> Three earlier figures for this were published before that one and all three were wrong, each from a comparison with more than one variable moving. See Task 7 in the implementation plan for what went wrong and why interleaving is not optional here.
### D8 — Request logging is a `Bus` subscriber, wrapped so a failing logger cannot go silent
The logger is a callable sink either way — the 8 direct diagnostics (shutdown timeout, degraded provider) are not events and need one regardless. The decision is only about request logging, and it goes through the event stream: one path, and it is composable and removable exactly as #10 asks for ("a composable step, not a global middleware").
The cost this closes: `emit` swallows listener failures by design (`src/bus.ts:41`), so a user-supplied logger that throws would stop writing with nobody informed. The built-in subscriber is therefore wrapped to fall back to `console` on failure. The Bus keeps its guarantee — an observer still cannot break a request — without buying it with silence.
---
## Verification this design must survive
`npm run lint && npm run format:check && npm run typecheck && npm test`, plus `test:deno`, `test:bun` and `test:edge` — all four now gate a merge. Per-request instrumentation is on the hot path, so `npm run bench` before and after, with the numbers in the implementation plan.
+166
View File
@@ -0,0 +1,166 @@
# Observability — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Design:** [2026-08-16-observability-design.md](./2026-08-16-observability-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
**Goal:** Make the existing event stream correlatable and measured, then build the logger on top of it as its first consumer. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
**Architecture:** Most of this lands in `src/bus.ts` and `src/pipeline.ts`. The `Bus` already has 19 emission points; this adds identity, timing and the request-level events those points had nothing to hang from. No new runtime dependency — `reflect-metadata` stays the only one, and the OpenTelemetry bridge lives outside core.
**Tech Stack:** TypeScript, Vitest, Deno/Bun/workerd suites, `performance.now()`, `crypto.randomUUID()`.
---
## Order
Tasks 1–3 are the correction; 4–6 are what consumes it. Do not start 4 before 3 — a logger built on uncorrelated events would need its own notion of request identity, which is the failure the design exists to prevent.
---
### Task 1: Give every request an identity, and carry it
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/http/core.ts` (`NeutralRequest`, `handle`)
- Modify: `src/http/server.ts` (~line 120, the Node call into `handle`)
- Modify: `src/http/web.ts` (~line 178, the Fetch call into `handle`)
- Modify: `src/bus.ts`
- Test: `test/observability.test.ts` (new)
**Step 1:** Extend `EventPayload` with the optional fields from the design: `requestId`, `traceId`, `route`, `method`, `transport`, `status`, `runtime`. All optional — boot and mesh events have no request to name.
**Step 2:** Add `requestId` to `NeutralRequest` (`src/http/core.ts`). Generate it in the **adapters**, not in `handle()`, and here is why that placement matters: both adapters read and size-check the body before they reach `handle()` (`server.ts:107`, `web.ts:143` per the #21 analysis), so a 413 is rejected before `handle()` ever sees the request. Generating inside `handle()` would leave exactly the failures an operator most wants to correlate without an id.
**Step 3:** One shared helper for generation, so the two adapters cannot diverge on the rule: adopt an incoming `x-request-id`, otherwise `crypto.randomUUID()`. Carry `traceparent` through as `traceId` **without parsing it** (D5).
**Step 4:** Write the test that fails first: fire two concurrent requests through `app.fetch`, collect `request:step:enter` from the bus, and assert every event carries a `requestId` and that the two requests' events never share one. This is the defect the whole design exists to fix, so it is the first test.
**Verify:** `crypto.randomUUID` on Node 18 — CI's `build` job pins `node-version: '18'`, and `test:edge` covers workerd. Do not assume; let both run.
### Task 2: Measure steps at their boundaries
**Files:**
- Modify: `src/pipeline.ts` (`runSteps`, ~line 48)
- Test: `test/observability.test.ts`
**Step 1:** Take `performance.now()` once before the loop, then once per iteration — **N+1 timestamps for N steps**, because a step's end is the next step's start. Not two per step. The design measured the difference: 25.2 ns vs 45.3 ns per step (D7).
**Step 2:** Attach `durationMs` to `request:step:leave`. The field has been declared in `EventPayload` since the beginning and written by nothing; this is what makes it real.
**Step 3:** Always on, no flag (D7 — 0.25% of a request, below the benchmark's own 0.3% CV).
**Verify:** a step that sleeps a known interval reports a `durationMs` in that neighbourhood. Assert a range, never an exact value.
### Task 3: Stop losing which step failed
**Files:**
- Modify: `src/pipeline.ts` (`runSteps`, and the catch at ~line 98)
- Test: `test/observability.test.ts`
`request:step:error` currently emits `{ name: 'pipeline' }`, which throws away the one fact it exists to report.
**Step 1:** Wrap each `step.run` inside `runSteps`, emit `request:step:error` with the real step name and `scope`, and rethrow unchanged. Do not swallow.
**Step 2:** `runPipeline`'s existing catch now emits `request:failed` instead of a second `step:error` (D3). Both fire for a failing step, deliberately: one marks the span, the other the trace.
**Verify:** a three-step pipeline whose middle step throws emits `request:step:error` naming *that* step, plus exactly one `request:failed`.
### Task 4: The logger contract
**Files:**
- Create: `src/logger.ts`
- Modify: `src/app/index.ts` (`createApp` options; the 6 `console.warn` calls)
- Modify: `src/deno.ts`, `src/bun.ts` (1 `console.warn` each)
- Modify: `src/index.ts` (export the type)
- Test: `test/logger.test.ts` (new)
**Step 1:** Define the interface. Keep it to the levels core actually uses — resist inventing a hierarchy nobody calls.
**Step 2:** Default implementation: structured JSON, human-readable when the process is interactive, decided **once at boot** rather than per call. It writes through `console`; core gains no logging dependency (D1).
**Step 3:** `createApp({ logger })`. A distinct registration, not a provider — it has to outlive the graph to report the graph failing to boot (D1). Per `AGENTS.md`, a new public option means `src/app/types.ts` too if it appears on `App`.
**Step 4:** Replace all 8 `console.warn` calls. `grep -rn "console\." src/` must return nothing afterwards, which is the check #10 actually asks for.
**Step 5:** Expose the logger under an injectable key so steps and handlers reach it with `@needs('logger')`. One object, two access paths, no second implementation.
### Task 5: Request logging as a subscriber
**Files:**
- Modify: `src/logger.ts`
- Test: `test/logger.test.ts`
**Step 1:** Build request logging as `bus.on(...)` over the corrected stream (D8). Composable and removable, which is what #10 means by "a composable step, not a global middleware".
**Step 2:** Wrap the subscriber so a throwing logger falls back to `console`. `Bus.emit` swallows listener failures by design (`src/bus.ts:41`); without the wrapper a broken user logger stops writing and tells nobody. The Bus keeps its guarantee; it just stops paying for it with silence.
**Verify:** a logger that throws on every call still produces output, and the request still succeeds.
### Task 6: The remaining events
**Files:**
- Modify: `src/bus.ts`, `src/http/core.ts`, `src/app/index.ts`
**Step 1:** Add `request:start|end|failed`, `route:matched|unmatched`, `graph:resolved|failed` to `LifecycleEvent`.
**Step 2:** `request:end` fires **when the handler returns**, not when a stream closes (D6). `stream:open`/`close` carry the same `requestId` so a consumer joins them itself.
**Step 3:** `route:unmatched` covers 404 and 405 both — naming it after one outcome would misreport the other.
**Step 4:** `route` on every payload is the **matched pattern**, never the concrete path. A metrics consumer labelling on raw URLs produces unbounded cardinality and takes down the metrics backend; the framework must not hand anyone that shape by default.
### Task 7: Benchmark, and publish the number — **DONE; D7 was wrong in shape**
**Files:**
- Modify: `BENCHMARKS.md`
D7 predicted ~0.25% **per step**, invisible against the harness's own 0.3% CV.
**Measured: +7.0% of the framework's own per-request work** — 4.074 µs → 4.361 µs, medians of five interleaved rounds, ranges not overlapping. About 0.29 µs, or ~2% of a request over a real socket.
The prediction was wrong in **shape**, not only magnitude. Per-step work is skipped entirely when nothing subscribes (`Bus.hasListeners`), so a deep pipeline pays no more than a shallow one; what remains is a **fixed per-request** cost — generating the request id, reading two headers, and the guard checks. "Always on" survives, for a better reason than it was made with: there is nothing per-step left to make optional.
**Three earlier numbers for this were published and all three were wrong**, which is the more useful lesson: −3.9%, then 0.8%, then −6.8%. Each came from a comparison with more than one variable moving.
- The first two were sequential rather than interleaved. The same code measured at the start and end of one session differed by **12%** as the machine warmed, so run order was indistinguishable from effect — one of them even reported the wrong sign.
- The third compared `7bd11bf` against `HEAD`, which differ by observability **and** three performance fixes pulling the other way. It reported their net as if it were one of them.
The number above compares `7bd11bf` against `523e318`, the last commit before those fixes, alternating round by round.
Two regressions were found and fixed by measuring rather than reasoning, both larger than anything the design anticipated:
- **A second `async` frame in `handle()` cost 0.43 µs/request** — a promise and two microtask ticks, an order of magnitude more than the four `Map` lookups it existed to arrange. `handle()` is no longer `async`.
- **A closure allocated per request inside `correlateRequest`** cost 0.16 µs, 45% of the then-remaining overhead, for a helper capturing nothing.
Recorded here because the lesson generalises: on this path, an extra promise costs more than any amount of bookkeeping, and a hot-path prediction reasoned from primitive costs was off by more than 10×.
### Task 8: Documentation
**Files:**
- Modify: `README.md` (the *Honest scope* paragraph at ~line 246)
- Modify: `website/src/content/docs/` — a new observability guide, plus the `createapp` reference table
`README.md:246` currently opens "**No observability layer, either.**" and links to #10. It is the single most load-bearing sentence in the CTO assessment, and rewriting it is part of this work rather than follow-up. Say what now exists and what still does not — the OpenTelemetry adapter is not in core and should not be implied to be.
Per `AGENTS.md`, new public API needs a note in `README.md`.
> If Phase 4 has already moved the site, the guide lands in the docs repository instead.
---
## Out of scope
`@green-tea/opentelemetry`, log shipping, sampling, redaction, W3C Trace Context parsing, and plugin/provider teardown (Task 2.5 in the trust-release plan — an awaited teardown and a non-blocking observer are opposite guarantees).
---
## Verification
```bash
npm run lint && npm run format:check && npm run complexity:check && npm run typecheck && npm test
npm run test:deno && npm run test:bun && npm run test:edge # all three gate a merge now
npm run bench # hot-path change
grep -rn "console\." src/ # must be empty
```
+350
View File
@@ -0,0 +1,350 @@
# Trust Release Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Close the gaps that four independent evaluations agree on, in the order that makes each one cheap. Prove portability in CI, make derived execution explainable, ship an observability contract, and move the documentation site out of the core repository so it gets its own lifecycle.
**Architecture:** Nothing here adds a runtime dependency. The observability work is a contract plus emission points, with exporters living outside core. The explain work is a resolver over data `explainRoute` already returns. The runtime matrix runs suites that already exist. The docs split moves a directory that is already self-contained.
**Tech Stack:** TypeScript, legacy decorators, Vitest, Deno/Bun/Workers runtimes, JSR, Astro/Starlight, GitHub/Gitea Actions.
---
## Why this order
The four reports in `.specs/reports/` were written independently and converge on one gap. Observability is the only dimension the CTO due diligence marks as risk **Alto** on its own (§5.3, risk register), it is P0 twice in the Trust Release report (§4, §5), and it is a listed con in the lead-dev report (§4). That is GH #10, and it is the largest item here — which is exactly why it is not first. The three phases before it are cheap, unblock evidence, and produce the material that #10's design needs.
Two things the reports demand that had **no issue filed**, both verified against the code rather than taken on the report's word:
- **Runtime matrix in CI.** `package.json:91-93` defines `test:deno`, `test:bun` and `test:edge`. `.github/workflows/ci.yml` runs none of them. `AGENTS.md:23` already warns that `npm test` does not cover the other runtimes — and CI does not close that. The framework's headline claim has no CI evidence. Trust Release §7 (P0), CTO §8.2 and P0-6.
- **`explain()` does not explain causality.** `src/app/introspect.ts:62` returns a flat `chain` with `needs`/`provides` per node, but never the edge from a need to the node that produced it. Trust Release §2 (P0).
One thing that **has** an issue but appears in no report: **#13 circuit breaker**. Neither the CTO report nor the Trust Release report raises it; the nearest item is "rate limiter" under the CTO's security pack (P0-3), which is a different mechanism. The issue itself already says a worked example in the docs might close it outright. It is scheduled last, as documentation.
**API freeze is deliberately not a phase.** `README.md:276` already declares it under `**next**`. It needs the RC boundary, and freezing a public surface before #10 lands would freeze an API that is still missing its observability contract. What this plan adds instead is a stability *contract* — a statement of which areas are volatile today, which promises nothing and commits to no date (Task 6.1).
**Out of scope: #21 and #17.** Both are claimed by `hgshreyas` with the design already settled in the issue threads. Do not touch them.
---
## Phase 0: Unblock releases
### Task 0.1: Scope the audit gate in stage and release
**Files:**
- Modify: `.github/workflows/stage.yml`
- Modify: `.github/workflows/release.yml`
`AGENTS.md:71` states the policy: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. `ci.yml:56-59` implements it. `stage.yml:21` and `release.yml:26` run bare `npm audit`, so a dev-only advisory blocks a publish. This is drift, not a second policy.
That drift is what stopped work twice. The `nanoid` advisory reached the tree through `tsup → postcss → nanoid` — a build-tooling path that ships to nobody.
**Step 1:** In both files, change `npm audit` to `npm audit --omit=dev`, and add a non-blocking full `npm audit` with `continue-on-error: true` after it so the advisory is still visible in the log.
**Step 2:** Carry a comment on the blocking step pointing at the rule, in the voice `ci.yml` already uses — the next person to read it should see a decision, not an omission.
**Verify:** `grep -n "npm audit" .github/workflows/*.yml` — every blocking occurrence carries `--omit=dev`.
---
## Phase 1: Prove portability, and publish to JSR
These are one phase because they are one subject. The type error JSR found is on the `app.fetch` path, which is the path Deno, Bun and edge all use; a runtime matrix would have caught it first. Fixing them together means the matrix has a green baseline to protect.
### Task 1.1: Fix the `BodyInit` hole on the Fetch path
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/http/web.ts`
- Test: `test/` (the Fetch adapter suite)
Gitea #19 reports, from a real `deno publish --dry-run`:
```
TS2345: Argument of type 'string | Buffer<ArrayBufferLike> | null' is not
assignable to parameter of type 'BodyInit | null | undefined'.
--> src/http/web.ts:112:23
```
`Buffer` is not a valid `BodyInit` under Deno's lib. It works at runtime because implementations are forgiving, which is what makes it worth fixing before a user reports it as a bug: it is a genuine typing hole on the runtime-agnostic path, not a JSR formality.
**Step 1:** Write a failing test that drives a `Buffer` body through the Fetch adapter and asserts the response body round-trips byte-for-byte.
**Step 2:** Narrow the body to a real `BodyInit` at the boundary — convert the `Buffer` to a view its type declares, rather than casting the error away. A cast would keep the hole and hide it.
**Step 3:** Confirm the test passes and `npm run typecheck` is clean.
### Task 1.2: Give the slow-type sites explicit return types
**Files:**
- Modify: `src/metadata.ts` (11 sites)
- Modify: `src/params.ts` (6 sites)
Two shapes, both mechanical: `missing-explicit-return-type` on factory functions (`routeDecorator` at `src/metadata.ts:103`, `envelope` at `src/params.ts:35`) and `missing-explicit-type` on the exported constants built from them (`export const Get = routeDecorator('GET', 'buffer')` at `src/metadata.ts:126`).
**Do not pass `--allow-slow-types`.** That flag degrades generated declarations and makes type checking 1.5–2× slower for consumers, in the framework whose central claim is type safety. Shipping it would contradict the pitch on its own install page.
**Step 1:** Annotate the factories first — several of the constant errors resolve on their own once the factory's return type is written down.
**Step 2:** Annotate whatever constants remain.
**Step 3:** `deno publish --dry-run` reports zero slow types, with no flags.
**Verify:** `npm run typecheck` and `npm test` still clean; the public types in `dist/` are unchanged or strictly more precise.
### Task 1.3: Runtime matrix in CI
**Files:**
- Modify: `.github/workflows/ci.yml`
The suites exist and CI ignores them. Add a matrix job that runs `test:deno`, `test:bun` and `test:edge` alongside the Node build.
**Step 1:** Add a job with the three runtimes, each installing its own toolchain. Keep it a separate job from `build` so a Bun failure reports as a Bun failure and does not bury the Node lint output — the same reasoning `ci.yml:53` already applies to the audit step.
**Step 2:** Confirm the forge difference documented at `AGENTS.md:73` does not bite: GitHub reads `pull_request` workflows from the base branch, so this workflow change cannot validate itself and must reach the base before it gates anything.
**Step 3:** Publish the resulting capability matrix. `README.md:273` already claims all four runtimes; the matrix is what turns that claim into evidence.
**Verify:** A deliberate break in shared code fails the Deno job and not only the Node one.
### Task 1.4: Claim the JSR scope and publish
**Files:**
- Modify: `deno.json`
- Modify: `.github/workflows/release.yml`
**Blocked on Diego and not delegable:** `@green-tea` on jsr.io must be claimed with a GitHub account.
**Step 1:** Add `name`, `version` and `exports` to `deno.json`. Decide whether all four entry points (`.`, `./deno`, `./bun`, `./edge`) are exported or only the Deno one.
**Step 2:** Publish from the same `v*` tag that publishes to npm, using GitHub Actions OIDC. `release.yml` already holds `id-token: write` for npm Trusted Publishing, so JSR needs no new secret.
**Step 3:** Nothing here justifies cutting a release on its own — it rides along with the next version cut that has a reason.
---
## Phase 2: The shutdown cluster
Four open issues, all consequences of the `close({ timeoutMs })` contribution that just merged (`3dcf784`). Treated as one deliverable because they are one subject: Trust Release §14 (P1, lifecycle guarantees) and CTO P0-4 (production checklist, shutdown).
Order matters — the bug first, then the API, then the docs that describe the finished API.
### Task 2.1: #20 — `finish()` reads its timer before declaration
A use-before-declare bug. Smallest item in this plan and it is already shipped. Fix it, and leave a test that fails if the ordering regresses.
### Task 2.2: #19 — shutdown deadline settable at `createApp` level
The 10s deadline is hardcoded. Make it configurable at app level, with `close({ timeoutMs })` still overriding per call.
Per `AGENTS.md:81`, a new option on a public interface **must** also change `src/app/types.ts`. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
### Task 2.3: #15 — graceful shutdown is Node-only — **DECIDED, DONE**
**Decision: `app.close()` stays Node-only; each adapter that owns a server offers the same `close({ timeoutMs })`.** The framework's line is *it handles architecture, you handle business*, and draining is owned by whoever holds the handle.
What the runtimes turned out to allow, measured rather than assumed:
| Runtime | Drain | After the deadline |
|---|---|---|
| Node | `server.close()` | `closeAllConnections()` — remainder cut |
| Bun | `stop(false)` | `stop(true)` — remainder cut |
| Deno | `shutdown()` | **returns anyway** — remainder ends with the process |
Deno cannot escalate. Aborting the serve signal while `shutdown()` is pending throws `BadResource: Bad resource ID` from Deno's own listener — uncaught, and fatal under `deno test`. Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long `close()` waits, not when connections die, and `runtimes.md` says so in a table rather than averaging the three.
`closeWithDeadline` (`src/http/shutdown.ts`) is shared so the two adapters cannot drift into different meanings of the same `timeoutMs`, and it resolves on its own timer rather than awaiting the force call — Bun's `stop(true)` was measured waiting out a handler with a pending timer, which is the unbounded wait the deadline exists to prevent.
### Task 2.5: Shutdown as an extension point — **OPEN, needs its own design**
Raised while deciding #15: shutdown should emit signals so plugins and providers register their own teardown, instead of every consumer writing `process.on('SIGTERM', …)` by hand. Same principle as the decision above — the framework owns the plumbing.
It does **not** fit the existing `Bus`, and that is the finding worth carrying forward. `Bus.on` takes a synchronous listener (`src/bus.ts:29`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:38`, `catch {}`). That is deliberate — observers must never break the pipeline — but a plugin closing a database connection needs shutdown to *wait for it*. Registering a teardown is not observing an event, and bending `Bus` to do both would cost the guarantee that makes it safe.
So it needs: an await-aware teardown registry, a new surface on `PluginApi` (public API — `src/plugin.ts:19`), and a decision about provider cleanup. That is Trust Release §14 "Graceful lifecycle guarantees" and CTO P0-4, and it belongs in a design document rather than inside a bug-fix cluster. Sequence it with Phase 3, whose observability contract shares the same lifecycle vocabulary.
### Task 2.4: #18 — docs still describe `close()` without the timeout
Last, so it documents the finished API rather than being rewritten twice. If Phase 4 has already run, this lands in the docs repository instead.
---
## Phase 3: Observability (#10)
The one every report puts first, and the only one that needs a design document before code.
### Task 3.1: Design document
**Files:**
- Create: `.specs/2026-XX-XX-green-tea-observability-design.md`
Write the design before any implementation, following the design/plan pairing already in `.specs/`.
The issue is explicit that this is **one design, not six**: an injectable logger, structured output and tracing hooks are the same API decision, and solving them separately leaves three mechanisms that do not fit together.
Inputs to reconcile:
- The scope in GH #10 — injectable logger contract, JSON default with human-readable dev output, request/response logging as a composable step rather than global middleware, hooks an exporter can attach to, metrics export.
- The Trust Release event vocabulary (§4) — `request.*`, `route.*`, `step.*`, `provider.*`, `graph.*`, `websocket.*`, `stream.*` — and its context fields (`requestId`, `traceId`, `route`, `transport`, `step`, `duration`, `status`, `scope`, `runtime`).
- Trust Release §6, graph timing. Per-step timings are close to free because the graph already knows every node, but the instrumentation stays opt-in if overhead is measurable. Measure before deciding.
Hard constraint, restated from `AGENTS.md:11`: **no new runtime dependency.** Core stays on `reflect-metadata` alone. An OpenTelemetry exporter is a separate package (`@green-tea/opentelemetry`), never a core dependency.
Decisions the design must settle rather than leave open:
1. Is the logger a provider like any other, or a distinct registration?
2. Do events go through one emitter or through per-category hooks?
3. Does a step failure emit `step.failed` and `request.failed`, or only the outer one?
4. Do long-lived streams and WebSockets emit per-message events, or only lifecycle ones? (The same reasoning that keeps upgrades out of the #21 gate applies.)
### Task 3.2: Implement to the approved design
Do not start before the design is reviewed. Write the implementation plan from the approved design, as `.specs/` already does for every other subsystem.
### Task 3.3: Rewrite the observability paragraph in `README.md`
`README.md:246` currently reads "**No observability layer, either.**" and points at issue #10. When #10 lands, that paragraph is wrong and it is the single most load-bearing sentence in the CTO's assessment. Rewriting it is part of the work, not follow-up.
`AGENTS.md:83`: new public API needs a note in `README.md`.
---
## Phase 4: Split the documentation site
Verified before scheduling: `website/` is self-contained. 26 source files, no path escaping the directory, and the `@green-tea/core` mentions inside the `.md` files are example code, not build-time imports.
The coupling to core is five lines:
| Location | What |
|---|---|
| `.github/workflows/ci.yml:62-65` | `npm ci --prefix website`, `npm audit --prefix website`, `npm run docs:build` |
| `package.json:100-101` | `docs:dev`, `docs:build` |
Plus two README references to update: `README.md:254` (the docs link) and `README.md:263` (`npm run docs:dev`).
**The real work is not the move.** No workflow anywhere in `.github/workflows/` deploys the site. `website/astro.config.mjs:6` points at `green-tea.expressive-tea.io` and the deploy happens by hand today. The new repository is where that pipeline gets built for the first time.
### Task 4.1: Create the repository and move `website/` with its history
Preserve commit history for the moved directory rather than landing it as one squashed import.
### Task 4.2: Build the deploy pipeline
The thing the docs never had. Build on push to the default branch, deploy to `green-tea.expressive-tea.io`.
### Task 4.3: Remove the website from core
Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`. Update `README.md:254` and `README.md:263`.
### Task 4.4: Guard the seam the split opens
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**
Numbered as an insertion because that is what it is, the same way Task 2.5 was. It is small, and its position is the whole point: **Task 2.5 adds public API** — `Hooks`, `TeardownFn`, `PluginApi.onShutdown` — and exported types are exactly what JSR's slow-types check polices. Writing that surface with no JSR gate on pull requests means learning at release time whether the shape is publishable.
Verified before writing this, because the first reading was wrong: `release.yml:42` **already** runs `deno publish --dry-run`, before publishing to either registry, and its comment already makes the argument — *"JSR checks things npm never looks at — slow types, module analysis — and learning about them after npm has published leaves the tag half-shipped."* Phase 1 already published to JSR, and a dry run passes today, slow-types check included.
The gap is not that the gate is missing. It is **when it runs**: only on a version tag. A change that breaks Deno's type-checker or introduces a slow type lands on `main` in silence and surfaces while cutting a release — the moment `release.yml`'s own npm-audit comment identifies as having the least time to judge a fix. The workflow makes that argument for advisories and not for JSR.
Worth stating plainly: `deno publish --dry-run` type-checks the four entry points with **Deno's** checker and lib, which is not the same pass as `tsc --noEmit -p tsconfig.json`. A second compiler over the same source is a real gate, not a formality — Task 1.1 exists because that second compiler found a hole the first one did not. And JSR serves `src/` directly, so anything it would reject is something a JSR user gets.
### Task 4.5.1: Run the JSR gate on every push and pull request
**Files:**
- Modify: `.github/workflows/ci.yml`
Add `deno publish --dry-run` to the `runtimes` job's Deno leg, which already installs Deno. Measured at **0.68s** against 2.0s for the whole vitest suite — cheap enough that placing it anywhere else is over-thinking.
Leave `release.yml` alone. The tag-time gate stays: it is the one that protects an immutable JSR version, and a gate that runs twice is not a duplication worth removing.
### Task 4.5.2: One command for the whole matrix
**Files:**
- Modify: `package.json`
- Modify: `README.md`
`npm test` is Node-only, deliberately — it is the fast local loop, 2s, and booting Deno, Bun and workerd into it would tax every run to catch what CI already catches on every push. The `runtimes` job means these suites are not unguarded; what is missing is a way for a contributor to run everything with one command before pushing.
Add `test:all` — `npm test` plus `test:deno`, `test:bun`, `test:edge`, and the JSR dry run. Say in `README.md` which one is the fast loop and which one is the pre-push check, so the split reads as a decision rather than an oversight.
### The decorator warning is expected — no task, and no new documentation
Every `deno publish --dry-run` prints:
```
Warning experimentalDecorators compiler option is deprecated and may be removed at any time
```
Whoever adds this gate to CI will see that warning arrive with it and should not treat it as something the gate found. It is **already documented, and better than a new note would manage**: `README.md:233` (*Why legacy decorators*) and `concepts/the-graph.md:43` in the docs repository both carry the reasoning — parameter decorators are deliberately absent from the TC39 Stage 3 proposal, so `handler(@param('id') id: string)` is only expressible with legacy decorators, and Stage 3 means the replacement is not finalized either.
An earlier draft of this phase claimed the framework "depends on `emitDecoratorMetadata`". That is **wrong**, and both documents already say so: argument positions are recorded explicitly, and `grep -rn 'design:type\|design:paramtypes' src/` returns nothing — the flag is set in `tsconfig.json` and `deno.json`, but no `design:*` reflection is read anywhere. Legacy parameter decorators are the only legacy surface this project actually depends on.
Do not turn the warning into an error to force the issue: that breaks releases on someone else's schedule.
---
## Phase 5: Close #13 as documentation
### Task 5.1: Write the circuit-breaker recipe
**Files:**
- Create: a guide page in the docs repository
The issue was opened to decide placement, not to commit to a core implementation, and it answers itself: core adding resilience policy would contradict the one-runtime-dependency rule. A circuit breaker fits a step — it needs whatever provides the client, it produces a guarded caller, and the graph already sequences it correctly.
Write it as a worked example, then close #13 pointing at the page. First real content in the new repository, which is also a live test of the deploy pipeline from Task 4.2.
---
## Phase 6: The stability contract
### Task 6.1: A stability paragraph in `Honest scope`
**Files:**
- Modify: `README.md`
Not a roadmap, and not the API freeze. A statement of which areas are volatile *today* — present state, no dates, no delivery commitment. This is spare-time work by one person and a roadmap it cannot keep would cost more trust than it earns.
`## Honest scope` (`README.md:240`) already carries exactly this voice: mesh is alpha, there is no observability layer, runtimes differ in what they can offer. The stability tiers belong in that section, in that register, as one paragraph.
Roughly the split the Trust Release report proposes in §8 — graph semantics, providers, steps and controllers as the stable candidates; decorator syntax, CLI and plugin APIs as beta; mesh and distributed capabilities as experimental. Verify each claim against the code before writing it down; a stability tier asserted and then broken is worse than none.
`README.md:266-276` keeps its `**next**` line unchanged. API freeze stays declared there and gets planned separately, near the RC.
---
## Verification
Per `AGENTS.md:28`, run before proposing any task as finished:
```bash
npm run lint && npm run format:check && npm run typecheck && npm test
```
And from Phase 1 onward the runtime suites are no longer optional, because CI runs them:
```bash
npm run test:deno && npm run test:bun && npm run test:edge
```
Conventional Commits focused on the *why*, every commit signed off (`git commit -s`), no AI co-authoring attribution.
@@ -0,0 +1,211 @@
# Shutdown teardown — Design
**Task:** 2.5 in the [trust-release plan](./2026-08-16-trust-release-plan.md) · Trust Release §14, CTO P0-4 · **Status:** reviewed, D1–D8 settled · **Constraint:** no new runtime dependency
---
## The diagnosis
An application closing a database connection today writes `process.on('SIGTERM', …)` by hand, because the framework offers nowhere to put that. `closeApp` (`src/app/index.ts:1009`) closes mesh links, streams and the HTTP server, and knows nothing about plugins or providers. `LifecycleEvent` (`src/bus.ts:2`) has no shutdown event at all — a plugin cannot even *observe* that the app is closing, let alone act on it.
The framework owns the plumbing everywhere else. This is the hole.
### Why the existing `Bus` cannot carry it
`Bus.on` takes a synchronous listener (`src/bus.ts:62`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:85`). Both are deliberate: observers must never break the pipeline. A plugin closing a database connection needs shutdown to *wait for it*, and needs its failure to be visible.
The observability design already settled this rather than leaving it open — `D2` of [2026-08-16-observability-design.md](./2026-08-16-observability-design.md):
> **This is exactly why shutdown teardown does not belong here.** A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
Conceptually this is still an event — *"the app is closing, do you have anything to do first?"* — and callers may reasonably think of registering as subscribing. Mechanically it is a separate await-aware registry, because bending `Bus` to do both would cost the guarantee that makes `Bus` safe.
### What "isolation is structural" actually protects
`src/plugin.ts:26` reads *"Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural."* That sentence is load-bearing and it is easy to over-read, so this design states what it does and does not cover — verified against the code, because the answer surprised both people in the conversation that produced this document.
**Enforced today:**
- A plugin receives only `bus.on` and `scope.add` — no `emit`, so it cannot fabricate lifecycle events, and no reach into the registry.
- `setRunner` (`src/app/index.ts:320`) throws on duplicate names, so a plugin cannot silently replace an existing provider or step.
- Plugin nodes carry `origin: 'plugin'` and stay attributable in the graph.
**Not enforced today:**
- `runSteps` passes the live context object to every step and merges its output with `Object.assign(context, output)` (`src/pipeline.ts:73-74`). No collision check. A plugin's step can mutate the context directly and can overwrite any key another step provided.
- `mountPlugins` (`src/app/index.ts:161`) runs *before* `provideBuiltins` (`:162`), and `provideBuiltins` skips anything already registered — so a plugin registering a node named `logger` or `rooms` replaces the builtin.
So the guarantee is about the **registration surface**, not about the **runtime context**. Teardown touches neither: it adds a third thing a plugin may register, and never sees a request context. The context-integrity question is real but pre-existing and out of scope here — it is recorded at the end so it is not lost.
---
## Decisions
### D1 — A teardown registry, not a `Bus` event
One list of callbacks, owned by the app, awaited on close. Not a `LifecycleEvent`, for the reason `D2` of the observability design already gives.
The registry is the entire mechanism. Everything below is a door into it.
### D2 — Three doors, one registry: one order, one failure policy
| Door | Who uses it | Shape |
|---|---|---|
| `hooks: [...]` in `createApp` | an application that wants lifecycle participation and nothing else | `onShutdown()` |
| `PluginApi.onShutdown` | a plugin that also extends the graph | `onShutdown()` |
| `dispose()` on a `@Provider` class | the provider that opened the resource | optional method |
Three entry points, **one** registry, **one** order, **one** failure policy. If they ever acquire separate ordering relative to each other, this design has failed and two mechanisms exist again.
The doors differ by intent, not by semantics. Today the only way into the lifecycle is to write a plugin, and a plugin means *"I want to extend the graph"* — someone who only wants to close a connection is forced to declare an extension they do not want.
### D3 — `PluginApi` gains a property; the `Plugin` signature does not change
`Plugin = (api: PluginApi) => void` is untouched. `onShutdown` joins `bus` and `scope` on the object a plugin already receives. Every existing plugin ignores it and behaves identically.
This is why the hooks framing is better than widening the plugin contract directly: it removes the only break the earlier sketch had. See "What breaks" below — the answer is now *nothing at runtime*.
### D4 — Teardown callbacks receive no arguments
```ts
type TeardownFn = () => void | Promise<void>;
```
State lives where the resource was created, and the closure already holds it:
```ts
class MyPlugin {
#db = new Pool();
mount(api: PluginApi) {
api.onShutdown(() => this.#db.end()); // the closure already has it
}
}
```
A provider's `dispose()` is the same picture — the instance holds its own connection.
**Nothing needs to cross scopes**, which is what makes a container reference, an app reference, or any transport mechanism unnecessary here. A bus solves *"tell someone I do not know"*. Teardown is *"run this thing I registered"*. Handing a hook a resolver would make the container reachable from a hook and would be a genuine widening — declined.
If an argument is ever needed, adding one to a callback that receives none is additive. The reverse is not.
### D5 — Order is the reverse of boot
Providers boot in topological order (`bootProviders`, `src/app/index.ts:664`), so they tear down in reverse: if `cache` needs `db`, `cache` closes first. Registration order within the same tier is preserved.
Sequential, not parallel. Reverse-topological order only means something if it is respected, and parallel teardown discards it.
### D6 — A failing teardown is logged and shutdown continues
The failure goes to the injectable `Logger` and `close()` still resolves. One plugin's broken teardown must not strand the remaining ones or hang the process.
This mirrors `Bus`'s philosophy — a subscriber cannot break the system — but with the visibility `Bus` lacks. `Bus` swallows silently because no logger existed when it was written; one exists now.
The counter-argument was weighed and rejected: a `close()` that reports success after losing data is arguably worse than one that fails loudly. It loses because the alternative is worse in the common case — a process that will not exit is a worse operational failure than one that exited with a warning in the log, and the warning is not silent.
### D7 — Triggered from each runtime's real close
`app.close()` returns at its `if (!server)` guard on Deno, Bun and the edge (`src/app/index.ts:1026`). Hanging teardown off `app.close()` would make behaviour differ per runtime, which the multi-runtime constraint forbids.
| Runtime | Entry point |
|---|---|
| Node | `app.close()` → `closeApp` |
| Deno | `serveDeno(app).close()` → `closeWithDeadline` |
| Bun | `serveBun(app).close()` → `closeWithDeadline` |
| edge (workerd) | **none — no shutdown exists** |
`serveDeno` and `serveBun` already receive the app, so their `close()` can run its teardown without the user calling two things. `closeWithDeadline` (`src/http/shutdown.ts`) is already shared by both *"so the two adapters cannot drift into different meanings of the same `timeoutMs`"* — the same argument applies here, and it is why teardown belongs in that shared function rather than in each adapter.
Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**: workerd never closes, so there is nothing to intercept. A plugin that depends on teardown for correctness is broken there. This is a runtime capability difference and belongs in the `runtimes.md` table beside `@Html` file mode and mesh, not in a footnote.
### D8 — Teardown shares the close budget, and `close()` never exceeds `timeoutMs`
`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.
- **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.
---
## The contract
```ts
/** A teardown callback. Receives nothing: state lives in the closure that registered it. */
export type TeardownFn = () => void | Promise<void>;
/** Lifecycle participation without extending the graph. Methods are optional so later
* stages (onBoot, onReady) can join without a breaking change. */
export interface Hooks {
onShutdown?: TeardownFn;
}
/** Unchanged except for the third capability. `Plugin` keeps its signature. */
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
onShutdown(fn: TeardownFn): void;
}
createApp({
modules: [...],
plugins: [...],
hooks: [...], // new
shutdownTimeoutMs: 10_000, // existing
teardownTimeoutMs: 2_000, // new, optional; <= shutdownTimeoutMs
});
@Provider({ provides: 'db' })
class Db {
provide() { /* ... */ }
async dispose() { /* optional; called if present */ }
}
```
### What this costs internally
`collectProviders` (`src/app/index.ts:345`) constructs each provider with `new ProviderClass()` and captures the instance in a closure. **The instance is never stored anywhere reachable**, and `Container.bindings` is private with no iteration, so there is no handle to call `dispose()` on today.
Keeping provider instances requires a new field on `Registry`. That is internal, not public API, and it is the part nobody sees coming from reading "add `onShutdown` to `PluginApi`".
### What breaks
**At runtime: nothing.** `Plugin`'s signature is unchanged, `Hooks` methods are optional, and `dispose()` is called only if present.
**At compile time: nothing either**, given D3. Widening `PluginApi` would have broken anyone constructing one as a literal — typically a test mock — but `onShutdown` is a required property on an object the framework builds and hands out, never one a user implements. Should that turn out to be wrong for some consumer, it goes in the CHANGELOG with the reason: making it optional would force every plugin to check for it and would turn a capability into a conditional forever.
---
## Out of scope, deliberately
- **`onBoot` / `onReady`.** `Hooks` is shaped as an object of optional methods so they can be added without a breaking change, but only `onShutdown` ships. The shape accommodates them; this design does not build them.
- **Request-scope cleanup.** Request values are recomputed per resolve (`src/container.ts`) and are garbage, not resources. Only app-scope teardown is in scope.
- **Edge teardown.** Not possible. Documented, not worked around.
- **A context argument for teardown callbacks.** D4. Additive later if a real case appears.
- **Context integrity.** A plugin's step can overwrite context keys and can replace the `logger` and `rooms` builtins. Real, pre-existing, unrelated to teardown, and recorded here only so the finding is not lost with this conversation.
---
## Verification this design must survive
1. A plugin registering `onShutdown` has it awaited before `close()` resolves — on Node, Deno and Bun, asserted per runtime rather than once.
2. A provider with `dispose()` has it called; one without is skipped.
3. Reverse-topological order: `cache` needing `db` tears down first.
4. A throwing teardown is logged and the remaining ones still run; `close()` resolves.
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
8. `close()` on an app with no teardown registered costs nothing measurable — this is not a request path, but it is still on the shutdown path of every app that uses none of it.
## Documentation this design changes
All of these now live in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs):
- `guides/plugins.md:7` — states plugins have exactly two capabilities. Becomes three, and the isolation wording needs the precision from the diagnosis above rather than a restatement.
- `guides/runtimes.md:44` — the shutdown table gains teardown, and edge gains its exception.
- `guides/dependency-injection.md:56` — describes what `close()` does; it now does one more thing.
- `README.md` — new public API, per `AGENTS.md:83`.
@@ -0,0 +1,141 @@
# Shutdown teardown — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Design:** [2026-08-17-shutdown-teardown-design.md](./2026-08-17-shutdown-teardown-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
**Goal:** Give plugins, providers and applications somewhere to put teardown, so closing a database connection stops meaning `process.on('SIGTERM', …)` by hand. Closes Task 2.5 of the [trust-release plan](./2026-08-16-trust-release-plan.md); Trust Release §14, CTO P0-4.
**Architecture:** A new `src/lifecycle.ts` holds the registry and nothing else. `src/plugin.ts` and `src/app/index.ts` gain doors into it; `src/app/index.ts` (`closeApp`) and `src/http/shutdown.ts` (`closeWithDeadline`) gain the call that drains it. No new runtime dependency — `reflect-metadata` stays the only one.
**The thing to keep hold of:** three doors, one registry, one order, one failure policy. Any task that gives a door its own ordering or its own error handling has broken D2, whatever the tests say.
---
## Order
Tasks 1–3 build the mechanism and the doors; nothing observable changes until Task 4 wires it into `close()`. Task 5 is the runtime parity that D7 demands and is the one most likely to surface a surprise, so it does not go last. Documentation is Task 7 because it should describe the finished API rather than be rewritten twice.
---
### Task 1: The registry
**Files:**
- Create: `src/lifecycle.ts`
- Create: `test/lifecycle.test.ts`
The whole mechanism, with no knowledge of plugins, providers, apps or HTTP.
```ts
export type TeardownFn = () => void | Promise<void>;
```
It needs: register a callback, and run everything registered — sequentially, in reverse registration order (D5), awaiting each, catching each (D6), never throwing. A failing callback is reported through the injectable `Logger` and the next one still runs.
Keep the timeout **out** of here. Bounding is the caller's job, and it is already solved twice over by `closeApp` and `closeWithDeadline`; a third implementation is how the three drift into different meanings of the same number.
Tests: order is reverse of registration; a throwing callback is logged and does not stop the rest; a rejecting async callback is treated the same; an empty registry resolves; running twice does not re-run callbacks (`close()` is called twice by more real applications than anyone expects).
### Task 2: The plugin and hook doors
**Files:**
- Modify: `src/plugin.ts`
- Modify: `src/app/index.ts` — `mountPlugins`, `createApp` options
- Modify: `src/app/types.ts` — `Hooks` on the public options
- Modify: `test/plugin.test.ts`
`PluginApi` gains `onShutdown(fn: TeardownFn): void`, bound to the app's registry. `mountPlugin`'s comment at `src/plugin.ts:26` currently says a plugin gets `on()` and `add()` and nothing else; it now gets three things, and the comment says which and why — the isolation wording in the design's diagnosis is the precise version, not "isolation is gone".
`createApp({ hooks })` takes `Hooks[]`, an object of optional methods so `onBoot`/`onReady` can join later without a breaking change. Only `onShutdown` exists now.
Tests: a plugin registering `onShutdown` lands in the registry; a plugin that never calls it behaves exactly as before (D3 — this is the no-break guarantee, so it gets an explicit test rather than an assumption); hooks and plugins interleave in one order rather than running as two groups.
### Task 3: Provider `dispose()`
**Files:**
- Modify: `src/app/index.ts` — `collectProviders`, `Registry`
- Modify: `test/app.test.ts`
`collectProviders` (`src/app/index.ts:345`) builds each provider with `new ProviderClass()` and captures the instance in a closure where nothing can reach it. Keep the instances on `Registry` so a `dispose()` can be called.
Registration order must follow boot order, not declaration order, so that D5's reverse-topological teardown falls out of the registry's reverse-registration rule rather than needing a second sort. That means registering a provider's `dispose()` as it boots in `bootProviders` (`:664`), not when it is collected.
A provider that failed to boot must not have `dispose()` called — it never provided anything. Optional providers that degraded (`degradedProviders`) are exactly this case and already tracked.
Tests: `dispose()` is called; a provider without one is skipped; `cache` needing `db` tears down first; a provider that failed to boot is not disposed.
### Task 4: Drain the registry on close — Node
**Files:**
- Modify: `src/app/index.ts` — `closeApp`
- Modify: `test/app.test.ts`
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` **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.
Tests: a registered teardown is awaited before `close()` resolves; a hanging teardown does not let `close()` exceed `timeoutMs`; a slow drain plus a set `teardownTimeoutMs` still leaves teardown its reserved slice; `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
### Task 5: Runtime parity — Deno and Bun
**Files:**
- Modify: `src/http/shutdown.ts` — `closeWithDeadline`
- Modify: `src/deno.ts`, `src/bun.ts`
- Modify: `test/deno/*`, `test/bun/*`
`app.close()` returns at its `if (!server)` guard on Deno and Bun (`src/app/index.ts:1026`), so teardown cannot hang off it without behaviour differing per runtime — which the multi-runtime constraint forbids (D7).
`serveDeno(app)` and `serveBun(app)` already hold the app, so their `close()` runs the teardown and the user calls one thing, not two. It goes in `closeWithDeadline` rather than in each adapter, for the reason that function already exists: so the two cannot drift into different meanings of the same `timeoutMs`.
Deno cannot escalate from graceful to forced — its deadline bounds how long `close()` waits, not when connections die. That asymmetry already exists and this must not make it worse.
These suites are **not** in `npm test`. Run `npm run test:deno` and `npm run test:bun` explicitly, and do not report this task done on the strength of vitest passing.
Tests, per runtime rather than once: a teardown registered on a Deno/Bun app is awaited by that server's `close()`.
### Task 6: Edge — document the hole, do not paper over it
**Files:**
- Modify: `src/edge.ts` — doc comment only
workerd never closes, so there is nothing to intercept and no design fixes it. A plugin depending on teardown for correctness is broken there.
No shim, no fake `close()`, no best-effort call on an unload event that does not exist. The only change is a doc comment stating it, so someone reading `edgeHandler` learns it there rather than in production. The user-facing half is Task 7.
### Task 7: Documentation
**Files:** all in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)
- Modify: `src/content/docs/guides/plugins.md` — line 7 says plugins have exactly two capabilities; it is three now, and the isolation sentence needs the design's precision rather than a restatement
- Modify: `src/content/docs/guides/runtimes.md` — the shutdown table gains teardown, and edge gains its row
- Modify: `src/content/docs/guides/dependency-injection.md` — line 56 describes what `close()` does
- Modify: `README.md` in core — new public API, per `AGENTS.md:83`
- Modify: `CHANGELOG.md` in core
Two repositories, one change. This is the first real test of the seam Phase 4 opened, and nothing fails if it is skipped — which is the point of doing it in the same session rather than leaving it to a follow-up.
---
## Out of scope
- `onBoot` / `onReady`. `Hooks` is shaped to accommodate them; this plan does not build them.
- Request-scope cleanup. Request values are recomputed per resolve and are garbage, not resources.
- Edge teardown. Not possible.
- A context argument for teardown callbacks (D4). Additive later if a real case appears.
- Context integrity — a plugin's step can overwrite context keys and replace the `logger` and `rooms` builtins. Real, pre-existing, and recorded in the design's out-of-scope section so it is not lost.
## Verification
The design's list, restated as the gate for calling this done:
1. A plugin's `onShutdown` is awaited before `close()` resolves — asserted on Node, Deno and Bun separately.
2. A provider with `dispose()` has it called; one without is skipped; one that failed to boot is not disposed.
3. Reverse-topological order: `cache` needing `db` tears down first.
4. A throwing teardown is logged, the rest still run, `close()` resolves.
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
8. `close()` on an app with no teardown registered costs nothing measurable.
Plus the gates every change here passes: `npm run lint`, `npm run complexity:check`, `npm run typecheck`, `npm test`, and — because Task 5 exists — `npm run test:deno`, `npm run test:bun`, `npm run test:edge`.
@@ -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.
+8
View File
@@ -23,4 +23,12 @@ export default tseslint.config(
], ],
}, },
}, },
{
// Nothing in core writes to console directly — every diagnostic goes through the injectable
// `Logger`, or an application cannot redirect it. This is the rule form of a check that was
// otherwise a `grep` somebody has to remember to run.
files: ['src/**/*.ts'],
ignores: ['src/logger.ts'], // the default logger *is* the console sink; that is its whole job
rules: { 'no-console': 'error' },
},
); );
+3 -3
View File
@@ -5670,9 +5670,9 @@
} }
}, },
"node_modules/nanoid": { "node_modules/nanoid": {
"version": "3.3.16", "version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
+7 -6
View File
@@ -1,15 +1,16 @@
{ {
"name": "@green-tea/core", "name": "@green-tea/core",
"version": "26.8.0-beta.0", "version": "26.9.0-beta.1",
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.", "description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
"license": "MIT", "license": "MIT",
"author": "green-tea contributors", "author": "green-tea contributors <projects@expressive-tea.io>",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea.git" "url": "git+https://github.com/Expressive-Tea/green-tea.git"
}, },
"bugs": { "bugs": {
"url": "https://github.com/Expressive-Tea/green-tea/issues" "url": "https://github.com/Expressive-Tea/green-tea/issues",
"email": "projects@expressive-tea.io"
}, },
"homepage": "https://green-tea.expressive-tea.io/docs/", "homepage": "https://green-tea.expressive-tea.io/docs/",
"keywords": [ "keywords": [
@@ -90,18 +91,18 @@
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/", "test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/", "test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts", "test:edge": "tsx test/edge/run.ts",
"test:all": "npm test && npm run test:deno && npm run test:bun && npm run test:edge && deno publish --dry-run --allow-dirty",
"typecheck": "tsc --noEmit -p tsconfig.json", "typecheck": "tsc --noEmit -p tsconfig.json",
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
"lint": "eslint src", "lint": "eslint src",
"lint:fix": "eslint src --fix", "lint:fix": "eslint src --fix",
"format": "prettier --write \"src/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"", "format:check": "prettier --check \"src/**/*.ts\"",
"docs:dev": "npm --prefix website run dev",
"docs:build": "npm --prefix website run build",
"complexity": "ccts src", "complexity": "ccts src",
"complexity:check": "node scripts/check-complexity.mjs", "complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25", "complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts", "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", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true" "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);
+581 -61
View File
@@ -1,7 +1,8 @@
import type http from 'http'; 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 { 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 { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
@@ -11,6 +12,9 @@ import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocke
import { isAsyncIterable } from '../channel'; import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import { installSignalHandlers } from '../http/signals-shutdown';
import type { Hooks } from './types';
import { import {
Ctor, Ctor,
getModuleMeta, getModuleMeta,
@@ -26,7 +30,7 @@ import {
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views'; import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi'; 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 { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup'; import { buildRemote } from '../mesh/teacup';
@@ -37,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router'; 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; type Runner = (ctx: any) => any;
@@ -47,11 +51,18 @@ interface Registry {
stepNodes: GraphNode[]; stepNodes: GraphNode[];
runners: Map<string, Runner>; runners: Map<string, Runner>;
providerMeta: Map<string, { optional: boolean }>; 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[]; routePlans: RoutePlan[];
exportedProviders: string[]; exportedProviders: string[];
exportedSteps: string[]; exportedSteps: string[];
exportedRoutes: RouteEntry[]; exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void; setRunner(name: string, runner: Runner, framework?: boolean): void;
} }
/** /**
@@ -75,6 +86,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[]; planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus; bus: Bus;
onError?: ErrorRenderer; onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
} }
/** /**
@@ -85,6 +98,14 @@ interface PipelineDeps {
export function createApp(opts: { export function createApp(opts: {
modules: Ctor[]; modules: Ctor[];
plugins?: Plugin[]; 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; mesh?: MeshConfig;
limits?: RequestLimits; limits?: RequestLimits;
devGraph?: boolean; devGraph?: boolean;
@@ -103,6 +124,62 @@ export function createApp(opts: {
viewEngine?: (source: string, data: unknown) => string; viewEngine?: (source: string, data: unknown) => string;
/** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */ /** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */
static?: boolean | string; static?: boolean | string;
/**
* How long `close()` gives in-flight work before forcing remaining connections shut, in ms
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
* reached from a signal handler, a test helper or a shutdown hook you do not own, which is
* 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).
*
* Registered here rather than declared as a provider, and the ordering is why: provider boot
* events and the failures they report happen *while* the graph resolves, so a provider cannot
* report its own boot failing, and shutdown warnings happen after the graph is gone. The logger
* has to outlive the graph on both ends. It is also reachable from a step or handler as
* `@needs('logger')` — one object, two access paths.
*/
logger?: Logger;
/**
* Log one line per completed request, and one per failed one (default: off).
*
* Off by default because a framework that writes to stdout without being asked is a framework
* you have to configure before you can use it. On, it is a subscriber to the lifecycle stream
* like any other consumer — `logRequests(app.bus, app.logger)` does the same thing by hand and
* hands back an unsubscribe, so nothing here is reachable only through this flag.
*/
logRequests?: boolean;
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
experimental?: boolean; experimental?: boolean;
/** /**
@@ -120,6 +197,8 @@ export function createApp(opts: {
} }
const bus = new Bus(); const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger);
const container = new Container(); const container = new Container();
let server: http.Server | undefined; let server: http.Server | undefined;
const streams = new Set<() => void>(); const streams = new Set<() => void>();
@@ -129,8 +208,9 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine }; const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx); const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry); const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
provideBuiltins(registry); mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order. // 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. // MVP: every route depends on every declared step + provider in the app graph.
@@ -143,7 +223,7 @@ export function createApp(opts: {
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
const finalize = (): void => { const finalize = (): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth));
booted = true; booted = true;
}; };
@@ -151,7 +231,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, 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; let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -159,7 +239,7 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time. // can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => { const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) { if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
remoteRoutes = spliced.remoteRoutes; remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks); meshLinks.push(...spliced.meshLinks);
finalize(); finalize();
@@ -207,7 +287,7 @@ export function createApp(opts: {
registry, registry,
opts.overrides, opts.overrides,
() => orderedProviders, () => orderedProviders,
{ runners, container, providerMeta, bus }, { runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
degradedProviders, degradedProviders,
ready, ready,
); );
@@ -215,6 +295,8 @@ export function createApp(opts: {
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const fetchOpts: HttpOptions = { const fetchOpts: HttpOptions = {
bus,
logger,
limits: opts.limits, limits: opts.limits,
tls: opts.tls, tls: opts.tls,
trustProxy: opts.trustProxy, trustProxy: opts.trustProxy,
@@ -226,7 +308,7 @@ export function createApp(opts: {
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
routePlans, routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError }, { providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts, fetchOpts,
bootApp, bootApp,
devRoutes, devRoutes,
@@ -245,6 +327,8 @@ export function createApp(opts: {
const wsRoutes = buildWsRoutes(routePlans, deps); const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
bus,
logger,
limits: opts.limits, limits: opts.limits,
streams, streams,
tls: opts.tls, tls: opts.tls,
@@ -257,26 +341,52 @@ export function createApp(opts: {
}); });
server.on('close', () => closeLinks(meshLinks)); server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve)); 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; return server;
}; };
const close = (): Promise<void> => // Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is
new Promise<void>((resolve) => { // load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app
// before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen() // that closed itself and expected to exit would simply hang.
// never runs) has links but no server, and would otherwise leak every teapot connection. let removeSignalHandlers: (() => void) | undefined;
// Closing a link rejects its in-flight RPCs via the socket's abort.
closeLinks(meshLinks);
if (!server) return resolve(); const clearSignalHandlers = (): void => {
removeSignalHandlers?.();
removeSignalHandlers = undefined;
};
server.close(() => resolve()); // waits for in-flight buffered to drain const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves clearSignalHandlers();
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive 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 { return {
listen, listen,
close, close,
handleSignals,
ready, ready,
fetch: fetchFn, fetch: fetchFn,
upgrade: upgradeFn, upgrade: upgradeFn,
@@ -288,6 +398,7 @@ export function createApp(opts: {
openapi, openapi,
degraded: () => [...degradedProviders], degraded: () => [...degradedProviders],
bus, bus,
logger,
}; };
} }
@@ -295,7 +406,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry { function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn 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)) if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner); runners.set(name, runner);
@@ -306,6 +422,7 @@ function emptyRegistry(): Registry {
stepNodes: [], stepNodes: [],
runners, runners,
providerMeta: new Map(), providerMeta: new Map(),
providerInstances: new Map(),
routePlans: [], routePlans: [],
exportedProviders: [], exportedProviders: [],
exportedSteps: [], exportedSteps: [],
@@ -322,6 +439,7 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
registry.providerMeta.set(meta.provides, { optional: meta.optional }); registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides); if (meta.export) registry.exportedProviders.push(meta.provides);
const instance: any = new ProviderClass(); const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx)); registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
} }
} }
@@ -438,12 +556,40 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
return 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. */ /** 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 extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) }; 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) { for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' }; const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -454,12 +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. */ /** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry): void { /**
if (registry.runners.has('rooms')) return; * 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.
builtin('logger', () => ({ logger }));
const roomsInstance = new Rooms(); const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); builtin('rooms', () => ({ rooms: roomsInstance }));
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms // 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 // Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -473,6 +653,7 @@ const DEEP_GRAPH_WARN = 20;
*/ */
function finalizeGraph( function finalizeGraph(
registry: Registry, registry: Registry,
logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN, warnDepth: number | false = DEEP_GRAPH_WARN,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry; const { providerNodes, stepNodes, routePlans } = registry;
@@ -492,10 +673,11 @@ function finalizeGraph(
const depth = closure.filter((node) => stepNodes.includes(node)).length; const depth = closure.filter((node) => stepNodes.includes(node)).length;
if (warnDepth !== false && depth > warnDepth) { if (warnDepth !== false && depth > warnDepth) {
console.warn( logger.warn(
`[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` + `${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` + `It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`, `is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
{ route: plan.pattern, method: plan.method, depth, threshold: warnDepth },
); );
} }
} }
@@ -515,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) { for (const plan of routePlans) {
for (const need of plan.needs) { for (const need of plan.needs) {
if (allowed.has(need)) continue; 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); const hint = nearest(need, allowed);
throw new Error( throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
@@ -523,11 +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. */ /** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
async function spliceRemoteScopes( async function spliceRemoteScopes(
mesh: MeshConfig, mesh: MeshConfig,
bus: Bus, bus: Bus,
registry: Registry, registry: Registry,
logger: Logger,
container: Container,
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
const remoteRoutes: RouteDef[] = []; const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
@@ -535,13 +823,23 @@ async function spliceRemoteScopes(
try { try {
for (const teapot of mesh.teapots ?? []) { for (const teapot of mesh.teapots ?? []) {
const link = await connectLink({ warnIfCleartext(teapot.url, logger);
url: teapot.url, // Deferred so the reconnect callback can name this link's provider tokens, which are only
secret: teapot.secret, // known once its manifest arrives — the callback is registered before the link can drop.
timeoutMs: mesh.timeoutMs, const rebind: Array<() => void> = [];
heartbeatMs: mesh.heartbeatMs, const link = await connectUntilDeadline(mesh, bus, logger, () =>
bus, 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); meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link); const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`; const origin = `mesh:${teapot.url}`;
@@ -550,6 +848,10 @@ async function spliceRemoteScopes(
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin }); registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
registry.providerMeta.set(provider.name, { optional: false }); registry.providerMeta.set(provider.name, { optional: false });
registry.setRunner(provider.name, provider.run); 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) { for (const step of steps) {
@@ -588,8 +890,8 @@ async function spliceRemoteScopes(
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape, compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
) )
) { ) {
console.warn( logger.warn(
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` + `mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' + 'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.', 'Remove one if that is not what you meant.',
); );
@@ -599,7 +901,19 @@ async function spliceRemoteScopes(
method: route.method, method: route.method,
pattern: route.pattern, pattern: route.pattern,
transport: 'buffer', 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 },
}),
}); });
} }
} }
@@ -623,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). * @returns The names of optional providers that failed and are running degraded (unregistered).
*/ */
async function bootProviders( async function bootProviders(
@@ -633,31 +980,45 @@ async function bootProviders(
runners: Map<string, Runner>; runners: Map<string, Runner>;
container: Container; container: Container;
providerMeta: Map<string, { optional: boolean }>; providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus; bus: Bus;
logger: Logger;
}, },
): Promise<string[]> { ): Promise<string[]> {
const { runners, container, providerMeta, bus } = deps; const { providerMeta, providerInstances, teardown, logger } = deps;
const degraded: string[] = []; const degraded: string[] = [];
for (const node of orderedProviders) { for (const level of topoLevels(orderedProviders)) {
bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); // 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 { // Teardown in level order, not completion order. `orderedProviders` is topologically sorted and
const value = await runners.get(node.name)!(await snapshot(container, node.needs)); // the registry runs in reverse, which is what gives dependants teardown before their
container.register(node.name, 'app', () => value); // dependencies for free — a guarantee that would have become luck if this followed whichever
await container.resolve(node.name); // warm the cache // provider happened to settle first. Registered before the failure pass so a level that aborts
bus.emit('boot:provider:ok', { name: node.name }); // the boot still leaves its successful siblings closeable.
} catch (error) { //
bus.emit('boot:provider:fail', { name: node.name, error }); // 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) { 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 // 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 // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
degraded.push(node.name); degraded.push(node.name);
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`); logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error });
} }
} }
@@ -679,7 +1040,10 @@ function makeAppBooter(
runners: Map<string, Runner>; runners: Map<string, Runner>;
container: Container; container: Container;
providerMeta: Map<string, { optional: boolean }>; providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus; bus: Bus;
logger: Logger;
}, },
degradedProviders: string[], degradedProviders: string[],
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */ /** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
@@ -692,8 +1056,9 @@ function makeAppBooter(
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
if (degradedProviders.length) { if (degradedProviders.length) {
console.warn( deps.logger.warn(
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`, `started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
{ degraded: degradedProviders },
); );
} }
}; };
@@ -719,7 +1084,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined; if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps; 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 manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
@@ -730,7 +1095,14 @@ function buildMeshControl(
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name)); 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 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]; return context[name];
}; };
@@ -751,7 +1123,15 @@ function buildMeshControl(
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, 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 }, seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
}); });
@@ -769,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. */ /** 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[] { 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 const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -788,7 +1168,17 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, 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.
correlation: {
requestId: req.requestId,
traceId: req.traceId,
route: plan.pattern,
method: plan.method,
transport: plan.transport,
},
seed: { seed: {
...provided, ...provided,
req, req,
@@ -957,6 +1347,136 @@ 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[],
streams: Set<() => void>,
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
logger: Logger,
teardown: TeardownRegistry,
reservedMs: number | undefined,
): Promise<void> {
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);
// No server means the app is served through `app.fetch` rather than `listen()`, which is how
// Deno, Bun and the edge all run. Draining is the transport's job and only the transport holds
// the handle, so `close()` is deliberately Node-only here rather than pretending otherwise;
// `serveDeno`/`serveBun` return a server with the same bounded `close({ timeoutMs })`.
if (!server) {
if (options.timeoutMs !== undefined) {
logger.warn(
'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();
}
let settled = false;
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
// is the point. Whichever one comes second is referenced by the other before its declaration
// runs, so what matters is which forward reference rests on a guarantee. setTimeout cannot
// invoke its callback synchronously — that is the event loop, not an implementation detail —
// so `finish` is always assigned by the time the callback can reach it. The reverse ordering
// relied on `server.close(cb)` deferring, which is Node's behaviour rather than a promise to
// us, and left a `ReferenceError` waiting in the shutdown path for whoever changed it.
const timer = setTimeout(() => {
if (settled) return;
logger.warn(`graceful shutdown timed out after ${timeoutMs}ms — forcing remaining HTTP connections closed`, {
timeoutMs,
});
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
// below — `engines` in package.json only guarantees >=18, so this matters.
server.closeAllConnections();
finish();
}, drainBudget);
timer.unref?.();
const finish = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
server.close(() => finish());
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. */ /** Best-effort close of every mesh link, ignoring individual failures. */
function closeLinks(links: Link[]): void { function closeLinks(links: Link[]): void {
for (const link of links) { for (const link of links) {
+61 -1
View File
@@ -1,5 +1,7 @@
import type http from 'http'; import type http from 'http';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { TeardownFn } from '../lifecycle';
import type { GraphNode } from '../graph'; import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz'; import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata'; import type { HttpMethod, Transport } from '../metadata';
@@ -35,7 +37,16 @@ export interface Explain {
/** A running application instance with lifecycle, introspection and graph-export methods. */ /** A running application instance with lifecycle, introspection and graph-export methods. */
export interface App { export interface App {
listen(port: number): Promise<http.Server>; listen(port: number): Promise<http.Server>;
close(): Promise<void>; 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 * 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 * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
@@ -62,6 +73,12 @@ export interface App {
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */ /** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
degraded(): string[]; degraded(): string[];
bus: Bus; bus: Bus;
/**
* Where framework diagnostics are written — the one passed to `createApp({ logger })`, or the
* default. Exposed so the Deno and Bun adapters report through the application's logger rather
* than reaching past it to `console`, and so a plugin or a test can read what core would write.
*/
logger: Logger;
} }
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */ /** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
@@ -95,4 +112,47 @@ export interface MeshConfig {
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter. * `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
*/ */
heartbeatMs?: number; 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;
} }
+46 -3
View File
@@ -3,6 +3,7 @@ import type { Channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core'; import type { WsSocket, WsRequest } from './http/ws-core';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -21,10 +22,25 @@ interface BunWebSocketHandler {
} }
interface BunServer { interface BunServer {
port: number; port: number;
stop(closeActiveConnections?: boolean): void; // Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it
// hid the fact that this is awaitable at all.
stop(closeActiveConnections?: boolean): Promise<void>;
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean; upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
requestIP(request: Request): { address: string; family: string; port: number } | null; requestIP(request: Request): { address: string; family: string; port: number } | null;
} }
/**
* What {@link serveBun} hands back: Bun's own server, plus the bounded `close()` that
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Bun,
* because a Bun app is served through `app.fetch` and never through `listen()`.
*/
export interface BunServeResult extends BunServer {
/**
* Drains in-flight requests, then force-closes whatever is left after `timeoutMs` (default:
* 10s). Same meaning as `app.close({ timeoutMs })` on Node.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
}
interface BunServeOptions { interface BunServeOptions {
port?: number; port?: number;
hostname?: string; hostname?: string;
@@ -56,9 +72,11 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level * Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state * websocket handler. The ServerWebSocket only exists in open(), so per-connection state
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade. * (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
* Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy.
*/ */
export function serveBun(app: App, options?: BunServeShortOptions): BunServer { export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult {
return Bun.serve({ const server = Bun.serve({
...options, ...options,
fetch(request, server) { fetch(request, server) {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
@@ -95,4 +113,29 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
}, },
}, },
}); });
// 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, {
// 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(
// 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) =>
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
timeoutMs: ms,
runtime: 'bun',
}),
),
),
});
} }
+149 -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 = export type LifecycleEvent =
| 'boot:provider:start' | 'boot:provider:start'
| 'boot:provider:ok' | 'boot:provider:ok'
@@ -6,20 +30,127 @@ export type LifecycleEvent =
| 'request:step:enter' | 'request:step:enter'
| 'request:step:leave' | 'request:step:leave'
| 'request:step:error' | '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:open'
| 'stream:close' | 'stream:close'
| 'stream:error' | 'stream:error'
| 'mesh:connect' | 'mesh:connect'
| 'mesh:disconnect' | 'mesh:disconnect'
| 'mesh:rpc:error' | 'mesh:rpc:error'
| 'plugin:mounted'; // 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. 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';
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */ /**
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
* the fields that say which request it belongs to.
*
* 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 { 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; name: string;
scope?: string; scope?: string;
error?: unknown; error?: unknown;
durationMs?: number; durationMs?: number;
/** Correlates every event of one request. Adopted from `x-request-id` when a gateway sent one. */
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}.
*
* 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;
}
/**
* The subset of {@link EventPayload} that identifies a request, spread into each of its events.
*
* `route` carries the matched pattern rather than the URL that arrived, and that is load-bearing
* rather than cosmetic: 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. Handing anyone that shape by default would be the framework's fault.
*/
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. */ /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
@@ -34,6 +165,21 @@ export class Bus {
return () => listenerSet.delete(listener); return () => listenerSet.delete(listener);
} }
/**
* Whether anything is listening to `event` — for skipping the *construction* of a payload nobody
* will read.
*
* Not a micro-optimisation looking for a problem. A correlated payload is built by spreading the
* request's identity into it, and that spread was measured at ~197 ns per request on a two-step
* pipeline — against a ~4.5 µs in-process request, on a path where the overwhelmingly common
* case is an application that subscribes to nothing at all. `emit` cannot help: its argument is
* already built by the time it is called. Only the caller can decline to build it.
*/
hasListeners(event: LifecycleEvent): boolean {
const listenerSet = this.listeners.get(event);
return listenerSet !== undefined && listenerSet.size > 0;
}
/** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */ /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
emit(event: LifecycleEvent, payload: EventPayload): void { emit(event: LifecycleEvent, payload: EventPayload): void {
for (const listener of this.listeners.get(event) ?? []) { for (const listener of this.listeners.get(event) ?? []) {
+62 -2
View File
@@ -1,5 +1,6 @@
import type { App } from './app/types'; import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) // The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. // doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
@@ -22,6 +23,23 @@ interface DenoHttpServer {
finished: Promise<void>; finished: Promise<void>;
shutdown(): Promise<void>; shutdown(): Promise<void>;
} }
/**
* What {@link serveDeno} hands back: Deno's own server, plus the bounded `close()` that
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Deno,
* because a Deno app is served through `app.fetch` and never through `listen()`.
*/
export interface DenoServer extends DenoHttpServer {
/**
* Drains in-flight requests, returning after at most `timeoutMs` (default: 10s).
*
* **The deadline bounds the wait, not the connections** — unlike Node's `app.close()` and Bun's
* `close()`, which force the remainder shut. Deno offers no force-close that composes with a
* drain already under way: aborting the serve signal at that point throws `BadResource` from
* Deno's own listener, uncaught. Whatever is still open when this resolves ends with the process.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
}
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>; type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
declare const Deno: { declare const Deno: {
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer; serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
@@ -31,9 +49,17 @@ declare const Deno: {
/** /**
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. * Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
* WebSocket messages flow through app.upgrade over the shared neutral core. * WebSocket messages flow through app.upgrade over the shared neutral core.
* Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
* the deployment platform or reverse proxy.
*/ */
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
return Deno.serve(options ?? {}, (request, info) => { // Deno's only force-close lever is the abort signal it was served with, so the adapter has to
// own one to offer a deadline at all. A caller-supplied signal still works and still aborts the
// server — it is chained into ours rather than replaced, so neither party loses its control.
const ac = new AbortController();
options?.signal?.addEventListener('abort', () => ac.abort(), { once: true });
const server = Deno.serve({ ...options, signal: ac.signal }, (request, info) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
// Deno invalidates request connection metadata as soon as the upgrade is accepted. // Deno invalidates request connection metadata as soon as the upgrade is accepted.
const wsRequest = toWsRequest(request, info.remoteAddr.hostname); const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
@@ -46,4 +72,38 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer
return app.fetch(request); return app.fetch(request);
}); });
// 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, {
// 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(
// 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
// surfaces uncaught — not catchable at this call site, and fatal under `deno test`.
// Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot
// escalate from graceful to forced the way Node's closeAllConnections() and Bun's
// stop(true) can, and the deadline here bounds how long `close()` waits, not when the
// connections die. Exiting the process after `close()` resolves is what ends them.
() => {},
closeOptions.timeoutMs ?? 10_000,
(ms) =>
app.logger.warn(
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
'a server that is already draining, so remaining connections end when the process does.',
{ 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. * Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` * 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. * 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( export function edgeHandler(
app: App, 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)); 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. */ /** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = { export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }, 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`, encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n', ping: () => ': ping\n\n',
}; };
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
/** Newline-delimited JSON encoder: one JSON object per line. */ /** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = { export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' }, 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`, 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; 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`. */ /** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
const producedBy = new Map<string, GraphNode>(); const producedBy = new Map<string, GraphNode>();
+135
View File
@@ -0,0 +1,135 @@
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
// the caller as a {@link BodyReader}.
import { HttpError, isHttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string };
}
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
export type MaybePromise<T> = T | Promise<T>;
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
return value instanceof Promise;
}
/**
* Reads the raw request body, enforcing `limit`.
*
* The adapter owns this and nothing else about the body, because enforcement is the one place the
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
* without bound first.
*
* The failure branch is opaque on purpose: Node answers an over-limit request with
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
* That header means nothing on the fetch side, and is a forbidden response header on some
* runtimes, so the adapter that needs it is the one that attaches it.
*
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
* reader can be built **once per server** instead of once per request: a closure capturing the
* request measured at 250 ns per request together with the error-context object it captured —
* more than the duplicate route resolution this whole indirection removes.
*/
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
/**
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
*
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
* character for character, because each adapter had to route the request itself in order to know
* whether to read a body — and so ended up owning every policy that depends on the matched route.
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
* runtimes quietly disagree about limits.
*/
export function acquireBody(
read: BodyReader,
source: unknown,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
const acquired = read(source, limit);
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
// this whole path without a single promise, and an `async` wrapper here would allocate one
// regardless. Same reason `handle()` is not async.
return isPromise(acquired)
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
: parseAcquired(acquired, matched, opts, req);
}
function parseAcquired(
acquired: { bytes: Buffer | undefined } | BodyFailure,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
if ('fail' in acquired) return acquired;
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
// off the promise path entirely.
if (acquired.bytes === undefined) return { body: undefined };
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body },
);
}
+286 -12
View File
@@ -5,23 +5,111 @@ import { isStreamResult, type PipelineResult } from '../pipeline';
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router'; import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream'; import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */ /**
* `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.
*
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
* body, it first had to route the request itself — a body is only read for a request that reaches
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
* a four-route app walked its table two and a half times per request. Handing over the *ability*
* to read instead of the result moves that decision here, where the route is known anyway.
*/
export interface NeutralRequest { export interface NeutralRequest {
method: string; method: string;
url: string; // path + query, e.g. "/users/9?x=1" url: string; // path + query, e.g. "/users/9?x=1"
headers: Record<string, string | string[] | undefined>; headers: Record<string, string | string[] | undefined>;
body: unknown; // already-parsed body /** Called only once a route matches, so an unmatched request still never reads a body. */
readBody: BodyReader;
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
source: unknown;
secure: boolean; secure: boolean;
ip: string; ip: string;
requestId: string;
traceId?: string;
}
// Module scope, not a local inside `correlateRequest`. Declared there it was a closure allocated
// on every single request, which measured at 0.16 us against a ~4.4 us one — 45% of the whole
// observability overhead, for a helper that captures nothing.
const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
/**
* Derives a request's identity from its headers, for the adapters to stamp on a `NeutralRequest`.
*
* **Called by the adapters, not by {@link handle}**, and the placement is the point. An adapter's
* `BodyReader` renders its own `413` (`server.ts`, `web.ts`) without `handle()` ever producing it,
* so identity has to exist before the read starts. Generating it in here would leave precisely the
* failures an operator most wants to correlate with nothing to correlate them by.
*
* An `x-request-id` from a gateway is adopted rather than replaced — a service behind a proxy must
* not open a second identity for a request that already has one. `traceparent` is carried through
* untouched: core implements no propagation spec, and W3C Trace Context belongs to the exporter.
*/
export function correlateRequest(headers: Record<string, string | string[] | undefined>): {
requestId: string;
traceId?: string;
} {
const incoming = first(headers['x-request-id'])?.trim();
const traceId = first(headers.traceparent)?.trim();
// `randomUUID` is not the lazy choice here, it is the measured one. Every supported runtime
// already batches entropy behind it, so the obvious "faster" replacements are not:
//
// crypto.randomUUID() 76 ns
// batched getRandomValues + hex, 12 bytes 50 ns cross-runtime, saves 0.26% of a request
// batched + Buffer.toString('hex') 49 ns Node-only, so it cannot be used here
// uint32 -> toString(36) from a pool 114 ns
// Math.random() x2 -> base36 265 ns 3.5x SLOWER; string work dominates
// getRandomValues per call, unbatched 472 ns
//
// 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 || randomUUID(), traceId: traceId || undefined };
} }
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ /** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome = export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer } | { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder }; | {
kind: 'stream';
headers: Record<string, string>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
route: string;
};
/** {@link handle}'s result for a normal (non-preflight) request. */ /** {@link handle}'s result for a normal (non-preflight) request. */
export interface HandleResult { export interface HandleResult {
@@ -45,7 +133,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> }, req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> { ): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; 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; return injected;
} }
@@ -56,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: {
@@ -104,17 +192,151 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {}); 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;
}
/** /**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response. * caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
*
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
* here in milliseconds while its connection may live for hours, and ending the span at close would put
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
*/ */
export async function handle( export function handle(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
req: NeutralRequest, req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req); const bus = opts?.bus;
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
if (
bus === undefined ||
!(
bus.hasListeners('request:start') ||
bus.hasListeners('request:end') ||
bus.hasListeners('route:matched') ||
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined, injected);
}
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(
routes: RouteDef[],
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;
const trace: Trace = {};
if (bus.hasListeners('request:start'))
bus.emit('request:start', {
name: `${req.method} ${req.url}`,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
});
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
// by the time anything is piped.
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
bus.emit('request:end', {
name: trace.route ?? `${req.method} ${req.url}`,
method: req.method,
route: trace.route,
status,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
return result;
}
async function dispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> {
// 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; let path: string;
try { try {
@@ -124,12 +346,53 @@ export async function handle(
} }
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { 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); const matched = resolveRoute(routes, req.method, path);
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected); 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,
});
return unmatchedOutcome(routes, opts, req, path, injected);
}
if (trace) trace.route = matched.def.pattern;
if (bus?.hasListeners('route:matched'))
bus.emit('route:matched', {
name: matched.def.pattern,
route: matched.def.pattern,
method: req.method,
transport: matched.def.transport,
requestId: req.requestId,
traceId: req.traceId,
});
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
// object per request bought nothing.
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
// caller merges `injected` into it exactly as it does for every other outcome.
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
let result: PipelineResult; let result: PipelineResult;
@@ -140,17 +403,28 @@ export async function handle(
headers: req.headers, headers: req.headers,
params: matched.params, params: matched.params,
query: parseQuery(req.url), query: parseQuery(req.url),
body: req.body, body: acquired.body,
protocol: req.secure ? 'https' : 'http', protocol: req.secure ? 'https' : 'http',
ip: req.ip, ip: req.ip,
requestId: req.requestId,
traceId: req.traceId,
}); });
} catch (error) { } catch (error) {
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); result = renderError(error, req, opts?.onError, opts?.logger);
} }
if (isStreamResult(result)) { if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; return {
injected,
outcome: {
kind: 'stream',
headers: encoder.headers,
stream: result.stream,
encoder,
route: matched.def.pattern,
},
};
} }
return { return {
+12 -2
View File
@@ -1,5 +1,7 @@
import { mergeVary } from '../security'; import { mergeVary } from '../security';
const hasOwn = Object.prototype.hasOwnProperty;
/** /**
* Merges a handler's response headers with authoritative `injected` headers * Merges a handler's response headers with authoritative `injected` headers
* (security + CORS). Injected keys win case-insensitively; `vary` is merged. * (security + CORS). Injected keys win case-insensitively; `vary` is merged.
@@ -10,7 +12,6 @@ export function mergeInjectedHeaders(
injected: Record<string, string>, injected: Record<string, string>,
): Record<string, any> { ): Record<string, any> {
const merged: Record<string, any> = {}; const merged: Record<string, any> = {};
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
let handlerVary: string | undefined; let handlerVary: string | undefined;
if (handlerHeaders) if (handlerHeaders)
@@ -22,7 +23,16 @@ export function mergeInjectedHeaders(
continue; continue;
} }
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; // `injected` is looked up directly instead of through a lowercased Set rebuilt per response.
// Every key it can hold is written as a lowercase literal in `src/security.ts` — both
// `buildSecurityHeaders` and `resolveCors`, which are its only sources — so lowercasing them
// again produced a copy of the keys it already had. Three allocations per response (an array,
// a mapped array, a Set) to answer a question the object answers itself: 146.4 ns against
// 55.9 ns.
//
// `hasOwnProperty` rather than `in`: a handler is free to send a header called `constructor`
// or `toString`, and `in` would find those on Object.prototype and silently drop them.
if (!hasOwn.call(injected, lowerKey)) merged[key] = handlerHeaders[key];
} }
Object.assign(merged, injected); Object.assign(merged, injected);
+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--;
},
};
}
+175 -28
View File
@@ -163,27 +163,117 @@ export function compilePattern(pattern: string): CompiledPattern {
return compiled; return compiled;
} }
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
/**
* Classifies one path segment as `.`, `..`, or neither.
*
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
* plain form resolves away from.
*/
function dotSegment(segment: string): '.' | '..' | undefined {
if (segment === '.' || segment === '..') return segment;
if (segment.length > 6 || !segment.includes('%')) return undefined;
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
return decoded === '.' || decoded === '..' ? decoded : undefined;
}
/**
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
*
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
* simply not recoverable there, so rejecting dot segments outright — which is what this module
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
* runtimes. Resolving is the only rule all four can agree on.
*
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
*/
function resolveDotSegments(path: string): string {
const out: string[] = [];
for (const segment of path.split('/').slice(1)) {
const dots = dotSegment(segment);
if (dots === '.') continue;
if (dots === '..') {
out.pop();
continue;
}
out.push(segment);
}
return `/${out.join('/')}`;
}
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */ /** Applies the public trailing-slash policy and validates every segment's percent encoding. */
export function normalizeRequestPath(path: string): string { export function normalizeRequestPath(path: string): string {
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash'); if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash'); if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
try { // Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment); // `%` at all — which is most of them — pays only the scans.
} catch { const resolved =
throw new InvalidRequestPathError('invalid request path: malformed path encoding'); (path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path;
const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
// Validation only — the decoded value is deliberately discarded, matching is done on the raw
// path. So the work is skipped entirely unless there is something to validate.
//
// This used to split the path and call `decodeURIComponent` per segment, on every request, and
// throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment
// route — around 8% of a whole request, spent proving that a string nobody decodes could be
// decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths.
//
// One call on the whole string rather than per segment is the same check: `decodeURIComponent`
// throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment
// decodes fine either way. Only the throw matters here, never the result.
if (normalized.includes('%')) {
try {
decodeURIComponent(normalized);
} catch {
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
}
} }
return normalized; return normalized;
} }
function decodeSegment(value: 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;
} }
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined { /**
const pathSegs = path.split('/').filter(Boolean); * Splits a request path into its non-empty segments.
*
* Called once per request by the scanning functions below, not once per candidate route. It used to
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
* registered route on every request, always producing the same array.
*/
function splitPath(path: string): string[] {
return path.split('/').filter(Boolean);
}
/**
* 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> = {}; const params: Record<string, string> = {};
for (let index = 0; index < compiled.segments.length; index++) { for (let index = 0; index < compiled.segments.length; index++) {
@@ -201,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
continue; 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; if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value; params[segment.name] = value;
} }
@@ -211,13 +301,18 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
/** Matches a compiled segment pattern and returns its decoded parameters. */ /** Matches a compiled segment pattern and returns its decoded parameters. */
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined { export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
return matchCompiled(compilePattern(pattern), path); return matchCompiled(compilePattern(pattern), splitPath(path));
} }
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */ /**
function moreSpecific(a: string, b: string): number { * Orders patterns by exactness, then static/constrained/plain segment specificity.
const scoreA = compilePattern(a); *
const scoreB = compilePattern(b); * 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; if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
@@ -230,23 +325,65 @@ function moreSpecific(a: string, b: string): number {
return 0; 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. */
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { interface IndexedRoute {
let best: MatchedRoute | undefined; def: RouteDef;
let bestPattern = ''; compiled: CompiledPattern;
}
for (const route of routes) { /**
if (route.method !== method) continue; * Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
const params = matchPattern(route.pattern, path); * they were built from.
if (!params) continue; *
* 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[]>>();
if (!best || moreSpecific(route.pattern, bestPattern) > 0) { function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
best = { params, def: route }; const cached = routeIndexCache.get(routes);
bestPattern = route.pattern; 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]);
} }
return best; // 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);
const decoded: Array<string | undefined> = new Array(pathSegs.length);
for (const { def, compiled } of candidates) {
const params = matchCompiled(compiled, pathSegs, decoded);
if (params) return { params, def };
}
return undefined;
} }
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */ /** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
@@ -271,10 +408,11 @@ const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ /** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
export function allowedMethods(routes: RouteDef[], path: string): string[] { export function allowedMethods(routes: RouteDef[], path: string): string[] {
const pathSegs = splitPath(path);
const methods = new Set<string>(); const methods = new Set<string>();
for (const route of routes) { for (const route of routes) {
if (!matchPattern(route.pattern, path)) continue; if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
methods.add(route.method); methods.add(route.method);
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD'); if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
} }
@@ -291,6 +429,15 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ /** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
export function parseQuery(url: string): Record<string, string> { export function parseQuery(url: string): Record<string, string> {
// Most requests carry no query string, and the work below is not free for them: `split` builds
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
//
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
// means, and that is a behaviour question rather than a performance one.
if (!url.includes('?')) return {};
const queryString = url.split('?')[1] ?? ''; const queryString = url.split('?')[1] ?? '';
const out: Record<string, string> = {}; const out: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value; for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
+131 -125
View File
@@ -1,29 +1,32 @@
import type http from 'http'; import type http from 'http';
import type https from 'https'; import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import { isHttpError, HttpError } from '../signals';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import { handle } from './core'; import {
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; 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 { interface HandlerConfig {
routes: RouteDef[]; routes: RouteDef[];
bus?: Bus; bus?: Bus;
opts?: HttpOptions; opts?: HttpOptions;
maxBody: number;
trustProxy: boolean; trustProxy: boolean;
} }
/** A ready-to-send error response produced while acquiring the request body. */
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
/** Builds the {@link ErrorRequest} handed to a user error renderer. */ /** Builds the {@link ErrorRequest} handed to a user error renderer. */
function errorRequest(req: http.IncomingMessage): ErrorRequest { function errorRequest(req: http.IncomingMessage): ErrorRequest {
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers }; return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
@@ -44,21 +47,34 @@ export function createHttpServer(
meshControl?: MeshControl, meshControl?: MeshControl,
opts?: HttpOptions, opts?: HttpOptions,
): http.Server { ): http.Server {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
const trustProxy = opts?.trustProxy ?? false; const trustProxy = opts?.trustProxy ?? false;
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy }); const handler = createRequestHandler({ routes, bus, opts, trustProxy });
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe // 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(). // (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 = nodeRequire<typeof import('http')>('http');
const nodeHttp = require('http') as typeof import('http'); const nodeHttps = nodeRequire<typeof import('https')>('https');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls const server: http.Server = (opts?.tls
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler) ? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server; : nodeHttp.createServer(handler)) as unknown as http.Server;
const maxConnections = opts?.limits?.maxConnections ?? 1000;
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.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
@@ -68,61 +84,92 @@ export function createHttpServer(
/** /**
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core. * Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`, * Describes the request, supplies the {@link BodyReader} the core calls once a route matches, then
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is * writes the result to `res` (buffered or streamed). Routing, body parsing, limits and error
* installed here — and stays the single source of truth for merging headers into every response — * rendering all live in the core. The security-header monkeypatch is installed here — and stays the
* so `handle()`'s own `injected` is intentionally unused by this adapter. * single source of truth for merging headers into every response — so `handle()`'s own `injected`
* is intentionally unused by this adapter.
*/ */
function createRequestHandler(cfg: HandlerConfig) { function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, maxBody, trustProxy } = cfg; 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> => { return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
const url = req.url ?? '/';
const path = url.split('?')[0];
const method = req.method ?? 'GET';
// Install the security-header patch BEFORE any routing/response so every path // Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead. // (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy); const secure = deriveSecure(req, trustProxy);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; // Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers);
// 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); patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily let result: HandleResult | Preflight;
// by reference at writeHead time, so keys added here still land on every response. let acquired = false;
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); const watching = watchingRequests(bus);
const startedAt = watching ? performance.now() : 0;
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
// (below) for a request that actually reaches a route handler — matching prior behaviour.
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
let matched: ReturnType<typeof resolveRoute>;
try { try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path)); if (!gate.acquire()) {
} catch { if (watching)
matched = undefined; // handle() owns the standard 400 envelope and injected headers emitShedPair(
} bus,
{
method: req.method ?? 'GET',
url: req.url ?? '/',
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
let body: unknown; res.writeHead(503, {
'content-type': 'application/json',
if (matched) { 'retry-after': '1',
const acquired = await acquireBody(req, matched, opts, maxBody); connection: 'close',
});
if ('fail' in acquired) { res.end(JSON.stringify({ error: 'Service Unavailable' }));
res.writeHead(acquired.fail.status, acquired.fail.headers);
res.end(acquired.fail.body);
return; return;
} }
body = acquired.body; // 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();
});
}
const result = await handle(routes, opts, { result = await handle(
method, routes,
url, opts,
headers: req.headers, {
body, ...correlation,
secure, method: req.method ?? 'GET',
ip: deriveIp(req, trustProxy), url: req.url ?? '/',
}); headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
},
injected,
);
} finally {
if (acquired) {
acquired = false;
gate.release();
}
}
if ('preflight' in result) { if ('preflight' in result) {
res.writeHead(204, result.preflight); res.writeHead(204, result.preflight);
@@ -131,7 +178,15 @@ function createRequestHandler(cfg: HandlerConfig) {
} }
if (result.outcome.kind === 'stream') { if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams); await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return; return;
} }
@@ -140,34 +195,27 @@ function createRequestHandler(cfg: HandlerConfig) {
}; };
} }
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */ /**
async function acquireBody( * The Node half of body acquisition: bytes off the socket, and the over-limit answer.
req: http.IncomingMessage, *
matched: MatchedRoute, * `readBody` enforces the limit against the running total as chunks arrive, so an oversized upload
* is rejected without being buffered. `connection: close` on that response is load-bearing — it
* stops the remainder of the upload from continuing to arrive on a kept-alive socket.
*/
function readRequestBytes(
source: unknown,
limit: number,
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
maxBody: number, ): Promise<{ bytes: Buffer | undefined } | BodyFailure> {
): Promise<{ body: unknown } | BodyFailure> { const req = source as http.IncomingMessage;
let buf: Buffer | undefined;
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
try { return readBodyBytes(req, limit).then(
buf = await readBody(req, bodyLimit); (bytes) => ({ bytes }),
} catch (error) { (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' } } }; return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
} },
);
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
return { fail: rendered };
}
return { body: parsed.body };
} }
/** /**
@@ -184,45 +232,3 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
}; };
} }
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Bounds a graceful shutdown by a deadline, forcing whatever is left.
*
* Shared by the Deno and Bun adapters so the two cannot drift into different meanings of the same
* `timeoutMs`, and shaped like the Node path in `closeApp`: try to drain, and if the deadline
* passes first, force the remainder and resolve anyway.
*
* The race is the point, and it is not paranoia. Both runtimes' force calls were measured against
* a handler that never resolves and returned immediately, but `Bun.stop(true)` was also measured
* waiting out a handler with a pending timer — same call, ~2s, because it awaits pending async
* work rather than only open connections. Awaiting the force call would therefore inherit exactly
* the unbounded wait the deadline exists to prevent. Resolving on our own timer means `close()`
* returns within `timeoutMs` whatever either runtime decides to wait for.
*
* @param graceful Drain in flight work. Unbounded — that is what the deadline is for.
* @param force Stop waiting and drop what is left. Fire-and-forget; its promise is not awaited.
*/
export function closeWithDeadline(
graceful: () => Promise<void>,
force: () => void,
timeoutMs: number,
onTimeout?: (timeoutMs: number) => void,
): Promise<void> {
return new Promise<void>((resolve) => {
let settled = false;
// Armed before `finish` exists, and deliberately: setTimeout cannot invoke its callback
// synchronously, so `finish` is always assigned by the time this can reach it. The reverse
// ordering would rest on when the runtime's own promise settles. Mirrors `closeApp`.
const timer = setTimeout(() => {
if (settled) return;
onTimeout?.(timeoutMs);
force();
finish();
}, timeoutMs);
timer.unref?.();
const finish = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
// A graceful path that rejects still has to end the shutdown: the deadline covers a slow
// close, not a broken one, and leaving close() pending forever is the worse failure.
void graceful().then(finish, finish);
});
}
+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 { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata'; import type { Transport } from '../metadata';
import type { Bus } from '../bus'; import type { Bus, Correlation } from '../bus';
const PING_MS = 15_000; const PING_MS = 15_000;
@@ -35,10 +35,16 @@ export async function pipeStream(
bus?: Bus, bus?: Bus,
name = '', name = '',
streams?: Set<() => void>, streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> { ): 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.writeHead(200, encoder.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting 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](); const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined; let ping: ReturnType<typeof setInterval> | undefined;
@@ -76,13 +82,13 @@ export async function pipeStream(
} }
} }
} catch (err) { } catch (err) {
bus?.emit('stream:error', { name, error: err }); bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err); const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame); if (frame && !res.writableEnded) res.write(frame);
} finally { } finally {
if (ping) clearInterval(ping); if (ping) clearInterval(ping);
streams?.delete(closer); streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end(); if (!res.writableEnded && !res.destroyed) res.end();
bus?.emit('stream:close', { name }); bus?.emit('stream:close', trace);
} }
} }
+17 -1
View File
@@ -4,10 +4,14 @@ import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views'; import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
/** Per-request size and timeout ceilings applied by the server. */ /** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits { export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000 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 requestTimeoutMs?: number; // default 30_000
headersTimeoutMs?: number; // default 10_000 headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000 keepAliveTimeoutMs?: number; // default 5_000
@@ -16,6 +20,14 @@ export interface RequestLimits {
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */ /** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
export interface HttpOptions { export interface HttpOptions {
/**
* Lifecycle events go here. Carried on the options rather than as a parameter so `handle()` —
* the one place both the Node and Fetch adapters meet — can emit without either adapter growing
* 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; limits?: RequestLimits;
streams?: Set<() => void>; streams?: Set<() => void>;
tls?: TlsOptions; tls?: TlsOptions;
@@ -37,6 +49,10 @@ export type RouteHandler = (req: {
body: unknown; body: unknown;
protocol: 'http' | 'https'; protocol: 'http' | 'https';
ip: string; ip: string;
/** Correlates every lifecycle event this request emits; see `correlateRequest` in `./core`. */
requestId: string;
/** An incoming `traceparent`, carried verbatim for an exporter to interpret. */
traceId?: string;
}) => Promise<PipelineResult>; }) => Promise<PipelineResult>;
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */ /** A registered HTTP route: method, path pattern, streaming transport, and handler. */
+206 -102
View File
@@ -1,34 +1,85 @@
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, 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 { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server'; import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { normalizeRequestPath, resolveRoute } from './router';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types'; 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 iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder(); 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>({ return new ReadableStream<Uint8Array>({
start() {
bus?.emit('stream:open', trace);
},
async pull(controller) { async pull(controller) {
try { try {
const { value, done } = await iterator.next(); const { value, done } = await iterator.next();
if (done) { if (done) {
close();
controller.close(); controller.close();
return; return;
} }
const encoded = encoder.encode(value); controller.enqueue(frame(encoder.encode(value)));
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
controller.enqueue(bytes);
} catch (err) { } catch (err) {
controller.error(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() { async cancel() {
close();
await iterator.return?.(); await iterator.return?.();
}, },
}); });
@@ -44,130 +95,183 @@ function headersToRecord(headers: Headers): Record<string, string> {
} }
/** /**
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the * The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where *
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures * Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
* (413/400/501) carry them too. * or not at all, so the limit can only be checked once the bytes are already in memory. That
* difference is exactly why the limit is passed in rather than applied by the shared core.
*/ */
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response { function readFetchBytes(
const headers = mergeInjectedHeaders(rendered.headers, injected); source: unknown,
return new Response(rendered.body, { status: rendered.status, headers }); limit: number,
opts: HttpOptions | undefined,
): MaybePromise<{ bytes: Buffer | undefined } | BodyFailure> {
const request = source as Request;
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => {
if (arrayBuffer.byteLength > limit) {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
} }
/** /**
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node * Whatever the host runtime's `Response` accepts as a body. Derived from the constructor rather
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure. * than written as `BodyInit`, because that name is not global under this `lib` (`es2020` plus
* `@types/node`) even though `Response` itself is — and Deno spells the same idea from its own lib.
*/ */
async function acquireFetchBody( type ResponseBody = ConstructorParameters<typeof Response>[0];
request: Request,
matched: MatchedRoute,
headers: Record<string, string>,
path: string,
maxBody: number,
opts: HttpOptions | undefined,
injected: Record<string, string>,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
if (request.body) { /**
const arrayBuffer = await request.arrayBuffer(); * Narrows a buffered body to something the runtime's `Response` accepts.
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; *
* A Node `Buffer` is a `Uint8Array` at runtime, so every runtime here takes one — but its declared
if (arrayBuffer.byteLength > bodyLimit) { * backing store is `ArrayBufferLike`, which admits `SharedArrayBuffer`, and `BodyInit` accepts only
return { * `ArrayBuffer`-backed views. Deno's lib therefore rejects it outright: this is the `app.fetch` path,
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected), * so the mismatch reaches Deno, Bun and edge alike. Node never allocates a Buffer over a
}; * `SharedArrayBuffer`, which is what makes the assertion on the backing store safe to state.
} *
* `byteOffset`/`byteLength` are load-bearing, not defensive. `Buffer.from` and `Buffer.allocUnsafe`
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); * hand back a window into a shared 8 KB pool, so re-viewing the backing store without them yields
} * the whole pool — neighbouring allocations included. Today the only Buffer reaching here comes from
* `fs.promises.readFile`, which returns an exactly-sized allocation, so nothing currently trips that.
const contentType = headers['content-type'] ?? ''; * `StaticHit.body` is typed `Buffer` though, and a pooled one is a correct value for it.
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; *
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; * Re-viewing rather than copying: this is the buffered-response path, and a copy per response would
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts); * be a real cost on the runtimes that have no other adapter.
*/
if ('error' in parsed) { export function toBodyInit(body: string | Buffer): ResponseBody {
return { if (typeof body === 'string') return body;
response: errorResponse( return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
injected,
),
};
}
return { body: parsed.body };
} }
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ /** 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>; const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') { 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 : result.outcome.body; const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
return new Response(body, { status: result.outcome.status, headers }); return new Response(body, { status: result.outcome.status, headers });
} }
/** /**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the * describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed). * calls once a route matches, and converts the outcome to a `Response` (buffered or streamed).
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/ */
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; // 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> => { return async (request: Request): Promise<Response> => {
const url = new URL(request.url); const url = new URL(request.url);
const path = url.pathname + url.search; const path = url.pathname + url.search;
const headers = headersToRecord(request.headers); const headers = headersToRecord(request.headers);
let matched: ReturnType<typeof resolveRoute>; // Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(headers);
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so a preflight — the one response
// this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers });
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(opts?.bus);
const startedAt = watching ? performance.now() : 0;
try { try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname)); if (!gate.acquire()) {
} catch { if (watching)
matched = undefined; // handle() renders the shared 400 response without reading a body 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,
headers,
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 ''.
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();
} }
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
// would have installed before body acquisition.
const injected = computeInjected(opts, { secure, headers });
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
const result = await handle(routes, opts, {
method: request.method,
url: path,
headers,
body,
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 ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
});
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and // 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 // so picks up the same authoritative security headers `injected` carries.
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
if ('preflight' in result) { 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 { channel } from '../channel';
import type { App } from '../app/types'; import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core'; 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 * 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; if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<SocketCtor>('ws');
return require('ws') as SocketCtor;
} }
/** /**
+9 -3
View File
@@ -1,5 +1,6 @@
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router'; import { matchPattern } from './router';
import type { WsRouteDef } from './types'; import type { WsRouteDef } from './types';
@@ -109,6 +110,11 @@ export async function runWsConnection(
): Promise<void> { ): Promise<void> {
const { closer } = trackConnection(socket, streams); const { closer } = trackConnection(socket, streams);
const name = route.def.pattern; 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; let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => { const onAbort = () => {
@@ -117,7 +123,7 @@ export async function runWsConnection(
}; };
socket.abort.addEventListener('abort', onAbort, { once: true }); socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name }); bus?.emit('stream:open', trace);
try { try {
const outbound = await route.def.open({ const outbound = await route.def.open({
@@ -129,9 +135,9 @@ export async function runWsConnection(
iterator = outbound[Symbol.asyncIterator](); iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator); await pumpOutbound(socket, iterator);
} catch (err) { } catch (err) {
bus?.emit('stream:error', { name, error: err }); bus?.emit('stream:error', { ...trace, error: err });
closeOnError(socket, err); closeOnError(socket, err);
} finally { } 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 type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types'; 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. */ /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null { function loadWss(): any | null {
try { try {
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket // `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). // 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 nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
return require('ws').WebSocketServer;
} catch { } catch {
return null; return null;
} }
+13 -5
View File
@@ -40,8 +40,10 @@ export {
Options, Options,
Html, Html,
} from './metadata'; } from './metadata';
export type { Transport, HttpMethod } from './metadata'; export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin } from './plugin'; export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals // Transformers & error signals
export { JsonTransformer } from './transformers'; export { JsonTransformer } from './transformers';
@@ -58,22 +60,28 @@ export {
// Bus & flow // Bus & flow
export { Bus } from './bus'; export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow'; export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators // Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec } from './params'; export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger';
// Streaming // Streaming
export { channel, isAsyncIterable } from './channel'; export { channel, isAsyncIterable } from './channel';
export type { Channel } from './channel'; export type { Channel } from './channel';
export { Rooms } from './rooms'; export { Rooms } from './rooms';
export { sseEncoder, ndjsonEncoder } from './encoders'; export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder } from './encoders'; export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation // HTTP, security & validation
export type { RequestLimits } from './http'; export type { RequestLimits } from './http';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart'; export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema'; 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 });
}
}
}
}
+154
View File
@@ -0,0 +1,154 @@
import type { EventPayload } from './bus';
/**
* The logging contract. Four levels, because four have callers: core diagnostics are all `warn`
* today, request logging adds `info` and `error`, and the graph diagnostics add `debug`. No
* `trace`, no `fatal`, no `silent` — a level nothing emits is a decision handed to the user for
* no reason.
*/
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
/** Structured context attached to a log record. Flattened into the JSON output alongside the message. */
export type LogFields = Record<string, unknown>;
/**
* What `createApp({ logger })` accepts, and what core writes every diagnostic through.
*
* Message first, fields second, so a call reads as a sentence and the structured part stays
* optional. Bridging a `pino`- or `winston`-style logger is a four-line adapter in either
* direction; core defines the shape it needs rather than adopting anyone's.
*/
export interface Logger {
debug(message: string, fields?: LogFields): void;
info(message: string, fields?: LogFields): void;
warn(message: string, fields?: LogFields): void;
error(message: string, fields?: LogFields): void;
}
/**
* Whether output should be human-readable rather than JSON.
*
* Decided once, when the logger is built, and never per call — the answer cannot change while the
* process runs, and asking on every record would put a syscall-shaped question on a path that is
* supposed to be cheap. `process` is absent on the edge, so the guard is not defensive padding:
* unattended is the correct default there, and JSON is the unattended format.
*/
function isInteractive(): boolean {
const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;
return Boolean(proc?.stdout?.isTTY);
}
const CONSOLE_METHOD: Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'> = {
debug: 'debug',
info: 'info',
warn: 'warn',
error: 'error',
};
function renderPretty(level: LogLevel, message: string, fields?: LogFields): string {
const pairs = fields
? Object.entries(fields)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
: [];
return `[green-tea] ${level.toUpperCase()} ${message}${pairs.length ? ' ' + pairs.join(' ') : ''}`;
}
function renderJson(level: LogLevel, message: string, fields?: LogFields): string {
// `name` rather than the `[green-tea]` prefix the messages used to carry inline: a log
// aggregator filters on a field, and cannot filter on a substring of prose.
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
}
/**
* Wraps a logger so a throwing one cannot go silent.
*
* `Bus.emit` isolates listener failures on purpose — an observer must never be able to break a
* request — but that guarantee has a cost when the observer is the logger itself: a user logger
* that throws would simply stop writing, with nothing to say so. Falling back to `console` keeps
* the Bus's promise without paying for it in silence.
*
* Exported because request logging is not the only thing that should survive a broken logger.
*/
export function withConsoleFallback(logger: Logger): Logger {
const guard =
(level: LogLevel) =>
(message: string, fields?: LogFields): void => {
try {
logger[level](message, fields);
} catch (error) {
console.error(
renderJson('error', 'the configured logger threw; falling back to console', {
level,
originalMessage: message,
error: error instanceof Error ? error.message : String(error),
...fields,
}),
);
}
};
return { debug: guard('debug'), info: guard('info'), warn: guard('warn'), error: guard('error') };
}
/**
* Subscribes request logging to the lifecycle stream: `info` per completed request, `error` per
* failed one. Returns an unsubscribe function, so it is as removable as it is composable — which
* is what "a composable step, not a global middleware" has to mean in practice.
*
* Reads the stream rather than being called from the request path, so there is exactly one account
* of what happened to a request. A second path would eventually disagree with the first.
*/
export function logRequests(bus: BusLike, logger: Logger): () => void {
const safe = withConsoleFallback(logger);
const offEnd = bus.on('request:end', (event) => {
safe.info(`${event.method ?? ''} ${event.route ?? event.name} ${event.status ?? ''}`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
status: event.status,
durationMs: event.durationMs,
});
});
const offFailed = bus.on('request:failed', (event) => {
safe.error(`${event.method ?? ''} ${event.route ?? event.name} failed`.trim(), {
requestId: event.requestId,
traceId: event.traceId,
route: event.route,
method: event.method,
error: event.error instanceof Error ? event.error.message : event.error,
});
});
return () => {
offEnd();
offFailed();
};
}
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
interface BusLike {
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
}
/**
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
*
* Writes through `console`, which is the whole reason core can have a logging contract without a
* logging dependency — `reflect-metadata` stays the only runtime dependency, and anything richer
* (transports, sampling, rotation) is a `Logger` a user passes in.
*/
export function createDefaultLogger(pretty: boolean = isInteractive()): Logger {
const write = (level: LogLevel, message: string, fields?: LogFields): void => {
console[CONSOLE_METHOD[level]](pretty ? renderPretty(level, message, fields) : renderJson(level, message, fields));
};
return {
debug: (message, fields) => write('debug', message, fields),
info: (message, fields) => write('info', message, fields),
warn: (message, fields) => write('warn', message, fields),
error: (message, fields) => write('error', message, fields),
};
}
+312 -60
View File
@@ -1,6 +1,8 @@
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import type { Logger } from '../logger';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter'; import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core'; import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -11,15 +13,71 @@ export interface Link {
close(): void; 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. */ /** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
type PendingEntry = { 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; resolve: (v: unknown) => void;
reject: (e: unknown) => void; reject: (e: unknown) => void;
timer: ReturnType<typeof setTimeout>; 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 * 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. * 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. */ /** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc( function sendRpc(
socket: WsSocket, socket: WsSocket | undefined,
pending: Map<string, PendingEntry>, pending: Map<string, PendingEntry>,
id: string, id: string,
kind: 'scope' | 'route', kind: 'scope' | 'route',
@@ -44,8 +102,9 @@ function sendRpc(
): Promise<unknown> { ): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting // 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) // 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. // before failing anyway — the caller pays for a verdict already known. This is also the
if (!socket.isOpen) { // 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}'`)); 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}`)); rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs); }, 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 })); 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. */ /** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
function settleRpcResponse( function settleRpcResponse(
pending: Map<string, PendingEntry>, pending: Map<string, PendingEntry>,
@@ -95,7 +135,10 @@ function settleRpcResponse(
if (frame.ok) { if (frame.ok) {
entry.resolve(frame.result); entry.resolve(frame.result);
} else { } 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)); 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 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 * 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 * 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. * 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 { interface Handshake {
url: string; url: string;
socket: WsSocket; socket: WsSocket;
pending: Map<string, PendingEntry>; pending: Map<string, PendingEntry>;
timeoutMs: number;
bus?: Bus; bus?: Bus;
resolve: (link: Link) => void; resolve: (session: Session) => void;
reject: (error: unknown) => void; reject: (error: unknown) => void;
onManifest: () => void; onManifest: (socket: WsSocket) => Session['heartbeat'];
onPong: () => void; 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 { function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
if (frame.v !== MESH_PROTOCOL_VERSION) { if (frame.v !== MESH_PROTOCOL_VERSION) {
hs.socket.close(); hs.socket.close();
hs.reject( hs.reject(
new Error( refused(
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, `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; return;
} }
hs.onManifest(); const heartbeat = hs.onManifest(hs.socket);
hs.bus?.emit('mesh:connect', { name: hs.url });
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs)); // `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> { async function readFrames(hs: Handshake): Promise<void> {
for await (const data of hs.socket.inbound) { for await (const data of hs.socket.inbound) {
let frame: Frame; let frame: Frame;
@@ -192,49 +238,61 @@ async function readFrames(hs: Handshake): Promise<void> {
} }
} }
/** /** Everything a link needs to open one session, shared by the first connect and every retry. */
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest interface SessionArgs {
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
*/
export function connectLink(args: {
url: string; url: string;
secret: string; secret: string;
timeoutMs?: number; timeoutMs: number;
heartbeatMs?: number; heartbeatMs: number;
pending: Map<string, PendingEntry>;
bus?: Bus; bus?: Bus;
Ctor?: SocketCtor; Ctor?: SocketCtor;
}): Promise<Link> { onEnd: () => void;
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;
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(() => { const connectTimer = setTimeout(() => {
socket.close(); socket.close();
reject(new Error(`mesh connect timeout: ${args.url}`)); reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs); }, args.timeoutMs);
const hs: Handshake = { const hs: Handshake = {
url: args.url, url: args.url,
socket, socket,
pending, pending: args.pending,
timeoutMs,
bus: args.bus, bus: args.bus,
resolve, resolve,
reject, reject,
onManifest: () => { onManifest: (established) => {
manifest = true; handshook = true;
clearTimeout(connectTimer); clearTimeout(connectTimer);
// started only once authenticated: an unauthenticated peer should not be pinging // 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(), onPong: () => heartbeat?.markAlive(),
}; };
opened.then( 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), (error) => reject(error),
); );
@@ -245,9 +303,16 @@ export function connectLink(args: {
() => { () => {
clearTimeout(connectTimer); clearTimeout(connectTimer);
heartbeat?.stop(); heartbeat?.stop();
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`); if (!handshook) {
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); // 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 }, { 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 * 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 * 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 * green-tea versions, not an internal detail. Peers refuse each other on mismatch rather
* refuse each other on mismatch rather than misparsing downstream. * 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; 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 { export interface RequestEnvelope {
method: string; method: string;
params: Record<string, string>; params: Record<string, string>;
query: Record<string, string>; query: Record<string, string>;
body: unknown; body: unknown;
headers: Record<string, string | string[] | undefined>; 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. */ /** 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. */ /** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string { export function encode(frame: Frame): string {
return JSON.stringify(frame); return JSON.stringify(frame);
+14 -2
View File
@@ -14,14 +14,26 @@ export interface RemoteRoute {
handler: (req: RequestEnvelope) => Promise<ResponseShape>; 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 { export function envelopeFrom(ctx: any): RequestEnvelope {
const req = ctx?.req;
const correlation = { requestId: req?.requestId, traceId: req?.traceId };
return { return {
method: ctx?.req?.method ?? ctx?.method ?? 'GET', method: req?.method ?? ctx?.method ?? 'GET',
params: ctx?.params ?? {}, params: ctx?.params ?? {},
query: ctx?.query ?? {}, query: ctx?.query ?? {},
body: ctx?.body, body: ctx?.body,
headers: ctx?.headers ?? {}, 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 { import {
encode, encode,
decode, decode,
untransportable,
MESH_PROTOCOL_VERSION, MESH_PROTOCOL_VERSION,
type Manifest, type Manifest,
type RequestEnvelope, type RequestEnvelope,
@@ -19,6 +20,28 @@ import {
/** WebSocket path where a teapot exposes its mesh control channel. */ /** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control'; 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. */ /** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
export function buildManifest(args: { export function buildManifest(args: {
providers: string[]; // exported provider tokens (app-scope) providers: string[]; // exported provider tokens (app-scope)
@@ -133,6 +156,19 @@ async function handleRpc(
try { try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); 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 })); socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) { } catch (err) {
@@ -151,19 +187,34 @@ async function serveFrames(
exportedRoutes: Set<string>, exportedRoutes: Set<string>,
): Promise<void> { ): Promise<void> {
let authed = false; 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 { try {
for await (const data of socket.inbound) { 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; let frame: Frame;
try { try {
frame = decode(String(data)); frame = decode(raw);
} catch { } catch {
continue; // undecodable frames are ignored, as before continue; // undecodable frames are ignored, as before
} }
if (!authed) { if (!authed) {
authed = handleHandshake(socket, frame, deps); authed = handleHandshake(socket, frame, deps);
if (authed) clearTimeout(handshakeTimer);
continue; continue;
} }
@@ -183,6 +234,7 @@ async function serveFrames(
} catch { } catch {
/* socket failed; the disconnect emit below is the same signal a clean close gives */ /* socket failed; the disconnect emit below is the same signal a clean close gives */
} finally { } finally {
clearTimeout(handshakeTimer);
deps.bus?.emit('mesh:disconnect', { name: 'teapot' }); deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
} }
} }
+39 -30
View File
@@ -100,48 +100,57 @@ export function Route(prefix: string): ClassDecorator {
}; };
} }
function routeDecorator(method: HttpMethod, transport: Transport) { /**
return ( * The shape every route decorator shares: a path, optional per-route overrides, and the
path: string, * `MethodDecorator` that records them against the controller.
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number }, *
): MethodDecorator => * Named rather than inferred because JSR rejects an inferred type on a public symbol — an inferred
(target, propertyKey) => { * one forces every consumer's type checker to re-derive it from the implementation instead of
const ctor = target.constructor; * reading it from the declaration. It also gives callers a name for the shape.
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; */
routes.push({ export type RouteDecorator = (
method, path: string,
path, opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
handlerName: String(propertyKey), ) => MethodDecorator;
transport,
export: opts?.export ?? false, function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
duplicates: opts?.duplicates, return (path, opts) => (target, propertyKey) => {
maxBodyBytes: opts?.maxBodyBytes, const ctor = target.constructor;
maxParts: opts?.maxParts, const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
}); routes.push({
Reflect.defineMetadata(K.routes, routes, ctor); method,
}; path,
handlerName: String(propertyKey),
transport,
export: opts?.export ?? false,
duplicates: opts?.duplicates,
maxBodyBytes: opts?.maxBodyBytes,
maxParts: opts?.maxParts,
});
Reflect.defineMetadata(K.routes, routes, ctor);
};
} }
/** Declares a buffered `GET` route. */ /** Declares a buffered `GET` route. */
export const Get = routeDecorator('GET', 'buffer'); export const Get: RouteDecorator = routeDecorator('GET', 'buffer');
/** Declares a buffered `HEAD` route. */ /** Declares a buffered `HEAD` route. */
export const Head = routeDecorator('HEAD', 'buffer'); export const Head: RouteDecorator = routeDecorator('HEAD', 'buffer');
/** Declares a buffered `POST` route. */ /** Declares a buffered `POST` route. */
export const Post = routeDecorator('POST', 'buffer'); export const Post: RouteDecorator = routeDecorator('POST', 'buffer');
/** Declares a buffered `PUT` route. */ /** Declares a buffered `PUT` route. */
export const Put = routeDecorator('PUT', 'buffer'); export const Put: RouteDecorator = routeDecorator('PUT', 'buffer');
/** Declares a buffered `PATCH` route. */ /** Declares a buffered `PATCH` route. */
export const Patch = routeDecorator('PATCH', 'buffer'); export const Patch: RouteDecorator = routeDecorator('PATCH', 'buffer');
/** Declares a buffered `DELETE` route. */ /** Declares a buffered `DELETE` route. */
export const Delete = routeDecorator('DELETE', 'buffer'); export const Delete: RouteDecorator = routeDecorator('DELETE', 'buffer');
/** Declares a buffered `OPTIONS` route. */ /** Declares a buffered `OPTIONS` route. */
export const Options = routeDecorator('OPTIONS', 'buffer'); export const Options: RouteDecorator = routeDecorator('OPTIONS', 'buffer');
/** Declares a `GET` route streamed as Server-Sent Events. */ /** Declares a `GET` route streamed as Server-Sent Events. */
export const Sse = routeDecorator('GET', 'sse'); export const Sse: RouteDecorator = routeDecorator('GET', 'sse');
/** Declares a `GET` route whose transport is content-negotiated at request time. */ /** Declares a `GET` route whose transport is content-negotiated at request time. */
export const Stream = routeDecorator('GET', 'negotiate'); export const Stream: RouteDecorator = routeDecorator('GET', 'negotiate');
/** Declares a `GET` route upgraded to a WebSocket. */ /** Declares a `GET` route upgraded to a WebSocket. */
export const Ws = routeDecorator('GET', 'ws'); export const Ws: RouteDecorator = routeDecorator('GET', 'ws');
/** Attaches a response transformer to a handler method. */ /** Attaches a response transformer to a handler method. */
export function Transformer(fn: TransformerFn): MethodDecorator { export function Transformer(fn: TransformerFn): MethodDecorator {
+2 -2
View File
@@ -1,6 +1,7 @@
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. // src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
import { Readable } from 'stream'; import { Readable } from 'stream';
import { HttpError } from './signals'; import { HttpError } from './signals';
import { nodeRequire } from './node-require';
/** A single uploaded file part decoded from a multipart body. */ /** A single uploaded file part decoded from a multipart body. */
export interface UploadedFile { export interface UploadedFile {
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
try { try {
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is // `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. // 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 nodeRequire('busboy');
return require('busboy');
} catch { } catch {
return null; 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);
}
+30 -19
View File
@@ -32,34 +32,45 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
Reflect.defineMetadata(ARGS, map, ctor); Reflect.defineMetadata(ARGS, map, ctor);
} }
function envelope(source: ArgSource) { /**
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator => * The shape every argument decorator shares: an optional key, key list or schema, an optional
(target, methodKey, index) => { * second schema, and the `ParameterDecorator` that records the resulting spec.
const spec: ArgSpec = { index, source }; *
if (Array.isArray(arg)) spec.keys = arg; * Named for the same reason as `RouteDecorator` in `./metadata` — JSR rejects an inferred type on a
else if (typeof arg === 'string') spec.key = arg; * public symbol, because consumers would have to re-derive it from the implementation on every check.
else if (isStandardSchema(arg)) spec.schema = arg; */
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`); export type ArgDecorator = (
arg?: string | string[] | StandardSchemaV1,
schema?: StandardSchemaV1,
) => ParameterDecorator;
if (schema !== undefined) { function envelope(source: ArgSource): ArgDecorator {
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`); return (arg, schema) => (target, methodKey, index) => {
spec.schema = schema; const spec: ArgSpec = { index, source };
} if (Array.isArray(arg)) spec.keys = arg;
else if (typeof arg === 'string') spec.key = arg;
else if (isStandardSchema(arg)) spec.schema = arg;
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
record(target, methodKey, spec); if (schema !== undefined) {
}; if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
spec.schema = schema;
}
record(target, methodKey, spec);
};
} }
/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */ /** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */
export const param = envelope('params'); export const param: ArgDecorator = envelope('params');
/** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */ /** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */
export const query = envelope('query'); export const query: ArgDecorator = envelope('query');
/** Inject the request body; pass a schema to validate it. */ /** Inject the request body; pass a schema to validate it. */
export const body = envelope('body'); export const body: ArgDecorator = envelope('body');
/** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */ /** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */
export const headers = envelope('headers'); export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */ /** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
export const header = envelope('headers'); export const header: ArgDecorator = envelope('headers');
/** Inject a value produced upstream by a step or provider, addressed by key. */ /** Inject a value produced upstream by a step or provider, addressed by key. */
export function needs(key: string): ParameterDecorator { export function needs(key: string): ParameterDecorator {
+79 -14
View File
@@ -1,8 +1,9 @@
import { Bus } from './bus'; import { Bus, type Correlation } from './bus';
import { renderError, type ErrorRenderer } from './transformers'; import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel'; import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata'; import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals'; 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. */ /** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep { export interface PipelineStep {
@@ -45,15 +46,56 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every * `request:step:enter`/`leave` on the bus. The single place steps are executed — every
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction. * transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
*/ */
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> { export async function runSteps(
steps: PipelineStep[],
seed: Record<string, unknown>,
bus: Bus,
correlation: Correlation = {},
): Promise<any> {
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
const context: any = seed; const context: any = seed;
// One timestamp per boundary, not one pair per step: a step's end is the next one's start, so
// N steps need N+1 readings rather than 2N. Measured at 25.2ns vs 45.3ns per step, against a
// ~10.19us request — 0.25%, below the 0.3% run-to-run CV of the project's own benchmark, which
// is why this is always on instead of hiding behind a flag nobody could tune with evidence.
// Hoisted out of the loop: listeners are registered at boot, so re-deciding this per step buys
// nothing. When nothing is listening — the common case — the whole block below costs a branch
// instead of building four payloads and reading three clocks for an audience of nobody.
const watchingEnter = bus.hasListeners('request:step:enter');
const watchingLeave = bus.hasListeners('request:step:leave');
const watchingError = bus.hasListeners('request:step:error');
const timing = watchingLeave || watchingError;
let mark = timing ? performance.now() : 0;
for (const step of steps) { for (const step of steps) {
bus.emit('request:step:enter', { name: step.name, scope: step.origin }); if (watchingEnter) bus.emit('request:step:enter', { name: step.name, scope: step.origin, ...correlation });
const output = await step.run(context);
Object.assign(context, output); try {
bus.emit('request:step:leave', { name: step.name, scope: step.origin }); const output = await step.run(context);
Object.assign(context, output);
} catch (error) {
// Emitted here, where the step that failed is still known. The outer catch in runPipeline
// only sees "something in the pipeline threw" and used to report `name: 'pipeline'`, which
// threw away the one fact the event exists to carry. Rethrown unchanged — this observes.
if (watchingError) {
bus.emit('request:step:error', {
name: step.name,
scope: step.origin,
error,
durationMs: performance.now() - mark,
...correlation,
});
}
throw error;
}
if (timing) {
const now = performance.now();
if (watchingLeave)
bus.emit('request:step:leave', { name: step.name, scope: step.origin, durationMs: now - mark, ...correlation });
mark = now;
}
} }
return context; return context;
@@ -72,13 +114,15 @@ export async function runPipeline(args: {
bus: Bus; bus: Bus;
transport: Transport; transport: Transport;
onError?: ErrorRenderer; onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation;
}): Promise<PipelineResult> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError } = args; const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed }; let context: any = { ...seed };
try { try {
context = await runSteps(steps, context, bus); context = await runSteps(steps, context, bus, correlation);
const result = await handler(context); const result = await handler(context);
const streaming = isAsyncIterable(result); const streaming = isAsyncIterable(result);
const contract = TRANSPORT_RETURN[transport]; const contract = TRANSPORT_RETURN[transport];
@@ -95,12 +139,33 @@ export async function runPipeline(args: {
const transformed = transformer(result); const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) { } catch (error) {
bus.emit('request:step:error', { name: 'pipeline', error });
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> }; const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError( let status: number | undefined;
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, try {
onError, 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 { Bus } from './bus';
import type { TeardownFn } from './lifecycle';
/** A step or provider a plugin contributes to the graph. */ /** A step or provider a plugin contributes to the graph. */
export interface ScopeNode { export interface ScopeNode {
@@ -13,18 +14,45 @@ export interface ScopeNode {
export interface ScopeApi { export interface ScopeApi {
add(node: ScopeNode): void; 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 { export interface PluginApi {
bus: { on: Bus['on'] }; bus: { on: Bus['on'] };
scope: ScopeApi; 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. */ /** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void; export type Plugin = (api: PluginApi) => void;
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */ /** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void { export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural. // Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope }; //
// "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); plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' }); 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 // src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */ /** TLS material for an HTTPS server. */
export interface TlsOptions { export interface TlsOptions {
key: Buffer | string; key: Buffer | string;
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
return headers; 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 (spec === '*') return true;
if (typeof spec === 'function') return spec(origin);
if (Array.isArray(spec)) return spec.includes(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. */ /** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors( export function resolveCors(
opts: CorsOptions, opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> }, req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers { ): Headers {
const headers: Headers = {}; const headers: Headers = {};
const rawOrigin = req.headers['origin']; const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin; 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. // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) { if (opts.credentials) {
@@ -112,8 +128,13 @@ export function resolveCors(
export function corsPreflightHeaders( export function corsPreflightHeaders(
opts: CorsOptions, opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> }, req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): 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 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( 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 { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { 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}. */ /** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { export function renderError(
return onError?.(error, req) ?? errorToResponse(error); 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 { TransformerFn } from './metadata';
import type { HtmlMeta } 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. */ /** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string { 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. /** 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 * 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 { function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const nodePath = require('node:path') as typeof import('node:path'); const fs = nodeRequire<typeof import('node:fs')>('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const base = views ?? process.cwd(); const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path); 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'); let nodePath: typeof import('node:path');
try { try {
// eslint-disable-next-line @typescript-eslint/no-require-imports fs = nodeRequire('node:fs');
fs = require('node:fs'); nodePath = nodeRequire('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
} catch { } catch {
throw new Error( throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
+71 -2
View File
@@ -439,6 +439,28 @@ describe('devGraph endpoint', () => {
}); });
describe('graceful shutdown', () => { describe('graceful shutdown', () => {
// A module whose only route never responds, so shutdown always has something in flight to give
// up on — the deadline is the only thing that can end close().
const hangModule = () => {
@Route('/')
class Ctl {
@Get('/hang') hang() {
return new Promise(() => {});
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
return M;
};
const listenHanging = async (app: ReturnType<typeof createApp>): Promise<number> => {
const server = await app.listen(0);
const port = (server.address() as any).port;
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50)); // let the request reach the handler
return port;
};
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
@Route('/') @Route('/')
class Ctl { class Ctl {
@@ -464,6 +486,49 @@ describe('graceful shutdown', () => {
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow(); await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
reader.cancel().catch(() => {}); reader.cancel().catch(() => {});
}); });
it('close({ timeoutMs }) forces shutdown when a handler never responds', async () => {
@Route('/')
class Ctl {
@Get('/hang') hang() {
return new Promise(() => {}); // never resolves — simulates a stuck handler
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50));
const start = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - start).toBeLessThan(600);
});
// The app-level default exists for the case where close() is reached from a signal handler or a
// test helper nobody local owns, so it has to work with close() called bare.
it('createApp({ shutdownTimeoutMs }) applies when close() is called with no options', async () => {
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 300 });
await listenHanging(app);
const start = Date.now();
await app.close();
expect(Date.now() - start).toBeLessThan(600);
});
// The interesting half of the precedence rule: an app-level default long enough to fail this
// test if it won, so the assertion can only pass if the per-call value took priority.
it('close({ timeoutMs }) overrides the app-level default', async () => {
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 30_000 });
await listenHanging(app);
const start = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - start).toBeLessThan(600);
});
}); });
describe('overrides', () => { describe('overrides', () => {
@@ -538,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 }); expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close(); 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' }) @Provider({ provides: 'rooms' })
class MyRooms { class MyRooms {
provide() { provide() {
@@ -553,7 +622,7 @@ describe('rooms auto-provide', () => {
} }
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {} 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) 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();
}
});
+71
View File
@@ -0,0 +1,71 @@
// Real Bun integration test for the bounded close() serveBun returns. app.close() cannot do this
// job on Bun — it returns at its `if (!server)` guard, because a Bun app is served through
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
// handle. See issue #15.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Get, Module } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
class Ctl {
@Get('/hang')
hang() {
return new Promise(() => {}); // never resolves — a stuck handler
}
@Get('/slow')
async slow() {
await Bun.sleep(200); // finite, so draining has something real to wait out
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
await Bun.sleep(50); // let the request actually reach the handler
const start = Date.now();
await server.close({ timeoutMs: 300 });
const elapsed = Date.now() - start;
// The assertion that matters is the upper bound: without the deadline this never returns.
expect(elapsed).toBeLessThan(2000);
expect(elapsed).toBeGreaterThanOrEqual(250);
});
test('serveBun close() drains an in-flight request rather than cutting it', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
await server.close({ timeoutMs: 5000 });
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); 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 = { const info = {
get remoteAddr() { get remoteAddr() {
if (upgraded) throw new TypeError('Request closed'); 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();
}
});
+86
View File
@@ -0,0 +1,86 @@
// Real Deno integration test for the bounded close() serveDeno returns. app.close() cannot do this
// job on Deno — it returns at its `if (!server)` guard, because a Deno app is served through
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
// handle. See issue #15.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { createApp, Route, Get, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
class Ctl {
@Get('/hang')
hang() {
return new Promise(() => {}); // never resolves — a stuck handler
}
@Get('/slow')
async slow() {
await new Promise((r) => setTimeout(r, 200)); // finite, so draining has something real to wait out
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const portOf = (server: { addr?: { port: number } }): number => server.addr!.port;
// On Deno the deadline bounds the wait, not the connections — see the comment on serveDeno's
// force callback. This test asserts exactly that: close() returns on time, and does so without
// the uncaught BadResource that aborting a draining server produces. The test runner fails on
// that error even when the assertions pass, so a green run here is the real assertion.
Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => {
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
const start = Date.now();
await server.close({ timeoutMs: 300 });
const elapsed = Date.now() - start;
// The assertion that matters is the upper bound: without the deadline this never returns.
if (elapsed >= 2000) throw new Error(`close() took ${elapsed}ms — the deadline did not fire`);
if (elapsed < 250) throw new Error(`close() returned in ${elapsed}ms — it did not wait the deadline`);
});
Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => {
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json());
await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close
await server.close({ timeoutMs: 5000 });
const body = await inFlight;
if (body.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(body)}`);
});
Deno.test('a caller-supplied signal still aborts the server', async () => {
const ac = new AbortController();
const server = serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} });
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(); 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 { 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 => const node = (name: string, needs: string[], provides: string[]): GraphNode =>
({ name, needs, provides, origin: 'test' }); ({ 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', () => { describe('nearest', () => {
it('suggests a close candidate (edit distance <= 2)', () => { it('suggests a close candidate (edit distance <= 2)', () => {
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user'); expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
+313 -3
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'; import { matchRoute, parseQuery, createHttpServer } from '../src/http';
const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
@@ -112,18 +116,216 @@ describe('request hardening', () => {
const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) }); const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) });
expect(res.status).toBe(413); expect(res.status).toBe(413);
expect(ran).toBe(false); expect(ran).toBe(false);
// Load-bearing, not cosmetic: without it the rest of the upload keeps arriving on a
// kept-alive socket after the response. Node-only — `Connection` is a forbidden response
// header on the fetch side, which is why the adapter attaches it rather than the shared core.
expect(res.headers.get('connection')).toBe('close');
server.close(); server.close();
}); });
it('sets the configured server timeouts', async () => { it('sets the configured server timeouts and connection limit', async () => {
const server = createHttpServer([], [], undefined, undefined, const server = createHttpServer([], [], undefined, undefined,
{ limits: { requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } }); { limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
expect(server.maxConnections).toBe(2468);
expect(server.requestTimeout).toBe(12345); expect(server.requestTimeout).toBe(12345);
expect(server.headersTimeout).toBe(6789); expect(server.headersTimeout).toBe(6789);
expect(server.keepAliveTimeout).toBe(4321); expect(server.keepAliveTimeout).toBe(4321);
server.close(); server.close();
}); });
it('caps concurrent connections by default', () => {
const server = createHttpServer([]);
expect(server.maxConnections).toBe(1000);
server.close();
});
it.each([0, -1])('treats maxConnections=%i as unlimited', (maxConnections) => {
const server = createHttpServer([], [], undefined, undefined, {
limits: { maxConnections },
});
expect(server.maxConnections).toBeUndefined();
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 () => { 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)); } } async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
const server = createHttpServer( const server = createHttpServer(
@@ -151,4 +353,112 @@ describe('request hardening', () => {
expect(await res.json()).toEqual({ a: '1', b: 'two' }); expect(await res.json()).toEqual({ a: '1', b: 'two' });
server.close(); 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);
});
});
+253
View File
@@ -0,0 +1,253 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { createApp, createDefaultLogger, logRequests, Route, Get, Step, Module, Provider, needs } from '../src/index';
import type { Logger, LogFields } from '../src/index';
/** Captures every call so a test can assert on what core wrote rather than on console output. */
function recordingLogger(): Logger & { records: Array<{ level: string; message: string; fields?: LogFields }> } {
const records: Array<{ level: string; message: string; fields?: LogFields }> = [];
const at =
(level: string) =>
(message: string, fields?: LogFields): void => {
records.push({ level, message, fields });
};
return { records, debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
}
afterEach(() => {
vi.restoreAllMocks();
});
describe('default logger', () => {
it('writes one JSON object per record when not on a TTY', () => {
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
createDefaultLogger(false).warn('something happened', { route: '/x', count: 2 });
expect(spy).toHaveBeenCalledTimes(1);
const written = JSON.parse(spy.mock.calls[0][0] as string);
expect(written).toMatchObject({ level: 'warn', name: 'green-tea', msg: 'something happened', route: '/x', count: 2 });
// A log aggregator filters on a field; it cannot filter on a substring of prose.
expect(written.msg).not.toContain('[green-tea]');
expect(typeof written.time).toBe('string');
});
it('writes a readable line instead when interactive', () => {
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
createDefaultLogger(true).warn('something happened', { route: '/x' });
const written = spy.mock.calls[0][0] as string;
expect(written).toBe('[green-tea] WARN something happened route=/x');
});
it('routes each level to the matching console method', () => {
const spies = {
debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
info: vi.spyOn(console, 'info').mockImplementation(() => {}),
warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
error: vi.spyOn(console, 'error').mockImplementation(() => {}),
};
const logger = createDefaultLogger(false);
logger.debug('d');
logger.info('i');
logger.warn('w');
logger.error('e');
for (const spy of Object.values(spies)) expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('createApp({ logger })', () => {
@Route('/')
class Ctl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
it('sends framework diagnostics to the supplied logger, not to console', async () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
// close({ timeoutMs }) on an app that never listen()ed is one of the diagnostics core emits.
await app.close({ timeoutMs: 100 });
expect(logger.records).toHaveLength(1);
expect(logger.records[0].level).toBe('warn');
expect(logger.records[0].message).toContain('has no listen()ed server');
// The point of the contract: nothing reached console behind the logger's back.
expect(consoleWarn).not.toHaveBeenCalled();
});
it('exposes the logger on the app so adapters and plugins share it', () => {
const logger = recordingLogger();
expect(createApp({ modules: [M], logger }).logger).toBe(logger);
});
it('warns about a deep dependency chain through the logger, with structured fields', () => {
const logger = recordingLogger();
@Step({ provides: 's0' })
class S0 {
run() {
return { s0: 0 };
}
}
@Step({ provides: 's1', needs: ['s0'] })
class S1 {
run() {
return { s1: 1 };
}
}
@Route('/deep')
class DeepCtl {
@Get('/go')
go(@needs('s1') s: unknown) {
return { s };
}
}
@Module({ mountpoint: '/', steps: [S0, S1], controllers: [DeepCtl] })
class DeepModule {}
createApp({ modules: [DeepModule], logger, warnGraphDepth: 1 });
const warned = logger.records.find((r) => r.message.includes('unusually deep'));
expect(warned).toBeDefined();
// Structured, so a dashboard can group by route instead of parsing the sentence.
expect(warned!.fields).toMatchObject({ route: '/deep/go', method: 'GET', depth: 2, threshold: 1 });
});
});
describe('request logging', () => {
@Route('/api')
class Ctl {
@Get('/ok')
ok() {
return { ok: true };
}
@Get('/boom')
boom(): never {
throw new Error('handler exploded');
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
it('is off unless asked for', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/api/ok'));
// A framework that writes to stdout uninvited is one you must configure before using.
expect(logger.records).toHaveLength(0);
});
it('logs one info per completed request, with the pattern and a duration', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger, logRequests: true });
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
const [record] = logger.records;
expect(record.level).toBe('info');
expect(record.fields).toMatchObject({ route: '/api/ok', method: 'GET', status: 200 });
expect(typeof record.fields!.requestId).toBe('string');
expect(record.fields!.durationMs).toBeGreaterThanOrEqual(0);
});
it('logs an error for a failed request, correlated with it', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger, logRequests: true });
await app.fetch(new Request('http://x/api/boom'));
const failed = logger.records.find((r) => r.level === 'error');
expect(failed).toBeDefined();
expect(failed!.fields).toMatchObject({ route: '/api/boom', error: 'handler exploded' });
// Same request, so the failure and the completion carry one identity between them.
const completed = logger.records.find((r) => r.level === 'info');
expect(completed!.fields!.requestId).toBe(failed!.fields!.requestId);
});
it('unsubscribes, so it is removable and not just optional', async () => {
const logger = recordingLogger();
const app = createApp({ modules: [M], logger });
const stop = logRequests(app.bus, logger);
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
stop();
await app.fetch(new Request('http://x/api/ok'));
expect(logger.records).toHaveLength(1);
});
it('keeps writing, and keeps serving, when the logger throws on every call', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
const exploding: Logger = {
debug: () => {
throw new Error('logger is broken');
},
info: () => {
throw new Error('logger is broken');
},
warn: () => {
throw new Error('logger is broken');
},
error: () => {
throw new Error('logger is broken');
},
};
const app = createApp({ modules: [M], logger: exploding, logRequests: true });
const res = await app.fetch(new Request('http://x/api/ok'));
// The request is unharmed: Bus.emit isolates listener failures by design.
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
// And the failure is not silent, which is what the wrapper buys on top of that guarantee.
expect(consoleError).toHaveBeenCalled();
const written = JSON.parse(consoleError.mock.calls[0][0] as string);
expect(written.msg).toContain('the configured logger threw');
expect(written.error).toBe('logger is broken');
});
});
describe('logger as a dependency', () => {
it('is injectable with @needs("logger") and is the same instance', async () => {
const logger = recordingLogger();
let seen: unknown;
@Provider({ provides: 'noop' })
class Noop {
provide() {
return { noop: 1 };
}
}
@Route('/')
class Ctl {
@Get('/log')
log(@needs('logger') injected: Logger) {
seen = injected;
injected.info('from a handler', { where: 'handler' });
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Noop], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/log'));
// One object, two access paths — not a second logger wired into the graph.
expect(seen).toBe(logger);
expect(logger.records).toContainEqual({ level: 'info', message: 'from a handler', fields: { where: 'handler' } });
});
});
+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);
});
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more