79 Commits
Author SHA1 Message Date
chrnx a16be6a832 Merge pull request 'chore(release): cut 26.9.0-beta.2' (#99) from chore/cut-26.9.0-beta.2 into develop
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 32s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (edge) (push) Successful in 14s
Release → npmjs / publish-prod (push) Has been skipped
Stage → Verdaccio / publish-stg (push) Successful in 27s
CI / dco (pull_request) Successful in 5s
2026-09-23 01:50:39 +00:00
chrnx b0a9f3bfc9 chore(release): cut 26.9.0-beta.2
CI / build (pull_request) Successful in 31s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 7s
CI / runtimes (deno) (pull_request) Successful in 20s
Dated 2026-09-22, the day the tag goes up, rather than the day the version was
decided — package.json has said 26.9.0-beta.2 since the staging bump on the
17th, and that is the difference the heading records. A version number is a
plan; a changelog heading is a receipt.

Last commit before the tag, which is the order AGENTS.md asks for and the one
the beta.1 slip taught: everything merged, the release gate measured, the
suites green on all four runtimes, and only then the date. Held here rather
than written with the bump, so nothing accumulated underneath a heading that
claimed to have shipped it.

The section covers what landed since beta.1: the plugin contract, app.boot(),
async serveDeno/serveBun, errors recognised by brand, and the mesh moving to
steps-and-routes-only exports. `release.yml` reads this section by version to
build the GitHub release notes, and does so after npm and JSR have published,
so the heading has to exist before the tag rather than after it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:41:19 -05:00
chrnx 9a8677d5c2 fix(bench): date the run in project time, and let the harness typecheck again
Two things the release run surfaced, neither of them visible from CI.

`npm run typecheck:bench` has been failing since serveDeno and serveBun became
async: the bench servers gained a top-level await, which `module: commonjs`
rejects outright, and bench/tsconfig.json inherited commonjs from the root
config it extends. The servers are ES modules run by tsx, Deno and Bun and
never by the CommonJS build, so the config was describing the wrong thing even
before the await arrived. CI runs `typecheck`, not `typecheck:bench`, which is
why a break in the harness waited for someone to run it by hand.

The date came from the runner's clock through toISOString, which is UTC. The
table was measured on the evening of the 22nd over ssh against a box keeping
UTC and dated itself the 23rd, a day ahead of the commit and of the changelog
entry it sits beside. It now reads project time.

tsx transpiles with this tsconfig too, so the module change was verified by
running the smoke pass again on that box: all six frameworks, the secure run
and all three runtimes still boot, and the regenerated header reads 2026-09-22.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:37:45 -05:00
chrnx 8c95ae8bfb docs(bench): regenerate the cross-framework tables on a box that was not busy
Measured on an otherwise idle Ryzen 3700X over ssh, with the same Node, Deno
and Bun versions the laptop runs, after two attempts here were thrown away.
The absolute numbers drop to roughly a third — a 2019 desktop part against an
M4 Max — and that is the trade: a slower box whose numbers mean something
beats a faster one whose numbers track what else was on screen.

The shape reproduced across both machines, which is the result worth having.
green-tea is behind Fastify on hello, param and pipeline, ahead of it on
validate, and ~2.8x ahead of Express, on the M4 and on the Ryzen alike. The
size of the gap did not reproduce (2-8% there, 7-15% here), so the README now
says the direction and points at the table for the number, rather than
quoting a percentage that is really a fact about somebody's hardware.

CV lands between 0.1% and 1.3% across every row, against 4-6% on the
contended runs.

Fixes a sentence added an hour ago claiming the ordering inside the fast group
moves between runs by more than the gap between its members. It does not — it
held on both boxes — and the claim happened to be the one that flattered us.
Cross-framework tables and the runtime table are regenerated; the hand-written
section below the marker, including the release gate, is untouched.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 20:20:57 -05:00
chrnx daf0fed8ab docs(agents): delete a branch when its work lands, on both sides
The cleanup that prompted this removed 36 branches from Gitea and 29 locally,
all but one already in develop and some of them three months old. Nothing had
gone wrong — each was simply merged and left, and the deletes were never part
of anyone's definition of done.

The cost lands on whoever cuts the next release, who cannot tell a branch
holding unmerged work from one that shipped in July without checking each in
turn. Writing the rule here rather than leaving it to habit is the point: the
humans and the agents working in this repository read the same file, so the
same definition of done applies to both.

CLAUDE.md is not touched on purpose — it points here precisely so the two
cannot drift.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 14:15:54 -05:00
chrnx c5a8361c14 docs(bench): record the 26.9.0-beta.2 release gate, and drop a claim it never supported
The breaking changes in this release — `Plugin` as `{ name, mount }`, async
`serveDeno`/`serveBun`, a teapot that cannot export a provider, an `HttpError`
recognised by brand — are boot-time and error-path work, so the question was
whether any of it reached the per-request path. Ten cases against
`v26.9.0-beta.1`, both trees on one box in one sitting with the order
alternating: nine overlap and say nothing, which is the answer.

The tenth is the part worth keeping. `param, 50 routes` came out +4.3% with
separated ranges, in our favour, and had no mechanism — the matcher work that
could produce it would have to show at 200 routes, where the same run said
+0.1%. Seven rounds put it at +0.5% and overlapping. It was chance, and it is
recorded as chance, because a flagged row means measure again in either
direction.

The README has claimed since 7 July that green-tea beat every other framework
in 3 of 4 scenarios. The table it links to stopped saying that at some point
over the following two months — a ranking written into prose once is a claim
nobody re-measures, and this one outlived the NestJS rows, the parity controls
and the runtime-neutral boundary the file itself documents the cost of. It is
replaced by the shape of the result, which is stable, and a pointer to the
table for the numbers, which are not.

The cross-framework tables are deliberately left at their 2026-09-02 date.
Two attempts to regenerate them produced runs where a framework's delta
tracked its position in the run order and a browser held ~60% of the machine;
publishing those would have read as green-tea overtaking Fastify, which is the
most flattering available reading of a broken measurement. Absolute numbers
need a quiet box.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-22 14:14:02 -05:00
chrnx a57223cef9 Merge pull request 'feat(runtime)!: serveDeno and serveBun boot before they bind' (#98) from feature/serve-adapters-boot into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (deno) (push) Successful in 19s
2026-09-20 16:55:47 +00:00
chrnx 9634ec73e8 feat(runtime)!: serveDeno and serveBun boot before they bind
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / dco (pull_request) Successful in 6s
Both were synchronous and left the boot to the first request, with the fix
documented as something the caller should remember: `await app.boot()` before
`Deno.serve` / `Bun.serve`. That made the correct use of a core helper depend
on reading a README, in a framework whose whole argument is that order should
not be something you have to get right.

The failure it leaves is the bad kind. `app.fetch` boots lazily and the boot
memo keeps the *rejection*, so a missing signing key does not fail the deploy:
the port binds, every request is answered 500 by the runtime, and none of them
reach `onError`. Anything that health-checks by asking whether the process is
listening sees a healthy server.

`listen()` has always awaited `bootApp()` before binding its socket, with a
comment saying it exists so Node and Deno/Bun serve an identical graph. They
did not. Now the three helpers agree, and the two adapters return promises.

`edgeHandler` is deliberately unchanged: on workerd there is no startup outside
a request, so there is no earlier moment to move the failure to.

Both new tests were confirmed to fail with the gate commented out — without it
`serveBun` resolves instead of rejecting, and serveDeno binds a port that 500s.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 12:38:50 -05:00
chrnx cbeab73626 Merge pull request 'chore(release): 26.9.0-beta.2 to staging' (#97) from release/26.9.0-beta.2 into develop
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 13s
Promote → GitHub / push-github (push) Successful in 7s
CI / dco (push) Has been skipped
2026-09-18 03:53:29 +00:00
chrnx 58ba18f9f8 chore: ignore per-developer agent directories
Stage → Verdaccio / publish-stg (push) Successful in 28s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 22s
.claude/ and .serena/ hold local settings and tool locks, one directory per
assistant, and both turned up as untracked noise in every status. Nothing in
either is shared configuration — .serena/ ships its own .gitignore, and the
only .claude/ file with a stable name is settings.local.json.

Blanket-ignored rather than enumerated, with a comment naming the one case that
would need revisiting: a repository-wide .claude/settings.json is a real
convention, and committing one later takes a negation line here. No such file
exists today, so this does not pre-build a rule for it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 22:40:03 -05:00
chrnx a30c2cecb3 chore(release): 26.9.0-beta.2 to staging
The plugins repository builds against Plugin { name, mount } and app.boot(),
which only develop has. Staging the version publishes it to Verdaccio under
stg and nowhere else; the npm and JSR cut stays a separate decision.

The bump also moves the exported VERSION, which was two releases behind and had
no business being. Its comment claimed it was "replaced at publish time" and
nothing ever did that — not tsup, not stage.yml, not release.yml, which only
reads the version out of package.json. VERSION is what a consumer quotes in a
bug report, so a stale one sends someone to the changelog of a release they are
not running.

Pinning it to package.json is what keeps this from being a fix with a shelf
life: the next bump that forgets it now fails the build. smoke.test.ts was
never going to catch it, because it asserts the CalVer shape and a stale
version matches that perfectly.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 22:39:49 -05:00
chrnx 1364d54ab4 Merge pull request 'feat(plugin)!: a plugin is a named object, and app.boot() is public' (#96) from feature/plugin-contract into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 31s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-09-17 03:47:20 +00:00
chrnx 7a01ca3068 docs: record the plugin contract change and app.boot()
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 16m38s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:45 -05:00
chrnx e0da6cee16 test(runtimes): build plugins as named objects on Deno and Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:25 -05:00
chrnx b3152aac45 test: build plugins as named objects
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:15 -05:00
chrnx 3fc761ce16 feat(app): expose boot() so providers can fail before serving
Only listen() booted before accepting traffic. Deno, Bun and edge all boot on the
first request, and the memo keeps the rejection, so a bad key answered 500 for the
life of the process while the app looked healthy.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:26:28 -05:00
chrnx 80f3f532f2 feat(plugin)!: a plugin is a named object, not a function
BREAKING CHANGE: `Plugin` is now `{ name, mount(api) }`. `fn.name` was the only
source for the name that plugin:mounted reports, and it is empty for a returned
arrow, "plugin" for a const, and whatever a minifier decides. A failed mount now
names the plugin and keeps the original error as its cause, and two plugins with
the same name fail createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:26:13 -05:00
chrnx e83d62cc1a feat(signals): recognise HTTP errors by brand, not by instanceof
A plugin published as its own package cannot import HttpError without depending on
core's version, and under CalVer no dependency range survives next month's beta. A
Symbol.for brand crosses copies, so a plugin throws a 429 core renders, while
importing nothing but types.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:25:50 -05:00
chrnx 73a4a9f6cd Merge pull request 'Mirror develop to GitHub contrib' (#95) from ci/mirror-develop-to-contrib into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 7s
CI / build (push) Successful in 30s
2026-09-12 21:36:14 +00:00
chrnx 25f4144a38 ci(promote): mirror develop to GitHub contrib
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 13s
Outside contributors target GitHub `contrib`, which tracked released
`main` and was reset after every release. Between releases they were
working against code the current develop no longer had — a PR touching
an area that changed on develop was obsolete the day it opened, and only
the maintainer could see why.

`contrib` now mirrors `develop`: promote.yml runs on develop pushes too
and pushes to `contrib`, not forced. The refusal is the guard — it fires
exactly when `contrib` holds external merges not yet carried into
develop, and the job says so instead of forcing over them. `main`
keeps its one meaning: released code.

Gitea's `contrib` is gone; it was only ever a copy waiting to be
forgotten. AGENTS.md and CONTRIBUTING.md describe the new flow, drop
the post-release reset, and note that a develop conflict is now the
contributor's to resolve because they can see it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 16:34:55 -05:00
chrnx 6717b15ee9 Merge pull request 'A teapot exports steps and routes, not providers' (#94) from feat/mesh-steps-only into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / runtimes (deno) (push) Successful in 18s
CI / build (push) Successful in 31s
CI / runtimes (edge) (push) Successful in 14s
2026-09-12 20:42:04 +00:00
chrnx 0ce81b08f3 test(mesh): cover the teapot dying with an RPC still in flight
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
The three failure tests kill the teapot between requests, so the link is
already down when the next one arrives and `rpc` fails before it sends
anything. Nothing covered the case that can actually hang: the request is
parked on a promise waiting for an `rpc-res` frame that is never coming.

`endSession` already handles it -- `rejectAllPending` fails what was
waiting with a 503 -- but that line was untested. Stubbing it out leaves
all three existing tests green while these two hang until the per-RPC
timeout (30s by default) and then answer 504, so the regression this
guards against is a request that stalls for half a minute and then
reports the wrong cause.

Asserts 503 specifically rather than "not 200", since a 504 would mean
the timeout caught it instead of the disconnect.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 249fc00f80 fix(mesh): name the teapot in the boot log a later 404 points back to
A route the absent teapot would have exported 404s, and that is the right
status: nothing was ever registered for a manifest that never arrived, so
there is no path to serve. But a bare 404 is indistinguishable from a typo
in the path, and the boot log is the only place the two are told apart.

It could not tell them apart either. The give-up warning relied on the
error's own message to identify the teapot, which holds for a refusal --
`mesh handshake failed: <url>` -- but not for an unreachable one, where the
error is a socket error that may carry no url at all. So the url is passed
in now, and every line of the boot-connect story names it: the retries, the
refusal, and the give-up. The give-up line also says no manifest was ever
exchanged, which is the fact that explains the 404.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 6e050197b6 test(mesh): drop the buildRemote case its neighbour already subsumes
'turns every manifest step into a lazy remote node' built the same thing as
the test directly below it and asserted less about it: one step token instead
of two, no assertion on what the RPC was called with. Two tests covering one
behaviour, one of them strictly weaker.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 8ef7c3ee14 fix(mesh): validate the manifest's route entries, not just its steps
decode is the mesh's trust boundary, and the steps array gained a per-element
check on this branch while the routes array beside it kept only its
Array.isArray. A peer sending `{ method: 5, pattern: {} }` got past decode and
died in compilePattern as a boot TypeError — it failed closed, so nothing was
exposed, but the error blamed green-tea for what was a malformed frame from
the other side. Both fields reach compilePattern, so both are checked.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx e69f604053 docs(mesh): record the scopes->steps rename as an exception to the bump rule
The bump rule in protocol.ts says renaming a field earns a protocol bump, and
this branch renamed the manifest's `scopes` to `steps` at v1 without one. The
argument for that lived only in the CHANGELOG, so the rule as written read as
simply broken to anyone who found it from the code.

The exception is now stated where the rule is, with the three conditions it
rests on: mesh is alpha, every app using it is gated behind `experimental:
true`, and both peers ship out of this repo, so no deployed pair can be split
across the rename. It retires with the first mesh release that drops
`experimental`.

Two other stale pointers go with it. The bootTimeoutMs JSDoc said `0` restores
"the old behaviour of a single attempt", which now reads as restoring a boot
that failed — it is only the attempt count, and the way to make a teapot's
absence fatal is a local `@needs` on one of its tokens. And the reconnect
plan's step 4 still pointed at invalidateRemoteBindings, which this branch
deleted; it gets a dated note in the same shape as the degrade plan's D6.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 727987286b refactor(graph): the missing-dependency note is a string, not a callback
topoSort, finalizeGraph, assertNeedsSatisfiable and finalize all threaded a
`(key: string) => string`, and no caller ever read `key` — the one producer,
in prepareGraph, is `() => ...`. The note names which teapots did not connect,
which does not vary by token, so the parameter was machinery for a
customization nothing asked for.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx bff8778112 refactor(mesh): @Provider's options no longer advertise export
The framework's public type offered an option whose only behaviour is to
throw at boot. Removing the field from the options type means a TypeScript
caller gets a compile error at the decorator, where the mistake is, instead
of a boot error a deploy away.

The runtime throw in collectProviders stays as the JavaScript backstop, so
ProviderMeta keeps the field and the decorator still records it through a
cast — a JS caller reaches the error naming the provider and its replacement
rather than having the option silently ignored.

The `as any` in the boot-throw test is now genuinely load-bearing, since no
TypeScript caller can write that decorator at all, and says so.

test/metadata.test.ts asserted the flag was stored for a provider. That half
described the option working, which is the message being removed, and the
boot throw it fed is already covered end to end in test/mesh/failure.test.ts.
The default is a different claim and stays: collectProviders throws on
anything truthy, so every plain provider recording `false` is what keeps
ordinary apps booting.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 1bcaa463f2 fix(mesh): a rejected first connect no longer leaks a retry supervisor
openSession's abort listener runs onEnd -> endSession -> scheduleRetry on
every socket abort, including the ones where the connect promise rejected.
A rejected connect means no caller ever received the Link, so nothing can
close it and closeLinks never sees it — connectUntilDeadline pushes to
meshLinks only on success. Every boot attempt against an unreachable teapot
therefore left a live supervisor behind, reconnecting forever on a handle
nobody holds.

Before this branch the boot then threw and the process died with them. Now
the teacup starts without that teapot, so they outlive the boot: close() the
teacup, bring the teapot up afterwards, and three mesh:connect events fire
for a URL contributing nothing to the graph, each holding an open socket.

The initial openSession now marks the link closed and clears the pending
timer before rethrowing. connectUntilDeadline is already the retry loop above
this; a second one underneath it was never wanted. Reconnection for a link
that did connect is untouched — that path runs through endSession on a
session that dropped after the Link escaped, and the rejection handler here
fires only on the first connect.

The regression test asserts both sides: no mesh:connect on the teacup, and
none on the teapot either, so a socket that opens without being adopted still
fails it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx f5d4d0cd74 docs(mesh): an absent teapot 404s, it does not 503
A teapot that never connected sent no manifest, so spliceRemoteScopes
registers nothing for it — no step runner, no route. Its routes therefore
take the ordinary unmatched path and 404, and a local node that needs one of
its tokens still fails the boot naming it. The 503 belongs to a teapot that
connected and later died, where the link and its exports exist and the
dead-link guard answers.

The previous commit said 503 for the absent case in five places, including
the warning an operator reads during a deploy. All five now tell the same
story, and the bootTimeoutMs JSDoc — stale in the other direction, still
claiming an absent teapot fails the boot — with them. The connectUntilDeadline
JSDoc also had a paragraph saying it still throws, contradicted three
paragraphs later; that one is gone.

No behaviour changed. Serving 503 for an absent teapot's tokens means knowing
what it would have exported, which is the expects list in the degrade plan and
is deliberately not built.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 03132b2048 docs(mesh): steps and routes are what a teapot exports
The CHANGELOG gains an [Unreleased] section — no version heading, no date —
covering the three mesh changes on this branch and why each one follows from
the first: a remote export is a step now, so it holds nothing between requests,
so an absent teapot costs a 503 rather than a boot.

The README says it in the Honest scope section, where the mesh caveats already
live: what can be exported, what happens if you export a provider anyway, and
why a missing token still fails the boot when an unreachable teapot no longer
does.

Two stale bits go with it. The JSDoc over assertNeedsSatisfiable still quoted
the old unconditional message; the Deno and Bun fixtures still said a teapot
exports its scopes. And the degrade plan's D6 planned to reuse a seam this
branch deleted — a dated note says so, and why a degraded step never needed it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 9f5792c1c5 test(mesh): steps-only exports across Deno, Bun and the edge
Deno and Bun mesh fixtures still exported a @Provider, which now throws
at boot. Convert each to a @Step (provide() -> run(), move the class
from providers: [] to steps: []) so the fixtures build a graph the
current mesh actually allows.

test/edge/_worker.mjs is a gitignored esbuild bundle rebuilt by
test/edge/run.ts on every test:edge run, so no source change was needed
there once the fixtures matched. All four suites pass: vitest (Node),
deno test, bun test, and the workerd/miniflare edge run, plus
typecheck.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 4e8aacb6b7 fix(mesh): name the absent teapot in the route-level missing-need error too
assertNeedsSatisfiable is a separate check from topoSort, so it didn't
get the note threaded into finalizeGraph -- a handler-level @needs
against an absent teapot's token read as a typo or a forgotten
export: true, which is worse than the pre-task behavior (the boot used
to throw naming the teapot). Thread missingNote through and soften
"local or mesh" to "local or connected mesh" when it's set, so the
message doesn't claim a search that never happened.

Also tightens two test assertions that only passed because "mesh"
happened to appear inside the unrelated "(local or mesh)" wording, and
removes adopt()'s now-fully-unused attempt parameter in mesh/link.ts
instead of leaving it underscored.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 3b680480ab feat(mesh): an unreachable teapot no longer stops the teacup from booting
Blocking existed for app-scope exports, which have to resolve at boot
because there is no later. Steps and proxied routes are all later. The
grace budget stays -- a co-deploy still waits -- but exhausting it now
warns instead of throwing. A missing token still fails the boot, and the
error now names the teapots that were away.

Also drops connectLink's onReconnect hook and the reconnected flag that
fed it: its only caller was removed by an earlier commit on this branch,
and it is not part of the public API (not re-exported, not documented).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 414b188792 fix(mesh): reject a manifest step that is not a string
decode is the mesh's trust boundary, reached before the handshake
authenticates the peer. The manifest row checked that steps was an array
but not what was in it, so {"steps":[123]} decoded cleanly and 123 would
have become a graph node name in buildRemote.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 6e66b05a41 refactor(mesh): drop the remote app-scope binding and its rebind seam
A remote provider was registered app-scope, resolved once, and cached for
the process lifetime; invalidateRemoteBindings existed only to un-cache it
on reconnect. With providers gone from the manifest, both go, and a remote
step needs nothing on reconnect because it holds nothing between requests.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 55890442fe refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one
value and told a reader nothing. No protocol bump: mesh is alpha, both
peers ship from this repo, and the number should mean incompatibility
between deployed versions.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx f6c05a0929 feat(mesh)!: refuse to export a provider
A provider's value is the object it builds, which cannot cross a JSON wire.
What did cross became an app-scope binding the teacup resolved once at boot
and served from a cache the teapot no longer stood behind. A step is the
shape that travels; the error says so.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:24 -05:00
chrnx 419ba092d4 docs(plans): a mesh that exports steps, not providers
Plan for dropping @Provider export from the mesh: the manifest carries step
names, an unreachable teapot stops blocking the boot, and the app-scope
binding that cached a remote value for the process lifetime goes away.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:23 -05:00
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 (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 22s
CI / runtimes (edge) (push) Successful in 12s
Stage → Verdaccio / publish-stg (push) Successful in 25s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
Promote → GitHub / push-github (push) Successful in 8s
CI / runtimes (bun) (push) Successful in 16s
Release → npmjs / publish-prod (push) Has been skipped
Reviewed-on: #91
2026-09-04 13:23:20 +00:00
chrnx dfe71102ca docs(changelog): date the section for the day the tag actually ships
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 14s
The heading was written for 2026-09-02, the day the cut was planned, then dated 2026-09-03
when it was closed. Neither day shipped anything, and the workflow split that has to land
before the tag moved it once more.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 22:10:20 -05:00
chrnx 7ccb55d07a Merge pull request 'Route ranking at build time, and a benchmark that can measure a release' (#87) from perf/matcher-and-benchmarks into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 31s
CI / runtimes (edge) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
2026-09-02 03:07:37 +00:00
chrnx e61771077c docs(bench): refresh the tables and record what moved between releases
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 19s
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 / dco (pull_request) Successful in 4s
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
`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 (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
`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 / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
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 (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
The event stream's contract, the read-only `events` token, the reserved framework names,
the unmatched-route label, the budget bookkeeping, and the `onError` crash.

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

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

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

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

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

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

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

Closes #74.

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

## `@needs('events')`

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

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

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

## The boot error teaches it

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

## Framework names are reserved

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

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

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

Closes #67.

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

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

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

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

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

Closes #65.

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

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

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

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

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

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

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

Closes #80.

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

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

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

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

Closes #64.

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

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

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

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

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

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

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

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

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

Closes #73.

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:47:57 -05:00
chrnx f08956bea8 Merge pull request 'Tier 1 for 26.9.0-beta.1: the four that block the cut' (#78) from beta/tier-1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 14:44:41 +00:00
chrnx b8b3548f15 perf(cors): resolve the request's headers once, not two or three times
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

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

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

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

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

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

Closes #77.

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

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

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

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

Closes #66.

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

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

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

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

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

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

Closes #70.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:09:56 -05:00
chrnx 4896ee86d2 fix(jsr): resolve require from source, not from tsup's banner
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 16s
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.

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

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

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

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

Closes #69.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:50:42 -05:00
chrnx bb0b01cf26 fix(cors): deny the origin when the origins predicate throws
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 14s
`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 (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
CI / build (push) Successful in 30s
CI / runtimes (bun) (push) Successful in 14s
CI / dco (push) Has been skipped
2026-09-01 13:29:40 +00:00
hgshreyas ff94e55496 feat: cap concurrent requests across runtimes
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / dco (push) Has been skipped
CI / runtimes (edge) (push) Successful in 11s
CI / build (pull_request) Successful in 29s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-31 08:53:14 -05:00
hgshreyas 82e1678dea fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-30 12:55:20 -05:00
chrnx 4b04421ddd Merge pull request 'ci(release): publish the release notes, not just the tag' (#62) from ci/github-releases into develop
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
Promote → GitHub / push-github (push) Failing after 6s
CI / dco (push) Has been skipped
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 25s
2026-08-19 19:32:14 +00:00
chrnx 0fad12688d ci(release): publish the release notes, not just the tag
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
The repository had two tags and no releases, so the only way to find out what
a version changed was to open CHANGELOG.md and scroll to the right heading.
The release page is where people who do not read changelogs look, and a
repository with tags and no releases reads as abandoned.

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:31:05 -05:00
chrnx 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
Promote → GitHub / push-github (push) Failing after 6s
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
2026-08-19 19:18:20 +00:00
chrnx 19fcc18899 ci(release): spend the publish's one dist-tag on latest while there is no stable
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / dco (pull_request) Successful in 4s
`npm dist-tag` cannot use Trusted Publishing. The OIDC exchange lives inside
`publish.js` and nowhere else, so the token it returns is publish-scoped: the
step added in the previous commit got `E401` on v26.8.0-beta.1, after both
registries had already taken the version.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:17:12 -05:00
120 changed files with 6940 additions and 895 deletions

No files matched your search

+33 -13
View File
@@ -1,13 +1,30 @@
name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
# its release workflow (production publish).
# Promotion. Runs on GITEA ONLY. Mirrors two branches to the public GitHub repo and nothing else:
#
# main → GitHub main the production mirror
# develop → GitHub contrib what outside contributors fork from and target
#
# Feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
# would expose every branch).
#
# Neither push is forced. For `contrib` that is the guard, not a limitation: the push is refused
# exactly when `contrib` holds external merges that have not been carried into `develop` yet
# (AGENTS.md, "External contributions"). Carry them and the next develop push fast-forwards.
#
# Tags are deliberately NOT mirrored. The same `v*` tag means two different things on the two
# forges: on Gitea it stages to Verdaccio (`stage.yml`), on GitHub it publishes to npm and
# JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
# decision a person takes after reading the staging run, not a side effect of creating it:
#
# git push gh v<version>
#
# `--tags` is left off the branch push for the same reason. It used to ride along here, which
# meant any tag sitting in the runner's clone could reach production as a side effect of
# promoting `main` — a publish nobody chose, of a commit nobody was looking at.
on:
push:
branches: [main]
tags: ['v*']
branches: [main, develop]
jobs:
push-github:
@@ -16,15 +33,18 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history + tags for a clean push
- name: Push main + tags to GitHub
fetch-depth: 0 # full history for a clean push
- name: Push to GitHub
env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: |
case "$GITHUB_REF_NAME" in
main) target=main ;;
develop) target=contrib ;;
*) echo "::error::promote runs for main and develop only, got '$GITHUB_REF_NAME'"; exit 1 ;;
esac
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
if [ "${{ github.ref_type }}" = "tag" ]; then
git push github "refs/tags/${{ github.ref_name }}"
else
git push github "HEAD:refs/heads/main"
git push github --tags
if ! git push github "HEAD:refs/heads/${target}"; then
echo "::error::GitHub ${target} has commits that ${GITHUB_REF_NAME} does not. For contrib that means external merges not yet carried into develop — carry them (AGENTS.md, External contributions); never force this push."
exit 1
fi
+49 -37
View File
@@ -16,7 +16,7 @@ jobs:
PKG: '@green-tea/core'
permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read
contents: write # create the GitHub release for this tag
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -42,19 +42,41 @@ jobs:
# types, module analysis — and learning about them after npm has published leaves the tag
# half-shipped. Seconds, against a failure mode with no clean recovery.
- run: deno publish --dry-run
# A publish sets exactly one dist-tag, and it is the only npm write this workflow can make:
# Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token
# it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag
# the publish gets has to be the one that matters most.
#
# While no stable release exists, `latest` and the channel tag mean the same thing — there is
# nothing else to install — and `latest` takes it, because that is what a bare
# `npm install @green-tea/core` resolves to. Leaving it behind on an older beta would hand the
# default install an older build than the one just released. The channel tag is then moved by
# hand; the step prints the command. Once a stable version exists it owns `latest` for good,
# a later beta must not drag it backwards, and the channel tag becomes the automatic one again.
- name: Publish to npmjs
run: |
VERSION=$(node -p "require('./package.json').version")
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
# Read the list into a variable so a failed lookup fails the step, rather than passing for
# "no stable exists" and pointing `latest` at a prerelease that should not have it.
VERSIONS=$(npm view "$PKG" versions --json)
if [ "$CHANNEL" != latest ] \
&& ! node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
TAG=latest
else
TAG=$CHANNEL
fi
echo "$VERSION under dist-tag: $TAG"
# Skip rather than fail when the version is already up. A step after this one can fail —
# the dist-tag move below does — and a re-run of the job has to be able to finish the
# remaining work instead of dying on a duplicate npm rejects anyway.
# 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
@@ -65,43 +87,33 @@ jobs:
run: |
VERSION=$(node -p "require('./package.json').version")
PKG=${PKG#@}
# 404 until the version exists — and it stays 404 for a package with no versions yet, which
# is the state this repository is actually in, so the guard must not read that as an error.
# 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
# `latest` is what a bare `npm install @green-tea/core` resolves to, and while there is no
# stable release the docs promise it is the newest beta. `npm publish --tag beta` sets exactly
# one tag, so `latest` has to be moved separately — and `npm dist-tag` cannot use Trusted
# Publishing, whose OIDC exchange lives only inside `npm publish`. So we run that same exchange
# by hand (id-token → short-lived npm token) rather than keep a long-lived token in a secret for
# one command. Last on purpose: both registries already have the version, and a dist-tag is the
# only thing here that can be redone. If this step fails, the release is out but `latest` is
# stale — recover with `npm dist-tag add @green-tea/core@<version> latest`.
- name: Point `latest` at this release while no stable exists
# 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")
case "$VERSION" in
*-*) ;;
*) echo "$VERSION is stable — npm publish already put it on latest"; exit 0 ;;
esac
# A stable release owns `latest` for good; a beta published afterwards must never drag it
# backwards, so the newest-beta rule applies only until the first stable exists.
# Read the list first so a failed lookup fails the step, rather than reading as "no stable
# exists" and moving `latest` backwards on the strength of a network error.
VERSIONS=$(npm view "$PKG" versions --json)
if node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
echo "a stable version exists — leaving latest where it is"; exit 0
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
URL=$(node -p "const u=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);u.searchParams.set('audience','npm:registry.npmjs.org');u.href")
ID_TOKEN=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$URL" \
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).value")
echo "::add-mask::$ID_TOKEN"
NODE_AUTH_TOKEN=$(curl -fsS -X POST -H "Authorization: Bearer $ID_TOKEN" \
"https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/$(node -p "encodeURIComponent(process.env.PKG)")" \
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).token")
echo "::add-mask::$NODE_AUTH_TOKEN"
export NODE_AUTH_TOKEN
npm dist-tag add "$PKG@$VERSION" latest
node scripts/changelog-section.mjs "$VERSION" "$TAG" > /tmp/notes.md
case "$VERSION" in *-*) PRE=--prerelease ;; *) PRE= ;; esac
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" \
--notes-file /tmp/notes.md --verify-tag $PRE
+13 -2
View File
@@ -1,12 +1,18 @@
name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
# internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag.
# Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version.
#
# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path —
# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we
# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm
# allows 72 hours to unpublish and JSR allows nothing at all.
on:
push:
branches: ['release/**']
tags: ['v*']
jobs:
publish-stg:
@@ -32,6 +38,11 @@ jobs:
run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version")
# Staging overwrites the version it publishes, and a stable number that changes
# under an internal consumer is worse than no staging at all. This will need
# revisiting at the first stable release, which is exactly the one most worth
# staging: the answer is probably to stage it under a suffixed version rather
# than to drop the guard.
case "$VER" in
*-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
+7
View File
@@ -1,6 +1,13 @@
# Local specs & plans — not committed
.specs/
# Per-developer agent state: local settings and tool locks, one directory per assistant. Nothing
# here is shared configuration — `.serena/` even ships its own .gitignore. A repository-wide
# `.claude/settings.json` is a real convention and would need a `!` line here to be committable;
# none exists today, so this stays a blanket ignore rather than a rule for a file nobody wrote.
.claude/
.serena/
# Node
node_modules/
dist/
+48 -8
View File
@@ -29,18 +29,23 @@ Run the first four before proposing anything as finished. The runtime suites sta
## Two forges
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and release tags, nothing else.
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and `develop` automatically — `develop` under the name `contrib` — and release tags only by hand.
```
feature/* → develop → main → [promote.yml] → GitHub main
↑ ↓
lead dev GitHub contrib ← external PRs
│ │
└─[promote.yml]┼──→ GitHub contrib ← external PRs
↑ │ │
└── carried back by hand ─┘ (a PR into develop)
│
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
└─── GitHub (pushed by hand): [release.yml] → npm + JSR
```
- **Gitea `develop`** — active development.
- **Gitea `main`** — staging. Merging here publishes nothing; only a `v*` tag publishes.
- **Gitea `main`** — staging. Merging here publishes nothing. A `v*` tag here publishes to the internal Verdaccio, never to a public registry.
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
- **`contrib`** — exists on *both* forges. Where outside contributions land.
- **GitHub `contrib`** — mirror of `develop`, pushed by `promote.yml` on every develop merge, and where outside contributions land. GitHub only: there is no Gitea `contrib`.
`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.
@@ -50,6 +55,14 @@ feature/* → develop → main → [promote.yml] → GitHub main
**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.
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
```bash
git branch -d <branch> && git push origin --delete <branch>
```
On 2026-09-22 this repository carried 36 branches on Gitea and 29 locally, every one but a single stale docs branch already merged into `develop`, some of them since July. At that size the branch list stops describing the work in flight and becomes something a release has to audit commit by commit — which is both when it costs the most and when nobody has the patience for it. `git branch -r --merged origin/develop` is the check. A branch whose commits were rebased on the way in will not appear there even though its content did land, so confirm that case by content (`git diff <branch> develop -- <file>`) rather than by the flag. Never `develop`, `main`, or a `release/*` that has not shipped yet.
**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
@@ -58,13 +71,13 @@ git diff <branch> <main> -- <suspect file> # empty means the content is alread
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.
**External contributions.** They arrive on GitHub `contrib`. Merge the pull request there, fetch GitHub `contrib` into a branch on Gitea, then open a pull request from it into `develop` and merge it. The next develop push mirrors back to `contrib`, and fast-forwards because `develop` now contains everything `contrib` had. 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 leave `contrib` with commits `develop` does not have, so the mirror push is refused until someone forces it. 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.
**Nothing to reset after a promotion.** `contrib` follows `develop` through the mirror, and there is no Gitea `contrib` to keep in step. The one thing the mirror will not do is push over external merges that were never carried in: that push is refused, the promote job fails, and the fix is to carry them as above — never to force.
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.
A conflict against `develop` is visible to the contributor through `contrib`, so it can be theirs to resolve: ask them to rebase onto the current `contrib`. Only a conflict against a feature branch that has not merged yet is the maintainer's alone, because that code they cannot see.
## Releasing
@@ -85,6 +98,33 @@ Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary
*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.
+214 -37
View File
@@ -4,14 +4,14 @@
## Environment
- **Date**: 2026-07-07
- **Commit**: fe1831a
- **Date**: 2026-09-22
- **Commit**: daf0fed
- **Node**: v22.22.2
- **OS**: darwin
- **CPU**: Apple M4 Max (16 cores)
- **RAM**: 69 GB
- **OS**: linux
- **CPU**: AMD Ryzen 7 3700X 8-Core Processor (16 cores)
- **RAM**: 67 GB
- **Core-pinned**: no
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
- **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
> loopback on the same machine, sharing the same cores as the server processes they measured. That
@@ -29,64 +29,74 @@
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
| raw-http | 41,631 | 2.00 | 3.00 | 4.00 | 0.6% | 41,343–41,974 |
| nestjs-fastify | 32,419 | 3.00 | 4.00 | 6.00 | 0.5% | 32,103–32,583 |
| fastify | 32,170 | 3.00 | 3.00 | 5.00 | 1.3% | 31,236–32,356 |
| green-tea | 29,777 | 3.00 | 6.00 | 7.00 | 0.4% | 29,557–29,873 |
| express | 10,546 | 8.00 | 13.00 | 18.00 | 0.4% | 10,480–10,625 |
| nestjs-express | 9,680 | 9.00 | 15.00 | 21.00 | 0.6% | 9,567–9,739 |
### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
| raw-http | 41,756 | 2.00 | 3.00 | 4.00 | 1.1% | 40,953–42,017 |
| fastify | 31,708 | 3.00 | 4.00 | 5.00 | 0.5% | 31,359–31,847 |
| nestjs-fastify | 29,880 | 3.00 | 4.00 | 6.00 | 0.3% | 29,745–29,961 |
| green-tea | 28,706 | 3.00 | 6.00 | 7.00 | 0.6% | 28,562–29,051 |
| express | 10,376 | 9.00 | 12.00 | 17.00 | 0.4% | 10,364–10,453 |
| nestjs-express | 9,257 | 10.00 | 15.00 | 21.00 | 0.2% | 9,244–9,285 |
### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
| raw-http | 39,897 | 2.00 | 3.00 | 5.00 | 0.6% | 39,847–40,441 |
| fastify | 31,436 | 3.00 | 4.00 | 6.00 | 0.6% | 31,079–31,563 |
| nestjs-fastify | 29,403 | 3.00 | 4.00 | 6.00 | 0.6% | 29,151–29,689 |
| green-tea | 26,839 | 3.00 | 6.00 | 8.00 | 0.1% | 26,783–26,872 |
| express | 10,365 | 9.00 | 12.00 | 18.00 | 1.3% | 10,171–10,542 |
| nestjs-express | 9,256 | 10.00 | 15.00 | 22.00 | 0.5% | 9,187–9,302 |
### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
| raw-http | 31,783 | 3.00 | 5.00 | 6.00 | 0.4% | 31,517–31,825 |
| green-tea | 22,005 | 4.00 | 7.00 | 9.00 | 0.7% | 21,736–22,187 |
| fastify | 20,430 | 4.00 | 8.00 | 9.00 | 0.4% | 20,398–20,601 |
| nestjs-fastify | 18,597 | 4.00 | 8.00 | 11.00 | 0.2% | 18,540–18,658 |
| express | 8,440 | 11.00 | 16.00 | 24.00 | 0.3% | 8,408–8,492 |
| nestjs-express | 7,666 | 12.00 | 18.00 | 26.00 | 0.3% | 7,645–7,703 |
## Step-scaling (green-tea)
| Path | Steps | req/s |
| --- | --- | --- |
| /steps/0 | 0 | 92,282 |
| /steps/3 | 3 | 81,530 |
| /steps/5 | 5 | 71,994 |
| /steps/0 | 0 | 29,196 |
| /steps/3 | 3 | 26,564 |
| /steps/5 | 5 | 25,314 |
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
Each additional pipeline step costs roughly 776 req/s (-13.3% over 5 steps), on this box.
## green-tea across runtimes
| Scenario | node | deno | bun |
| --- | --- | --- | --- |
| JSON hello (overhead) | 30,379 | 51,888 | 46,300 |
| Route param | 29,204 | 51,786 | 42,788 |
| Pipeline (3 steps) | 27,208 | 50,692 | 39,644 |
| POST JSON + validation | 22,609 | 35,743 | 31,960 |
Same application, same built bundle, same box — only the runtime differs. Read across a row, never against the cross-framework tables above: those measure other frameworks on Node, and nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.
## Cost of secure-by-default (green-tea)
| Label | req/s |
| --- | --- |
| security:false (parity) | 98,093 |
| security:true (default) | 92,998 |
| security:false (parity) | 29,777 |
| security:true (default) | 28,919 |
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 ~2.9% req/s on this box.
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
@@ -116,3 +126,170 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
<!-- keep-below: hand-written, survives `npm run bench` -->
## What moved between releases
These figures were measured per function and never per version. Every change on the request path
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
`npm run bench:compare` exist to close.
### The release gate: `26.9.0-beta.1` → `26.9.0-beta.2`
Ten cases, both trees on one box in one sitting, alternating which side ran first each round, sharing
one `node_modules` — the two revisions differ by a version string and nothing else in `package.json`,
so the only thing that moved between the sides is green-tea. Medians of three rounds:
| Scenario | 26.9.0-beta.1 | 26.9.0-beta.2 | Δ | |
| --- | --- | --- | --- | --- |
| hello | 90,615 | 89,853 | −0.8% | overlaps |
| param | 86,956 | 87,572 | +0.7% | overlaps |
| pipeline (3 steps) | 80,061 | 81,504 | +1.8% | overlaps |
| steps5 | 75,436 | 75,238 | −0.3% | overlaps |
| validate (POST) | 70,240 | 73,568 | +4.7% | overlaps |
| hello + security | 83,738 | 84,890 | +1.4% | overlaps |
| hello + cors predicate | 82,237 | 82,528 | +0.4% | overlaps |
| preflight + cors predicate | 111,223 | 114,220 | +2.7% | overlaps |
| param, 50 routes | 83,505 | 87,078 | +4.3% | **flagged** |
| param, 200 routes | 73,289 | 73,335 | +0.1% | overlaps |
Nine rows overlap and therefore say nothing, which is the result this gate exists to produce. The
release is a breaking one — `Plugin` became `{ name, mount }`, `serveDeno()` and `serveBun()` became
async, `@Provider({ export: true })` stopped being a thing a teapot can do, and an `HttpError` is now
recognised by a brand rather than by `instanceof` — but all of that is boot-time or error-path work.
None of it sits on the per-request path these cases walk, and the table agrees.
The tenth row is why "flagged" is not a synonym for "found something". `param, 50 routes` came out
+4.3% with separated ranges, in green-tea's favour, and it did not survive being asked twice: re-run
alone at seven rounds it is **+0.5% and overlapping**, with both sides swinging between 80,794 and
88,259 req/s. The reason to doubt it before re-running was that it had no mechanism — the matcher
work that could produce it would have to show at 200 routes too, and that row had already said
+0.1%. Treat a flagged row as an instruction to measure again, whichever direction it points; a win
nobody can explain is a measurement problem more often than it is a win.
The cross-framework tables above moved to a quiet box for this release, which is why their absolute
numbers are roughly a third of the previous run's: an idle 2019 desktop Ryzen against a laptop M4
Max. Two attempts on that laptop were discarded first, and the reason is worth recording. Each
framework's delta against its own previous number tracked its position in the run order rather than
anything in its code — the one measured second lost 7%, the ones measured last gained — while a
browser and the window server held around 60% of the machine throughout. That run would have read
as green-tea overtaking Fastify, which is the most flattering available reading of a broken
measurement and exactly the kind this file exists to refuse. The gate table above survives the same
contention, because both sides pay it and the order alternates; an absolute cross-framework number
does not.
What survived the move is the shape, and that is the part worth trusting. On both machines green-tea
is behind Fastify on `hello`, `param` and `pipeline` and ahead of it on `validate`, and roughly
2.8× ahead of Express throughout. The *size* of the gap did not survive: against Fastify it is
2-8% on the M4 and 7-15% here. A percentage quoted without the hardware it was measured on is not a
fact about the framework.
### 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.
+336 -2
View File
@@ -6,7 +6,340 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
## [26.9.0-beta.2] - 2026-09-22
### Breaking
- **`serveDeno()` and `serveBun()` are async**, returning `Promise<DenoServer>` and
`Promise<BunServeResult>`. They now boot the app before they bind, which is what `listen()` has
always done.
They did not, and the documented fix was to remember to `await app.boot()` first. That made the
correct use of a core helper depend on reading a README, in a framework whose argument is that
order should not be something you have to get right. Forget it and a missing signing key is not a
failed deploy: the boot memo keeps the rejection, so the port binds, every request gets a 500 from
the runtime, and none of them reach `onError`. The server looks healthy to anything that only
checks whether it is listening.
Migration is one keyword, and the value is unchanged:
```diff
- const server = serveDeno(app, { port });
+ const server = await serveDeno(app, { port });
```
Both runtimes support top-level `await`, so a module that serves at import time needs nothing
else. `edgeHandler` is deliberately untouched: on workerd there is no startup outside a request,
so there is no earlier moment to move the failure to.
- **A plugin is a named object.** `Plugin` is now `{ name, mount(api) }`; it was `(api) => void`.
The name that `plugin:mounted` reports came from `fn.name`, which is `""` for an arrow returned
straight from a factory, `"plugin"` for a `const`, and whatever a minifier leaves behind — so the
event that exists to report which plugins mounted reported none of them by name. The name is now
the author's word, a failed `mount` is reported as `plugin "<name>" failed to mount: …` with the
original error as its `cause`, and two plugins sharing a name fail `createApp`.
Migration is mechanical:
```diff
- const jwt = (options) => ({ scope }) => { scope.add(node); };
+ const jwt = (options) => ({
+ name: options.provides ?? 'jwt',
+ mount({ scope }) { scope.add(node); },
+ });
```
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
the boot, with an error naming the provider and the replacement. A provider is a factory whose
value *is* the object it builds — a pool, a client, a `db` — and an object is not what a JSON wire
carries. What did cross was whatever half of it survived serialization, and it arrived as an
app-scope binding: the teacup resolved it once at boot and then served that value for the life of
the process, out of a cache the teapot no longer stood behind. Restarting the teapot, or changing
what it built, changed nothing on the teacup until the teacup itself restarted.
Export a `@Step` instead. It runs on the teapot, per request, and only its result comes back —
which is why the two entries below follow from this one: a remote export now holds nothing between
requests. `invalidateRemoteBindings`, the `rebind` array and the `onReconnect` callback that drove
them are gone with it. All three existed to throw away a cached app-scope value when a link came
back; there is no longer a cached value, so a reconnected link is simply usable again on the next
RPC. Internal, so nothing importable changed.
**A teapot that boots today can stop booting**, and the replacement is mechanical: the exported
`@Provider` becomes a `@Step` that returns what the provider's value carried.
- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now
`{ steps: string[], routes }`. Every export is request-scope after the change above, so the
lifetime field had one possible value left and told a reader nothing. A manifest step that is not
a string is now rejected on arrival, rather than trusted because a peer sent it.
`MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both
peers ship from this repository, and there is no deployed pair of versions for a bump to protect —
it would spend the number on nobody. A stable wire would not get that option; alpha is exactly
what the word buys, and this is the last comfortable moment to use it.
### Added
- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`,
`serveDeno()` and `serveBun()` all call it for you (see Breaking, below). Call it by hand when you
drive `app.fetch` / `app.upgrade` from your own server: those boot lazily, and the boot memo keeps
a rejection, so a bad key answers 500 on *every* request, from the runtime, without reaching
`onError`. On workerd there is no startup outside a request, so calling it moves nothing.
- **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry
`Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and
`isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a
different copy of core — a plugin package, an app that installed from npm and JSR both — now
renders with its own status instead of a 500. The exported `HttpErrorLike` type and the
`isValidationError` guard come with it. The string is the public protocol: code that imports only
types writes `Symbol.for('green-tea.http-error')` itself.
### Changed
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** Blocking was never
caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later
to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the
container is thirty seconds behind" and "the teapot does not exist" look identical for the first
thirty seconds; exhausting it now warns and starts without that teapot.
What that buys is narrower than it sounds, and worth stating exactly. A teapot that never
connected sent no manifest, so the teacup learned nothing about it — no step runners, no routes,
a graph identical to the one it would have had if that teapot were never configured. Its routes
therefore **404**, through the ordinary unmatched-route path, because nothing was ever registered
to match. And any local step or handler that needs one of its tokens **still fails the boot**,
naming the teapot that did not connect. `503` is what a teapot that connected and *later* died
answers: that link exists, its steps and routes are registered, and the dead link is what returns
the status. Never reachable and reachable-then-gone are different situations, and they read
differently on purpose.
So the change is for the teacup that does *not* depend on that teapot: it starts, rather than
refusing over a dependency it never had. It is not graceful degradation of the dependency, and
cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have
exported, and only a declaration can say. That declaration is the `expects` list in
`docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are
unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot
without spending the grace, because it is the teapot's decision rather than the network's and will
be the same decision in thirty seconds; and the missing-token error, which now says "local or
connected mesh" rather than "local or mesh", the old wording having claimed a search that never
happened.
## [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
@@ -309,7 +642,8 @@ change before the stable release.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...main
[26.9.0-beta.2]: https://github.com/Expressive-Tea/green-tea/compare/v26.9.0-beta.1...v26.9.0-beta.2
[26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
+4 -4
View File
@@ -4,9 +4,9 @@ Thanks for your interest. green-tea is open source, but not anyone can push dire
## 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.
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main`, release tags, and `develop` — the last one under the name `contrib`. 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 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. `contrib` is a mirror of `develop`, so you are working against the current code rather than the last release.
**From Gitea, if you have access:** follow the branch model below.
@@ -30,7 +30,7 @@ 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.
`contrib` follows `develop`, so it moves whenever development does. If your branch has been open a while, rebase onto the current `contrib` before pushing again.
## Developer Certificate of Origin (DCO)
@@ -91,7 +91,7 @@ If your assistant reads repository instructions, `AGENTS.md` has the conventions
- `feature/<name>` — branch from `develop`.
- `hotfix/<name>` — branch from `main`.
- `release/<version>` — release stabilization.
- `contrib` — GitHub only. Where outside contributions land before a maintainer moves them to `develop`.
- `contrib` — GitHub only. A mirror of `develop`, and where outside contributions land before a maintainer carries them into `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.)
+11 -6
View File
@@ -56,9 +56,9 @@ npm install busboy # multipart/form-data file uploads
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
- **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 (`await app.listen()` → `await serveDeno()` / `await serveBun()` / `edgeHandler`) and nothing else — each one boots the app before it binds, so a provider that cannot start fails the deploy instead of answering `500`s from a port that looks healthy. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `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.
- **Plugins can't sabotage you.** A plugin is `{ name, mount(api) }`. It 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?
@@ -141,10 +141,11 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** 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.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -152,7 +153,9 @@ without growing the runtime dependency tree past `reflect-metadata`:
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
On that harness, **green-tea handled more requests per second than every other framework in 3 of 4 scenarios** (JSON response, routing, and body-parsing-plus-validation), behind only raw `http` with no framework at all. In the fourth (a multi-step pipeline) it lands even with Fastify.
On that harness green-tea is in the same class as Fastify and NestJS-on-Fastify, roughly 2.8× ahead of Express, and behind raw `http` with no framework at all. Within that class the shape reproduces on two very different machines: green-tea is **behind** Fastify on the JSON, routing and pipeline scenarios, and **ahead** of it on POST-plus-validation. How far behind is a property of the box rather than a constant — 2-8% on a laptop M4 Max, 7-15% on an idle desktop Ryzen — which is why the table carries its hardware and its date, and why a percentage quoted without them says little. Read [BENCHMARKS.md](./BENCHMARKS.md) rather than a sentence here: a ranking written into prose once is a claim nobody re-measures.
The question a release actually has to pass is the other one — *did the last N commits cost anything* — and comparing today's numbers against a table generated weeks ago answers it with two machines in a mood rather than two versions. `npm run bench:compare` runs both trees on one box in one sitting, alternating sides; `26.9.0-beta.1 → 26.9.0-beta.2` came out flat on every case.
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
@@ -285,7 +288,9 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built.
**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 became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `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
+270
View File
@@ -0,0 +1,270 @@
/**
* Compares green-tea against an earlier green-tea, on one box, in one sitting.
*
* `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release
* actually has to pass: **did the last N commits cost anything.** It is a different measurement and
* it needs a different setup, because comparing today's numbers against a table generated weeks ago
* compares two machines-in-a-mood, not two versions.
*
* Usage:
*
* git worktree add /tmp/base v26.8.0-beta.1
* ln -s "$PWD/node_modules" /tmp/base/node_modules
* AB_BASE=/tmp/base npm run bench:compare
*
* The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has
* not moved between the two revisions — check that first, or the comparison is measuring a
* dependency bump.
*
* Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100),
* `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json).
*/
import autocannon from 'autocannon';
import { spawn } from 'child_process';
import { writeFileSync } from 'fs';
const DURATION = Number(process.env.AB_DURATION ?? 10);
const ROUNDS = Number(process.env.AB_ROUNDS ?? 3);
const CONNS = Number(process.env.AB_CONNS ?? 100);
const HEAD = process.cwd();
// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables.
const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare';
const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare';
function requireBase(): string {
const base = process.env.AB_BASE;
if (base) return base;
console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.');
process.exit(1);
}
const BASE = requireBase();
interface Case {
name: string;
path: string;
method?: 'GET' | 'POST' | 'OPTIONS';
body?: unknown;
headers?: Record<string, string>;
env?: Record<string, string>;
}
const ORIGIN = { origin: 'http://bench.example' };
const CASES: Case[] = [
{ name: 'hello', path: '/hello' },
{ name: 'param', path: '/users/42' },
{ name: 'pipeline (3 steps)', path: '/pipeline' },
{ name: 'steps5', path: '/steps/5' },
{ name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } },
{ name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } },
// The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets
// the header measures the path around it rather than the path through it.
{ name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN },
{
name: 'preflight + cors predicate',
path: '/hello',
method: 'OPTIONS',
env: { GT_CORS: '1' },
headers: { ...ORIGIN, 'access-control-request-method': 'GET' },
},
// Route-table width. Every matcher cost scales with the number of candidates a request walks
// past, and the cross-framework table has six routes — so a change that saves work per candidate
// measures as noise there no matter how real it is. `/users/:id` is registered last and is not
// all-static, so it takes the full scan rather than the early exit a literal path gets.
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
];
const ONLY = process.env.AB_ONLY;
const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES;
function log(m: string): void {
process.stderr.write(`[compare] ${m}\n`);
}
async function boot(cwd: string, env: Record<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], {
cwd,
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env },
});
let stderr = '';
child.stderr.on('data', (d) => (stderr += d));
const port = await new Promise<number>((resolve, reject) => {
const t = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error(`no READY in 15s:\n${stderr}`));
}, 15000);
let buf = '';
child.stdout.on('data', (d) => {
buf += d;
const m = /READY (\d+)/.exec(buf);
if (m) {
clearTimeout(t);
resolve(Number(m[1]));
}
});
child.on('exit', (c) => {
clearTimeout(t);
reject(new Error(`exited ${c}:\n${stderr}`));
});
});
const kill = (): Promise<void> =>
new Promise<void>((r) => {
child.on('exit', () => r());
child.kill('SIGTERM');
setTimeout(() => {
try {
child.kill('SIGKILL');
} catch {
/* already dead */
}
}, 2000);
});
return { port, kill };
}
async function hit(port: number, c: Case, warmup = false): Promise<number> {
const r = (await autocannon({
url: `http://127.0.0.1:${port}${c.path}`,
connections: CONNS,
duration: DURATION,
pipelining: 1,
method: (c.method ?? 'GET') as 'GET',
headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers },
body: c.body ? JSON.stringify(c.body) : undefined,
})) as unknown as {
requests: { average: number };
non2xx?: number;
errors?: number;
timeouts?: number;
};
// A case whose route 404s still posts a req/s number, and a run whose connections all errored
// posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this
// case claims to send before believing any of it.
// Not on the warmup: a cold server drops a handful of connections from the opening burst, and
// absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise
// it exists to discard.
if (!warmup) {
const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0);
if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`);
if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`);
}
return r.requests.average;
}
const median = (xs: number[]): number => {
const s = [...xs].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
};
/**
* True when the two sides' sample ranges do not overlap at all.
*
* A weak signal on its own and stated as such: with three samples a pair of overlapping
* distributions separates by chance often enough to fool you, which it did the first time this was
* run. Treat a flagged row as "measure it again with more rounds", never as a result.
*/
const separated = (a: number[], b: number[]): boolean => {
const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)];
return x[0] > y[y.length - 1] || y[0] > x[x.length - 1];
};
/**
* Counts `cors.origins` invocations for one cross-origin GET and one preflight.
*
* Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved
* are invisible in req/s — but the option takes a function so it can be a lookup, and there the
* same saving is a network round trip.
*/
async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> {
const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server);
const base = `http://127.0.0.1:${port}`;
// The read carries no `Origin`, so asking cannot change the answer.
const read = async (): Promise<number> => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls;
try {
const before = await read();
await fetch(`${base}/hello`, { headers: ORIGIN });
const afterGet = await read();
await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } });
const afterPreflight = await read();
return { get: afterGet - before, preflight: afterPreflight - afterGet };
} finally {
await kill();
}
}
async function main(): Promise<void> {
const samples: Record<string, { base: number[]; head: number[] }> = {};
for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] };
for (let round = 0; round < ROUNDS; round++) {
// Alternate which side goes first. Thermal drift and background load over a half-hour run are
// real; alternating spreads them across both sides instead of charging them to whichever went
// second.
const order: Array<['base' | 'head', string]> =
round % 2 === 0
? [
['base', BASE],
['head', HEAD],
]
: [
['head', HEAD],
['base', BASE],
];
for (const [side, cwd] of order) {
for (const c of RUN_CASES) {
const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER);
try {
await hit(port, c, true); // warmup, discarded
const v = await hit(port, c);
samples[c.name][side].push(v);
log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`);
} finally {
await kill();
}
}
}
}
const rows = RUN_CASES.map((c) => {
const b = median(samples[c.name].base);
const h = median(samples[c.name].head);
return {
name: c.name,
base: b,
head: h,
delta: ((h - b) / b) * 100,
separated: separated(samples[c.name].base, samples[c.name].head),
samples: samples[c.name],
};
});
const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) };
writeFileSync(
process.env.AB_OUT ?? 'bench/compare-results.json',
JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2),
);
const f = (n: number): string => Math.round(n).toLocaleString();
console.log('\n| Scenario | base | head | Δ | |');
console.log('| --- | --- | --- | --- | --- |');
for (const r of rows) {
const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps';
console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`);
}
console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`);
console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+31 -1
View File
@@ -37,6 +37,8 @@ export interface RenderData {
scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; reqSec: number }[];
/** Optional: results captured before the runtime matrix existed still render. */
runtimes?: { runtime: string; scenario: string; reqSec: number }[];
}
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
@@ -124,6 +126,33 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
}
/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */
function renderRuntimes(runtimes: RenderData['runtimes']): string {
if (!runtimes?.length) return '';
const names = [...new Set(runtimes.map((row) => row.runtime))];
const scenarios = [...new Set(runtimes.map((row) => row.scenario))];
const at = (runtime: string, scenario: string): number | undefined =>
runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec;
const header = `| Scenario | ${names.join(' | ')} |`;
const divider = `| --- | ${names.map(() => '---').join(' | ')} |`;
const lines = scenarios.map((scenario) => {
const cells = names.map((runtime) => {
const value = at(runtime, scenario);
return value === undefined ? '—' : fmtInt(value);
});
return `| ${scenario} | ${cells.join(' | ')} |`;
});
const note =
'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' +
'never against the cross-framework tables above: those measure other frameworks on Node, and ' +
'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.';
return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n');
}
function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |';
const divider = '| --- | --- |';
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
}
export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data;
const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
return [
renderLeaderboard(scenarios),
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
'',
renderScenarios(scenarios),
renderStepScaling(stepScaling),
renderRuntimes(runtimes),
renderSecureCost(secureCost),
renderMethodology(),
].join('\n');
+266 -204
View File
@@ -1,17 +1,17 @@
{
"env": {
"date": "2026-07-07",
"commit": "fe1831a",
"date": "2026-09-22",
"commit": "daf0fed",
"node": "v22.22.2",
"os": "darwin",
"cpu": "Apple M4 Max (16 cores)",
"ram": "69 GB",
"os": "linux",
"cpu": "AMD Ryzen 7 3700X 8-Core Processor (16 cores)",
"ram": "67 GB",
"pinned": false
},
"config": {
"conns": 100,
"duration": 5,
"runs": 3,
"duration": 10,
"runs": 5,
"warmup": 1,
"pipelining": 1
},
@@ -23,80 +23,80 @@
{
"framework": "raw-http",
"reqSec": {
"median": 115398.4,
"min": 114822.4,
"max": 115539.2,
"stddev": 310.09010876768724,
"cv": 0.0026905088104554075
"median": 41630.55,
"min": 41342.55,
"max": 41973.82,
"stddev": 232.79156158245826,
"cv": 0.0055977118567263305
},
"p50": 0,
"p99": 1,
"p999": 1
"p50": 2,
"p99": 3,
"p999": 4
},
{
"framework": "fastify",
"reqSec": {
"median": 86764.8,
"min": 86496,
"max": 87123.2,
"stddev": 256.9227813090051,
"cv": 0.002960121758353106
"median": 32170.19,
"min": 31235.64,
"max": 32355.64,
"stddev": 403.36620390905324,
"cv": 0.012593571579786219
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 3,
"p999": 5
},
{
"framework": "express",
"reqSec": {
"median": 24366.4,
"min": 24283.2,
"max": 24417.6,
"stddev": 55.38455460585383,
"cv": 0.002273984274990166
"median": 10545.82,
"min": 10480.37,
"max": 10625.1,
"stddev": 47.02831087759791,
"cv": 0.004456044641032285
},
"p50": 3,
"p99": 5,
"p999": 8
"p50": 8,
"p99": 13,
"p999": 18
},
{
"framework": "green-tea",
"reqSec": {
"median": 98092.8,
"min": 98054.4,
"max": 98668.8,
"stddev": 281.0175795212842,
"cv": 0.002859589501804015
"median": 29776.73,
"min": 29557.1,
"max": 29872.73,
"stddev": 120.92248317000461,
"cv": 0.004066812850878315
},
"p50": 0,
"p99": 1,
"p999": 2
"p50": 3,
"p99": 6,
"p999": 7
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 21761.6,
"min": 21697.6,
"max": 21896,
"stddev": 82.67870880032535,
"cv": 0.0037952010918943873
"median": 9679.64,
"min": 9566.91,
"max": 9738.55,
"stddev": 58.2951632985104,
"cv": 0.006025529205104781
},
"p50": 4,
"p99": 6,
"p999": 10
"p50": 9,
"p99": 15,
"p999": 21
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 95033.6,
"min": 94240,
"max": 95264,
"stddev": 438.6166536839312,
"cv": 0.00462452048886261
"median": 32418.91,
"min": 32103.28,
"max": 32582.55,
"stddev": 159.574135748874,
"cv": 0.004929287112917938
},
"p50": 1,
"p99": 1,
"p999": 2
"p50": 3,
"p99": 4,
"p999": 6
}
]
},
@@ -107,80 +107,80 @@
{
"framework": "raw-http",
"reqSec": {
"median": 116332.8,
"min": 115974.4,
"max": 116409.6,
"stddev": 189.66281191162406,
"cv": 0.001631663389130871
"median": 41755.64,
"min": 40952.73,
"max": 42017.46,
"stddev": 439.72294183496837,
"cv": 0.010587809774433589
},
"p50": 0,
"p99": 1,
"p999": 1
"p50": 2,
"p99": 3,
"p999": 4
},
{
"framework": "fastify",
"reqSec": {
"median": 86278.4,
"min": 86137.6,
"max": 86764.8,
"stddev": 268.69839349476365,
"cv": 0.003110165492522174
"median": 31708.37,
"min": 31359.28,
"max": 31846.55,
"stddev": 168.73300179869975,
"cv": 0.005328784944282288
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 4,
"p999": 5
},
{
"framework": "express",
"reqSec": {
"median": 23835.2,
"min": 23803.2,
"max": 24046.4,
"stddev": 107.89690552662897,
"cv": 0.004515472130491916
"median": 10375.64,
"min": 10364,
"max": 10452.73,
"stddev": 37.668132419858544,
"cv": 0.003621859193349617
},
"p50": 3,
"p99": 5,
"p999": 8
"p50": 9,
"p99": 12,
"p999": 17
},
{
"framework": "green-tea",
"reqSec": {
"median": 93433.6,
"min": 93152,
"max": 93612.8,
"stddev": 189.6628119116206,
"cv": 0.002030662686635119
"median": 28706.19,
"min": 28562.19,
"max": 29050.91,
"stddev": 166.92265315408858,
"cv": 0.005803163694455583
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 6,
"p999": 7
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 20955.2,
"min": 20948.8,
"max": 21201.6,
"stddev": 117.69157432317111,
"cv": 0.005594982425799189
"median": 9257.1,
"min": 9244,
"max": 9285.46,
"stddev": 16.97885461390117,
"cv": 0.0018327336012062287
},
"p50": 4,
"p99": 6,
"p999": 11
"p50": 10,
"p99": 15,
"p999": 21
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 89312,
"min": 89235.2,
"max": 89529.6,
"stddev": 124.68598780759793,
"cv": 0.001395338811201841
"median": 29880,
"min": 29744.73,
"max": 29961.46,
"stddev": 90.38256681462417,
"cv": 0.003027383166346
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 4,
"p999": 6
}
]
},
@@ -192,80 +192,80 @@
{
"framework": "raw-http",
"reqSec": {
"median": 113491.2,
"min": 112531.2,
"max": 114809.6,
"stddev": 933.9810324031724,
"cv": 0.008220892102882115
"median": 39896.73,
"min": 39847.28,
"max": 40440.73,
"stddev": 235.6558649726337,
"cv": 0.0058846766178520865
},
"p50": 0,
"p99": 1,
"p999": 1
"p50": 2,
"p99": 3,
"p999": 5
},
{
"framework": "fastify",
"reqSec": {
"median": 85024,
"min": 84512,
"max": 85177.6,
"stddev": 284.55819947576623,
"cv": 0.003351507726431956
"median": 31436.37,
"min": 31078.55,
"max": 31562.91,
"stddev": 185.21052212010017,
"cv": 0.005909263441314207
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 4,
"p999": 6
},
{
"framework": "express",
"reqSec": {
"median": 23950.4,
"min": 23902.4,
"max": 24011.2,
"stddev": 44.519758410046,
"cv": 0.0018585004345727763
"median": 10365.46,
"min": 10170.55,
"max": 10542.19,
"stddev": 129.83340146510884,
"cv": 0.01252603707960138
},
"p50": 3,
"p99": 5,
"p999": 8
"p50": 9,
"p99": 12,
"p999": 18
},
{
"framework": "green-tea",
"reqSec": {
"median": 84896,
"min": 84243.2,
"max": 85267.2,
"stddev": 423.2825796347192,
"cv": 0.004991414284012342
"median": 26838.55,
"min": 26783.28,
"max": 26872,
"stddev": 35.930271582608675,
"cv": 0.0013390899572667937
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 6,
"p999": 8
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 20824,
"min": 20804.8,
"max": 20878.41,
"stddev": 31.17605954717337,
"cv": 0.001496278247605678
"median": 9256.37,
"min": 9187.28,
"max": 9302.19,
"stddev": 42.180541200890175,
"cv": 0.0045584972844857205
},
"p50": 4,
"p99": 6,
"p999": 11
"p50": 10,
"p99": 15,
"p999": 22
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 87328,
"min": 86867.2,
"max": 87660.8,
"stddev": 325.38753646827104,
"cv": 0.0037278603866430907
"median": 29402.91,
"min": 29151.28,
"max": 29689.46,
"stddev": 189.99449229911926,
"cv": 0.006460862473261261
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 3,
"p99": 4,
"p999": 6
}
]
},
@@ -276,80 +276,80 @@
{
"framework": "raw-http",
"reqSec": {
"median": 100140.8,
"min": 99846.4,
"max": 100294.4,
"stddev": 185.88177843875883,
"cv": 0.0018570746103533369
"median": 31783.28,
"min": 31517.1,
"max": 31824.73,
"stddev": 111.5598838292694,
"cv": 0.003516116881358333
},
"p50": 0,
"p99": 1,
"p999": 2
"p50": 3,
"p99": 5,
"p999": 6
},
{
"framework": "fastify",
"reqSec": {
"median": 63721.6,
"min": 63574.4,
"max": 63760,
"stddev": 79.99288857281053,
"cv": 0.0012560645345785087
"median": 20429.82,
"min": 20397.82,
"max": 20601.46,
"stddev": 73.12471046096515,
"cv": 0.0035727493036941836
},
"p50": 1,
"p99": 2,
"p999": 3
"p50": 4,
"p99": 8,
"p999": 9
},
{
"framework": "express",
"reqSec": {
"median": 20097.6,
"min": 20056,
"max": 20174.41,
"stddev": 49.04789518646266,
"cv": 0.0024390608203285337
"median": 8440.37,
"min": 8407.64,
"max": 8492,
"stddev": 29.52737333390846,
"cv": 0.003496408589959768
},
"p50": 4,
"p99": 6,
"p999": 12
"p50": 11,
"p99": 16,
"p999": 24
},
{
"framework": "green-tea",
"reqSec": {
"median": 77177.61,
"min": 77126.4,
"max": 77254.4,
"stddev": 52.602458962379814,
"cv": 0.0006815013839797027
"median": 22005.1,
"min": 21736,
"max": 22186.91,
"stddev": 149.1731413626461,
"cv": 0.006790967759795645
},
"p50": 1,
"p99": 2,
"p999": 2
"p50": 4,
"p99": 7,
"p999": 9
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 18856,
"min": 18852.8,
"max": 19067.2,
"stddev": 100.32338821143516,
"cv": 0.005301010367660728
"median": 7666.37,
"min": 7645.28,
"max": 7703.46,
"stddev": 20.418688106732038,
"cv": 0.002662071942974812
},
"p50": 5,
"p99": 7,
"p999": 30
"p50": 12,
"p99": 18,
"p999": 26
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 59145.6,
"min": 59004.8,
"max": 59376,
"stddev": 153.00625985741647,
"cv": 0.002585636725423652
"median": 18596.8,
"min": 18540.37,
"max": 18658.19,
"stddev": 37.943211988443956,
"cv": 0.0020404741150848267
},
"p50": 1,
"p99": 3,
"p999": 3
"p50": 4,
"p99": 8,
"p999": 11
}
]
}
@@ -358,27 +358,89 @@
{
"path": "/steps/0",
"steps": 0,
"reqSec": 92281.6
"reqSec": 29196.37
},
{
"path": "/steps/3",
"steps": 3,
"reqSec": 81529.61
"reqSec": 26563.64
},
{
"path": "/steps/5",
"steps": 5,
"reqSec": 71993.61
"reqSec": 25314.19
}
],
"secureCost": [
{
"label": "security:false (parity)",
"reqSec": 98092.8
"reqSec": 29776.73
},
{
"label": "security:true (default)",
"reqSec": 92998.4
"reqSec": 28918.55
}
],
"runtimes": [
{
"runtime": "node",
"scenario": "JSON hello (overhead)",
"reqSec": 30378.91
},
{
"runtime": "node",
"scenario": "Route param",
"reqSec": 29203.64
},
{
"runtime": "node",
"scenario": "Pipeline (3 steps)",
"reqSec": 27208
},
{
"runtime": "node",
"scenario": "POST JSON + validation",
"reqSec": 22608.73
},
{
"runtime": "deno",
"scenario": "JSON hello (overhead)",
"reqSec": 51888
},
{
"runtime": "deno",
"scenario": "Route param",
"reqSec": 51785.6
},
{
"runtime": "deno",
"scenario": "Pipeline (3 steps)",
"reqSec": 50692.37
},
{
"runtime": "deno",
"scenario": "POST JSON + validation",
"reqSec": 35742.55
},
{
"runtime": "bun",
"scenario": "JSON hello (overhead)",
"reqSec": 46299.64
},
{
"runtime": "bun",
"scenario": "Route param",
"reqSec": 42788.37
},
{
"runtime": "bun",
"scenario": "Pipeline (3 steps)",
"reqSec": 39643.64
},
{
"runtime": "bun",
"scenario": "POST JSON + validation",
"reqSec": 31960
}
]
}
+78 -4
View File
@@ -1,17 +1,30 @@
import autocannon from 'autocannon';
import { spawn, execSync } from 'child_process';
import os from 'os';
import { writeFileSync } from 'fs';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
/** Hand-written notes start here and are carried across regenerations verbatim. */
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
const SMOKE = process.env.BENCH_SMOKE === '1';
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
/** Whether a runtime is on PATH. */
function which(cmd: string): boolean {
try {
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`);
}
@@ -23,11 +36,25 @@ interface RunResult {
p999: number;
}
/**
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
* are handed to their own runtime, which is the whole point of measuring them.
*/
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
// missing flag fails as a boot timeout that reads like a framework problem.
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
bun: (file) => ({ cmd: 'bun', args: [file] }),
};
async function spawnServer(
name: string,
extraEnv: Record<string, string> = {},
runtime: 'node' | 'deno' | 'bun' = 'node',
): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
const child = spawn(cmd, args, {
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
});
let stderr = '';
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
}));
const stepScaling: RenderData['stepScaling'] = [];
const secureCost: RenderData['secureCost'] = [];
const runtimes: RenderData['runtimes'] = [];
for (const fw of frameworks) {
log(`booting ${fw}`);
@@ -145,10 +173,49 @@ async function main(): Promise<void> {
}
}
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
// fastify-on-Node would read as a comparison nobody made.
//
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
// runtime is not installed — a contributor without Bun should still get every other table.
for (const { runtime, server } of [
{ runtime: 'node', server: 'green-tea-node' },
{ runtime: 'deno', server: 'green-tea-deno' },
{ runtime: 'bun', server: 'green-tea-bun' },
] as const) {
if (runtime !== 'node' && !which(runtime)) {
log(`skipping ${runtime}: not installed`);
continue;
}
log(`booting green-tea on ${runtime}`);
try {
const { port, kill } = await spawnServer(server, {}, runtime);
try {
for (const s of SCENARIOS) {
const runs = await measure(port, s.path, s.method, s.body);
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
}
} finally {
await kill();
}
} catch (error) {
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
// of the run over.
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
}
}
const commit = execSync('git rev-parse --short HEAD').toString().trim();
const data: RenderData = {
env: {
date: new Date().toISOString().slice(0, 10),
// Project time, not the runner's. A benchmark is often driven over ssh against a box that
// keeps UTC, and a run made on the evening of the 22nd then dates itself the 23rd — which
// reads as a day of drift against the commit and the changelog entry beside it.
date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }),
commit,
node: process.version,
os: os.platform(),
@@ -160,8 +227,15 @@ async function main(): Promise<void> {
scenarios: scenarioBlocks,
stepScaling,
secureCost,
runtimes,
};
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
// Everything below the marker is written by hand and survives a re-run. The generated tables
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
// history this file exists to keep gets lost a second time.
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
log('wrote BENCHMARKS.md + bench/results.json');
}
+61
View File
@@ -0,0 +1,61 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+84
View File
@@ -0,0 +1,84 @@
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
// secure-by-default headers, and a `cors.origins` predicate.
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
type Ctor = new (...args: any[]) => any;
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
// change what it reports.
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
}
// Filler routes, so the width of the route table becomes a dimension the harness can see.
//
// Every matcher cost discussed for this file — the specificity scan, the per-candidate
// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate
// routes a request has to walk past. At the six routes the cross-framework table uses, all of them
// measure as noise, which says nothing about them and everything about the instrument. `/users/:id`
// is declared last so a request for it pays the full scan.
function fillerRoutes(count: number): Ctor[] {
return Array.from({ length: count }, (_, i) => {
@Route(`/filler${i}`)
class Filler {
@Get('/:a/:b') ab(@param('a') a: string) {
return { a };
}
}
return Filler as Ctor;
});
}
const EXTRA = Number(process.env.GT_ROUTES ?? 0);
@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] })
class BenchModule {}
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
// one this release stopped evaluating two and three times per request.
const ALLOWED = new Set(['http://bench.example']);
let corsCalls = 0;
const cors =
process.env.GT_CORS === '1'
? {
origins: (o: string) => {
corsCalls++;
return ALLOWED.has(o);
},
}
: undefined;
const app = createApp({
modules: [BenchModule],
security: process.env.GT_SECURE === '1',
...(cors ? { cors } : {}),
});
async function main() {
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+1 -1
View File
@@ -30,5 +30,5 @@ class Bench {
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' });
const server = await serveBun(app, { port: 0, hostname: '0.0.0.0' });
console.log(`READY ${server.port}`);
+1 -1
View File
@@ -30,4 +30,4 @@ class Bench {
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
await serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
+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);
});
+10 -1
View File
@@ -1,5 +1,14 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true },
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true,
// The bench servers are ES modules, run by tsx, Deno and Bun rather than by the CommonJS build
// the root config describes. `serveDeno`/`serveBun` became async in 26.9.0-beta.2, so two of
// them now open with a top-level `await`, which `module: commonjs` rejects outright.
"module": "es2022",
"moduleResolution": "bundler"
},
"include": ["."]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.1",
"version": "26.9.0-beta.2",
"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
@@ -64,6 +64,13 @@ instead of a boot manifest.
(`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.
**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped
exporting providers — with nothing cached between requests, there is nothing left to invalidate.
This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the
*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the
seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts.
## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
@@ -85,6 +85,12 @@ not a wait for `timeoutMs`.
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.
**Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the
remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback went with that — there is no cached value left to invalidate, so a
reconnected link is simply usable again on the next RPC. The rest of this plan shipped as
written; only this step has no counterpart in the code.
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
@@ -0,0 +1,710 @@
# A mesh that exports steps, not providers
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or
> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking.
**Status:** planned, 2026-09-06
**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`,
mesh tests on all runtimes, `README.md`, `CHANGELOG.md`
**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a
protocol bump because of it.
**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error,
and a teapot that is unreachable at boot no longer stops the teacup from starting.
## The problem
`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot
cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses
any class instance, so an exported provider can only ever return plain data. What survives is the
worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope**
binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the
process. It is a cache the teapot no longer stands behind, wearing the word "provider".
A step is the shape that actually works across the mesh. It runs per request, the teacup sends the
envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to
the token. Transparent to the caller, and nothing is held.
Two things follow from that, and they are the whole of this plan:
1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative
already exists and is spelled `@Step({ export: true })`.
2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value
has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is
away costs a `503` on the requests that need it, and the app starts.
## Decisions
**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a
warning would leave a running app whose token resolves locally and looks exported. The error names
the replacement, so the message is a fix and not a complaint.
**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in
`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`,
both peers ship from this repo, and a bump would spend the number on a version nobody deployed.
`MESH_PROTOCOL_VERSION` stays `1`.
**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the
design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The
loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the
manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots
into a graph with no `authorization` node, which is strictly worse than today. So the budget stays;
exhausting it now warns and contributes nothing, instead of failing the boot.
**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a
protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and
they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at
3am that says nothing about a secret. Only *unreachable* becomes non-fatal.
**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away
and a local step declares `needs: ['authorization']`, `topoSort` throws
`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to
remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and
`503` forever. The message gains the teapots that did not connect, so the cause is on the screen.
**D6 — The `expects` / degrade plan survives; its D6 does not.**
`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may
legitimately be absent", and it is already steps-only. But its D6 reuses
`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded
step swaps a runner, not a container binding. Note it there rather than leave a dangling reference.
## File structure
| File | Change |
| --- | --- |
| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row |
| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` |
| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` |
| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error |
| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal |
| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` |
| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 |
## A note on the line numbers
Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol —
`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph`
— and treat the numbers as hints.
---
## Task 1: Forbid exporting a provider
The prohibition lands first and alone, because every later task assumes it. Nothing on the wire
changes yet.
**Files**
- Modify: `src/app/index.ts:440` (`collectProviders`)
- Test: `test/mesh/failure.test.ts`
- [ ] **Step 1: Write the failing test**
```ts
// test/mesh/failure.test.ts
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Module } from '../../src/index';
describe('provider export', () => {
it('refuses to boot when a provider is exported over the mesh', async () => {
@Provider({ provides: 'db', needs: [], export: true } as any)
class Db {
provide() {
return { db: { query: () => [] } };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class AppModule {}
expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow(
/provider 'db' cannot be exported/i,
);
});
});
```
- [ ] **Step 2: Run it and watch it fail**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: FAIL — no error is thrown, the app builds.
- [ ] **Step 3: Throw in `collectProviders`**
Replace `src/app/index.ts:440`:
```ts
if (meta.export) registry.exportedProviders.push(meta.provides);
```
with:
```ts
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
// resolved once and cached for the life of the process. A step is the shape that travels:
// it runs per request, on the teapot, and only its result comes back.
if (meta.export)
throw new Error(
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
```
- [ ] **Step 4: Run it and watch it pass**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: PASS.
- [ ] **Step 5: Fix every test that exported a provider**
```bash
npx vitest run test/mesh/
```
Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`.
Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`,
`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/
git commit -m "feat(mesh)!: refuse to export a provider
A provider's value is the object it builds, which cannot cross a JSON wire.
What did cross became an app-scope binding the teacup resolved once at boot
and served from a cache the teapot no longer stood behind. A step is the
shape that travels; the error says so."
```
---
## Task 2: A manifest of steps and routes
**Files**
- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`)
- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent)
- Modify: `src/mesh/teacup.ts` (`buildRemote`)
- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison)
- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts`
**Interfaces**
- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }`
- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest`
- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }`
- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/protocol.test.ts
it('encodes a manifest of step names', () => {
const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }));
expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] });
});
it('rejects a manifest whose steps are not an array', () => {
expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow(
/steps and routes must be arrays/,
);
});
```
```ts
// test/mesh/teapot.test.ts
it('builds a manifest from step tokens and routes', () => {
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
steps: ['auth'],
routes: [{ method: 'GET', pattern: '/u/:id' }],
});
});
```
```ts
// test/mesh/teacup.test.ts
it('turns every manifest step into a lazy remote node', async () => {
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
const { steps, routes } = buildRemote(link);
expect(routes).toEqual([]);
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
});
```
- [ ] **Step 2: Run them and watch them fail**
```bash
npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts
```
Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`.
- [ ] **Step 3: Change the protocol**
In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface:
```ts
/**
* A mesh server's advertised steps and routes.
*
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
* lazy — the token exists in the teacup's graph, and running it is an RPC.
*/
export interface Manifest {
steps: string[];
routes: RouteEntry[];
}
```
In the `Frame` union, replace the `manifest` member:
```ts
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
```
And its `SHAPE` row:
```ts
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
},
```
Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still
carry a `Date` or a `Map`.
- [ ] **Step 4: Change `buildManifest`**
In `src/mesh/teapot.ts`, replace the function at `:43-56`:
```ts
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
return { steps: [...args.steps], routes: args.routes };
}
```
Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends
`steps: manifest.steps` in place of `scopes: manifest.scopes`.
The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3
— a task must leave the tree typechecking, and splitting a signature from its only call site across
two commits leaves a broken commit in history:
```ts
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field.
- [ ] **Step 5: Change `buildRemote`**
In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`):
```ts
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
name: token,
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
}));
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method,
pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
}));
return { steps, routes };
}
```
The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and
`resolveScope` on the teapot side resolves both the same way.
- [ ] **Step 6: Update the refuse policy in `link.ts`**
Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it:
a returned manifest must still contain every step token the link contributed at boot, and every
route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect
plan).
- [ ] **Step 7: Typecheck, then run the mesh suite**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl`
call site was missed.
- [ ] **Step 8: Commit**
```bash
git add src/mesh/ test/mesh/
git commit -m "refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one
value and told a reader nothing. No protocol bump: mesh is alpha, both
peers ship from this repo, and the number should mean incompatibility
between deployed versions."
```
---
## Task 3: The teacup stops splicing providers
**Files**
- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`)
- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`)
- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`)
- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`)
- Test: `test/mesh/integration.test.ts`
- [ ] **Step 1: Write the failing test**
This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })`
(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made
that fixture fail at boot, so converting it is not optional — and converting it is the regression
guard, because a step re-runs where the provider was cached:
```ts
// test/mesh/integration.test.ts — replaces the @Provider fixture at :6
let configCalls = 0;
@Step({ provides: 'config', needs: [], export: true })
class Config {
run() {
configCalls += 1;
return { config: { region: 'mx', call: configCalls } };
}
}
```
and add, alongside the existing `/local/who` assertion:
```ts
it('re-runs the RPC on every request rather than caching a boot value', async () => {
// same teapot/teacup pair the '/local/who' test stands up
expect((await hit('/api/local/who')).config.call).toBe(1);
expect((await hit('/api/local/who')).config.call).toBe(2);
});
```
- [ ] **Step 2: Run it — it should already pass, and that is the point**
```bash
npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC'
```
Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable
through provider export, which Task 1 made impossible — once `config` is a step it lands in the
request-scope bucket and already re-runs. The guard exists so that removing the splice in the next
steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it.
- [ ] **Step 3: Delete `exportedProviders`**
Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In
`buildMeshControl` (`:1078-1088`):
```ts
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
// ...
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
- [ ] **Step 4: Delete the remote-provider splice**
In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls
`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block
(`:846-856`). Destructure only what is left:
```ts
const { steps, routes } = buildRemote(link);
```
Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter
from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and
nowhere else in the function.
The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between
requests, so a reconnected link is simply usable again on the next RPC.
- [ ] **Step 5: Run the full suite and the typechecker**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS, and no unused-symbol errors.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/mesh/
git commit -m "refactor(mesh): drop the remote app-scope binding and its rebind seam
A remote provider was registered app-scope, resolved once, and cached for
the process lifetime; invalidateRemoteBindings existed only to un-cache it
on reconnect. With providers gone from the manifest, both go, and a remote
step needs nothing on reconnect because it holds nothing between requests."
```
---
## Task 4: An unreachable teapot does not stop the boot
**Files**
- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`)
- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`)
- Modify: `src/graph.ts:54` (the missing-dependency message)
- Test: `test/mesh/boot-retry.test.ts`
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/boot-retry.test.ts
it('boots when a teapot is unreachable and nothing local needs it', async () => {
const app = createApp({
modules: [LocalOnlyModule], // declares no needs on a remote token
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).resolves.toBeUndefined();
});
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
const app = createApp({
modules: [NeedsAuthModule], // a step with needs: ['auth']
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
});
it('still fails the boot when the teapot refuses the secret', async () => {
// stand up a teapot with secret 'right', connect with 'wrong'
await expect(app.ready()).rejects.toThrow(/refused/i);
});
```
- [ ] **Step 2: Run them and watch the first two fail**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message
(it says `missing dependency: auth` with no mention of the teapot), the third passes already.
- [ ] **Step 3: Make budget exhaustion non-fatal**
In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the
permanent-refusal `throw` (D4). Change the return type to `Promise<Link | undefined>` and replace
the exhaustion branch:
```ts
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// proxied route now, so an absent teapot costs a 503 on the requests that need it — and a
// teacup that refuses to start takes down the half of itself that never needed the teapot.
if (remaining <= 0) {
logger.warn(
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it; its steps and routes will 503`,
);
return undefined;
}
```
In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url:
```ts
const link = await connectUntilDeadline(/* … */);
if (!link) {
absent.push(teapot.url);
continue;
}
```
Return `absent` alongside `remoteRoutes` and `meshLinks`.
- [ ] **Step 4: Name the absent teapots in the missing-dependency error**
`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note
instead of mesh knowledge — note the capital S, and that `seedKeys` stays second:
```ts
// src/graph.ts:46
export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] {
```
and at the throw (`src/graph.ts:54`):
```ts
throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`);
```
The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its
signature rather than reaching for a module-level variable:
```ts
// src/app/index.ts:654 — finalizeGraph gains a trailing optional param
function finalizeGraph(
registry: Registry,
logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: (key: string) => string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
```
`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`:
```ts
// Without this the error is `missing dependency: auth needed by getUser` and says nothing about
// the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = absent.length
? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}`
: undefined;
```
The note is unconditional on the key rather than per-token on purpose: the teacup does not know
which teapot *would* have owned a token it never received a manifest for, and guessing would put a
wrong url in an error. Listing the ones that were away is true and enough.
- [ ] **Step 5: Run them and watch them pass**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: PASS, all three.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts
git commit -m "feat(mesh): an unreachable teapot no longer stops the teacup from booting
Blocking existed for app-scope exports, which have to resolve at boot
because there is no later. Steps and proxied routes are all later. The
grace budget stays -- a co-deploy still waits -- but exhausting it now
warns instead of throwing. A missing token still fails the boot, and the
error now names the teapots that were away."
```
---
## Task 5: The other runtimes
`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and
`src/app/index.ts` — exactly the code AGENTS.md says to run them for.
**Files**
- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`,
`test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts`
- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`
- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step**
```bash
grep -rn "export: true" test/deno test/bun test/interop test/edge
```
- [ ] **Step 2: Run each runtime suite**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a
mismatch here means one side was missed.
- [ ] **Step 3: Commit**
```bash
git add test/
git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge"
```
---
## Task 6: Say it in the docs
**Files**
- Modify: `README.md` (mesh section)
- Modify: `CHANGELOG.md` (`[Unreleased]`)
- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6)
- [ ] **Step 1: README**
In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails
at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`;
a missing token still fails the boot, and that is deliberate.
- [ ] **Step 2: CHANGELOG**
Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag
ships, never earlier.
```markdown
### Changed
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
at boot. A provider's value is the object it builds, which cannot cross a JSON wire; what did
cross became an app-scope binding the teacup resolved once and cached for the life of the
process. Export a `@Step` instead — it runs on the teapot per request and returns its result.
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The
`bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without
that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still
fails the boot, and the error names the teapots that did not connect.
- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump,
which alpha permits and a stable version would not.
```
- [ ] **Step 3: Note the broken seam in the degrade plan**
Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a
runner, not a container binding.
- [ ] **Step 4: The full gate**
```bash
npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check
npm run test:deno && npm run test:bun && npm run test:edge
```
- [ ] **Step 5: Commit**
```bash
git add README.md CHANGELOG.md docs/plans/
git commit -m "docs(mesh): steps and routes are what a teapot exports"
```
---
## Size
Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new
subsystem, no new configuration, no background loop. The risk is not in the code but in the wire —
both peers change at once, which alpha allows and which the runtime suites are there to prove.
## Branch
From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes.
```bash
git fetch origin && git checkout -b feat/mesh-steps-only origin/develop
```
+9 -6
View File
@@ -31,8 +31,11 @@ class UserController {
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const logger: Plugin = (api) => {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
const logger: Plugin = {
name: 'step-logger',
mount(api) {
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
},
};
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
@@ -75,9 +78,9 @@ if (require.main === module) {
// ── Mesh Demo (teapot / teacup) ───────────────────────────────────────────
@Provider({ provides: 'config', export: true })
class ConfigProvider {
provide() {
@Step({ provides: 'config', needs: [], export: true })
class ConfigStep {
run() {
return { config: { env: 'demo' } };
}
}
@@ -98,7 +101,7 @@ class PingController {
}
}
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
@Module({ mountpoint: '/mesh', steps: [ConfigStep, AuthStep], controllers: [PingController] })
class TeapotModule {}
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.9.0-beta.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.9.0-beta.2",
"license": "MIT",
"dependencies": {
"reflect-metadata": "0.2.2"
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.1",
"version": "26.9.0-beta.2",
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
@@ -102,6 +102,7 @@
"complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
"bench": "tsx bench/run.ts",
"bench:compare": "tsx bench/compare.ts",
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true"
},
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// Prints one version's section of CHANGELOG.md, for a GitHub release body.
//
// Reads the current file rather than the tag's copy on purpose: the changelog is the record, so a
// correction to an old entry should reach the release that describes it.
//
// Usage: node scripts/changelog-section.mjs <version> [tag]
// The optional tag makes relative links absolute — a release body resolves them against the release
// page, not the repository, and pinning to the tag keeps the link on the file as that version had it.
import { readFileSync } from 'node:fs';
const REPO = 'Expressive-Tea/green-tea';
const [version, tag] = process.argv.slice(2);
if (!version) {
console.error('usage: changelog-section.mjs <version> [tag]');
process.exit(2);
}
const lines = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8').split('\n');
const isHeading = (l) => l.startsWith('## [');
// The `[label]: url` block at the bottom of the file belongs to no section. Without this the last
// section swallows it, since nothing else comes after.
const isLinkRef = (l) => /^\[[^\]]+\]:\s+\S/.test(l);
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
if (start === -1) {
console.error(`no section for ${version}. Headings in CHANGELOG.md:\n${lines.filter(isHeading).join('\n')}`);
process.exit(1);
}
const rest = lines.slice(start + 1);
const stop = rest.findIndex((l) => isHeading(l) || isLinkRef(l));
const body = (stop === -1 ? rest : rest.slice(0, stop)).join('\n').trim();
const absolute = tag
? body.replace(/\]\(\.\/([^)\s]+)\)/g, `](https://github.com/${REPO}/blob/${tag}/$1)`)
: body;
console.log(absolute);
+282 -104
View File
@@ -1,8 +1,8 @@
import type http from 'http';
import { Bus } from '../bus';
import { Bus, type Events } from '../bus';
import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
@@ -13,6 +13,7 @@ import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import { installSignalHandlers } from '../http/signals-shutdown';
import type { Hooks } from './types';
import {
Ctor,
@@ -40,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
type Runner = (ctx: any) => any;
@@ -58,10 +59,9 @@ interface Registry {
*/
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
routePlans: RoutePlan[];
exportedProviders: string[];
exportedSteps: string[];
exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void;
setRunner(name: string, runner: Runner, framework?: boolean): void;
}
/**
@@ -85,6 +85,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus;
onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
}
/**
@@ -139,6 +141,25 @@ export function createApp(opts: {
* 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).
*
@@ -188,7 +209,7 @@ export function createApp(opts: {
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger);
provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph.
@@ -200,8 +221,8 @@ export function createApp(opts: {
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const finalize = (): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth));
const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
booted = true;
};
@@ -209,7 +230,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -217,10 +238,15 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks);
finalize();
// Without this the error is `missing dependency: auth needed by getUser` and says nothing
// about the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = spliced.absent.length
? ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}`
: undefined;
finalize(meshNote);
}
meshControl = buildMeshControl(opts.mesh, registry, {
@@ -274,6 +300,7 @@ export function createApp(opts: {
const fetchOpts: HttpOptions = {
bus,
logger,
limits: opts.limits,
tls: opts.tls,
trustProxy: opts.trustProxy,
@@ -285,7 +312,7 @@ export function createApp(opts: {
};
const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
@@ -305,6 +332,7 @@ export function createApp(opts: {
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
bus,
logger,
limits: opts.limits,
streams,
tls: opts.tls,
@@ -317,16 +345,54 @@ export function createApp(opts: {
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
// After the socket is up, so a boot that throws never leaves a handler behind pointing at an
// app that never served.
handleSignals(close);
return server;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs);
// Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is
// load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app
// that closed itself and expected to exit would simply hang.
let removeSignalHandlers: (() => void) | undefined;
const clearSignalHandlers = (): void => {
removeSignalHandlers?.();
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
return closeApp(
server,
meshLinks,
streams,
options,
opts.shutdownTimeoutMs,
logger,
teardown,
opts.teardownTimeoutMs,
);
};
const handleSignals = <T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T => {
if (!opts.handleSignals) return closer;
const wrapped = ((options?: { timeoutMs?: number }) => {
clearSignalHandlers();
return closer(options);
}) as T;
removeSignalHandlers = installSignalHandlers(() => wrapped(), logger);
return wrapped;
};
return {
listen,
close,
handleSignals,
ready,
boot: bootApp,
fetch: fetchFn,
upgrade: upgradeFn,
inspect,
@@ -345,7 +411,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn
const setRunner = (name: string, runner: Runner) => {
const setRunner = (name: string, runner: Runner, framework = false) => {
if (!framework && RESERVED_TOKENS.has(name))
throw new Error(
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
);
if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner);
@@ -358,7 +429,6 @@ function emptyRegistry(): Registry {
providerMeta: new Map(),
providerInstances: new Map(),
routePlans: [],
exportedProviders: [],
exportedSteps: [],
exportedRoutes: [],
setRunner,
@@ -371,7 +441,16 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
const meta = getProviderMeta(ProviderClass)!;
registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides);
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
// resolved once and cached for the life of the process. A step is the shape that travels:
// it runs per request, on the teapot, and only its result comes back.
if (meta.export)
throw new Error(
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
@@ -522,8 +601,19 @@ function buildTeardownRegistry(
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
// The name is the plugin's identity in `plugin:mounted` and in a mount failure, so two of them
// make both ambiguous. Two instances of one plugin are legitimate — they differ by `provides`,
// and the convention derives the name from it (.specs/2026-09-15, rule 2).
const seen = new Set<string>();
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
for (const plugin of plugins ?? []) {
if (seen.has(plugin.name)) {
throw new Error(`two plugins are named "${plugin.name}" — pass a different \`provides\` to one of them`);
}
seen.add(plugin.name);
mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
}
for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -534,22 +624,46 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
}
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry, logger: Logger): void {
/**
* Token names the framework owns. Declaring one is a boot error, not a silent override.
*
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
* That is the kind of thing that is discovered from a log line that never appeared.
*
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
*/
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
const builtin = (name: string, value: () => Record<string, unknown>): void => {
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
registry.providerMeta.set(name, { optional: false });
registry.setRunner(name, value, true);
};
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
// same object createApp holds, not a second one — core cannot depend on the graph for something
// it must use while the graph is still resolving.
if (!registry.runners.has('logger')) {
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
registry.providerMeta.set('logger', { optional: false });
registry.setRunner('logger', () => ({ logger }));
}
builtin('logger', () => ({ logger }));
if (registry.runners.has('rooms')) return;
const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
builtin('rooms', () => ({ rooms: roomsInstance }));
// The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
// not one.
//
// A subscription is not like the other injectables, and the difference is the scope that reaches
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
// `on` and `onShutdown` together, remains the right home for observation.
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
}
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -565,9 +679,10 @@ function finalizeGraph(
registry: Registry,
logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
const orderedSteps = ordered.filter((node) => stepNodes.includes(node));
const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins)
@@ -592,12 +707,24 @@ function finalizeGraph(
}
}
assertNeedsSatisfiable(routePlans, providerNodes, stepNodes);
assertNeedsSatisfiable(routePlans, providerNodes, stepNodes, missingNote);
return { orderedProviders, orderedSteps };
}
/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */
function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void {
/**
* Throws if any route needs a key that nothing provides, suggesting the nearest match.
*
* `missingNote` arrives only from a mesh boot, and only when a teapot did not connect. It changes
* what the message can honestly claim: "local or connected mesh" instead of "local or mesh", since
* the exports of an absent teapot were never searched — and it appends which teapots those were,
* which is the actual cause every time it is the cause.
*/
function assertNeedsSatisfiable(
routePlans: RoutePlan[],
providerNodes: GraphNode[],
stepNodes: GraphNode[],
missingNote?: string,
): void {
const producedKeys = new Set<string>([
...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides),
@@ -607,9 +734,29 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) {
for (const need of plan.needs) {
if (allowed.has(need)) continue;
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
// news that it is not the same shape. Say why, where they are.
if (need === 'bus') {
throw new Error(
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
`that could reach it could also emit, and an observation channel anything can write to ` +
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
`which gets on() and onShutdown() together and is the right home for observation.`,
);
}
const hint = nearest(need, allowed);
// "local or mesh" claims the mesh was consulted and came up empty — true only when every
// teapot connected. When one didn't, say "connected mesh" instead so the message doesn't
// assert a search that never happened, and let missingNote name which teapots were away.
const scope = missingNote ? 'local or connected mesh' : 'local or mesh';
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 (${scope}) provides it` +
`${hint ? ` — did you mean '${hint}'?` : ''}${missingNote ?? ''}`,
);
}
}
@@ -620,20 +767,29 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
*
* 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.
*
* Exhausting the budget returns `undefined` rather than throwing (D4 keeps the one exception: a
* permanent refusal still does). Every export a teapot makes is lazy now — a request-scope step or
* a proxied route — so nothing needed this link resolved by boot, and a teacup that refuses to
* start takes down the half of itself that never needed the teapot.
*
* Returning `undefined` is not the same as degrading it. The caller registers nothing for a link it
* never got, because a teapot that did not connect sent no manifest and so nobody knows what it
* would have exported. Its routes 404 like any unregistered path, and a local node that needs one
* of its tokens still fails the boot in finalize(), named. Serving 503 for those tokens instead
* needs an `expects` declaration — see docs/plans/2026-08-18-mesh-degrade-plan.md, still planned.
*/
async function connectUntilDeadline(
mesh: MeshConfig,
bus: Bus,
logger: Logger,
url: string,
attempt: () => Promise<Link>,
): Promise<Link> {
): Promise<Link | undefined> {
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
const deadline = Date.now() + budgetMs;
let delay = 500;
@@ -650,20 +806,29 @@ async function connectUntilDeadline(
// 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}`);
logger.error(`mesh: teapot ${url} 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.
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// proxied route now, so nothing needed this link resolved by boot, and a teacup that refuses
// to start takes down the half of itself that never needed the teapot. What starting does NOT
// do is degrade the dependency: an absent teapot sent no manifest, so it contributes no nodes
// at all — its routes 404 and a local `needs` on its tokens still fails in finalize().
if (remaining <= 0) {
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`);
throw error;
logger.warn(
`mesh: teapot ${url} unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it. No manifest was ever exchanged, ` +
`so none of its steps or routes are in this graph: its routes 404 like any path that ` +
`was never registered, and the boot still fails if anything local needs one of its ` +
`tokens. This line is what a later 404 on one of its routes points back to.`,
);
return undefined;
}
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`,
`mesh: teapot ${url} 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);
@@ -691,38 +856,22 @@ function warnIfCleartext(url: string, logger: Logger): void {
);
}
/**
* 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 steps into the registry, and returns their routes. */
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
registry: Registry,
logger: Logger,
container: Container,
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
try {
for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger);
// Deferred so the reconnect callback can name this link's provider tokens, which are only
// known once its manifest arrives — the callback is registered before the link can drop.
const rebind: Array<() => void> = [];
const link = await connectUntilDeadline(mesh, bus, logger, () =>
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
connectLink({
url: teapot.url,
secret: teapot.secret,
@@ -730,25 +879,20 @@ async function spliceRemoteScopes(
heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange,
onReconnect: () => invalidateRemoteBindings(rebind),
logger,
bus,
}),
);
meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
for (const provider of providers) {
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
registry.providerMeta.set(provider.name, { optional: false });
registry.setRunner(provider.name, provider.run);
// A remote app-scope value is resolved once at boot and frozen into the container, so it
// would keep answering from a cache the teapot no longer stands behind. Re-registering
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
if (!link) {
absent.push(teapot.url);
continue;
}
meshLinks.push(link);
const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
for (const step of steps) {
registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin });
registry.setRunner(step.name, step.run);
@@ -817,7 +961,7 @@ async function spliceRemoteScopes(
throw err;
}
return { remoteRoutes, meshLinks };
return { remoteRoutes, meshLinks, absent };
}
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -832,8 +976,41 @@ function applyOverrides(overrides: Record<string, unknown> | undefined, registry
}
}
/** What a provider's boot produced: nothing to say, or the error it failed with. */
interface BootOutcome {
node: GraphNode;
error?: Error;
}
/** Boots one provider and registers its value. Never rejects — the caller decides what a failure means. */
async function bootProvider(
node: GraphNode,
deps: { runners: Map<string, Runner>; container: Container; bus: Bus },
): Promise<BootOutcome> {
const { runners, container, bus } = deps;
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
try {
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
bus.emit('boot:provider:ok', { name: node.name });
return { node };
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
return { node, error: error as Error };
}
}
/**
* Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn.
* Runs app-scoped providers level by level — concurrently within a level, sequentially between
* them; required failures abort, optional ones warn.
*
* The topo sort already proved nothing in a level can order anything else in it, so serializing a
* level only ever bought latency: an app paid the sum of its providers' boot times instead of its
* longest chain. Concurrency is the second thing the graph earns its users, after pruning, and the
* one a middleware chain structurally cannot offer.
*
* @returns The names of optional providers that failed and are running degraded (unregistered).
*/
async function bootProviders(
@@ -848,40 +1025,39 @@ async function bootProviders(
logger: Logger;
},
): Promise<string[]> {
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
const { providerMeta, providerInstances, teardown, logger } = deps;
const degraded: string[] = [];
for (const node of orderedProviders) {
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
for (const level of topoLevels(orderedProviders)) {
// Outcomes rather than rejections: a sibling that throws must not strand the ones that
// succeeded, or a provider that opened a pool would never get its dispose() registered.
const outcomes = await Promise.all(level.map((node) => bootProvider(node, deps)));
try {
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
container.register(node.name, 'app', () => value);
await container.resolve(node.name); // warm the cache
// Registered here, as it boots, rather than where it was collected. `orderedProviders` is
// topologically sorted, so registration order *is* boot order — and the registry running in
// reverse then gives dependants teardown before their dependencies for free, with no second
// sort to keep in step with this one.
//
// Inside the try 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.
// Teardown in level order, not completion order. `orderedProviders` is topologically sorted and
// the registry runs in reverse, which is what gives dependants teardown before their
// dependencies for free — a guarantee that would have become luck if this followed whichever
// provider happened to settle first. Registered before the failure pass so a level that aborts
// the boot still leaves its successful siblings closeable.
//
// Skipped for a failure on purpose: a provider that threw never provided anything, and calling
// dispose() on a half-constructed one is how a teardown finds a null connection.
for (const { node, error } of outcomes) {
if (error) continue;
const instance = providerInstances.get(node.name);
if (instance?.dispose) teardown.add(() => instance.dispose!());
bus.emit('boot:provider:ok', { name: node.name });
} catch (error) {
bus.emit('boot:provider:fail', { name: node.name, error });
}
for (const { node, error } of outcomes) {
if (!error) continue;
if (!providerMeta.get(node.name)?.optional) {
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
throw new Error(`provider '${node.name}' failed: ${error.message}`);
}
// optional: warn, leave it unregistered; routes needing it fail at request time
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
degraded.push(node.name);
logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, {
provider: node.name,
error,
});
logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error });
}
}
@@ -938,8 +1114,8 @@ function buildMeshControl(
registry: Registry,
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
): MeshControl | undefined {
const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
if (hasExports && !mesh?.secret) {
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
@@ -947,8 +1123,8 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it
@@ -986,6 +1162,7 @@ function buildMeshControl(
transformer: plan.transformer,
bus,
onError,
logger,
transport: plan.transport,
correlation: {
requestId: env.correlation?.requestId,
@@ -1011,7 +1188,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError } = deps;
const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -1030,6 +1207,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer,
bus,
onError,
logger,
transport: plan.transport,
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete
// paths gets one label per distinct URL, and that takes down the metrics backend.
+36 -5
View File
@@ -38,6 +38,15 @@ export interface Explain {
export interface App {
listen(port: number): Promise<http.Server>;
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
*
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
* their server, which is why the option is declared once on `createApp` and works on all three.
* Call it yourself only if you serve the app some other way.
*/
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
/**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
@@ -50,6 +59,22 @@ export interface App {
* shares this same memoized step — calling both never resolves the graph twice.
*/
ready(): Promise<void>;
/**
* Boots the providers now, instead of on the first request.
*
* The three serving helpers call it for you: `listen()` before it accepts a connection,
* `serveDeno()` and `serveBun()` before they bind. Calling it by hand is for the paths that have
* no startup of their own — `app.fetch` and `app.upgrade` driven by your own server, where a
* provider that throws fails *every* request, answered by the runtime with a 500 that never
* reaches `onError`, because the boot memo keeps the rejection. Calling this first turns that into
* a startup failure, which is where a bad key or an unreachable database belongs.
*
* Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike
* `ready()`, it does run provider factories.
*
* On workerd there is no startup outside a request, so calling it moves nothing.
*/
boot(): Promise<void>;
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
fetch(request: Request): Promise<Response>;
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
@@ -127,12 +152,18 @@ export interface MeshConfig {
* 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.
* has not settled — should not fail a deploy, and this is the grace for that. When the deadline
* passes the teacup warns and starts anyway: every export is a step or a proxied route, so
* nothing needed that link resolved by boot.
*
* `0` restores the old behaviour of a single attempt.
* Starting is not degrading, though. A teapot that never connected sent no manifest, so none of
* its steps or routes are registered: its routes 404 rather than 503, and a local node that needs
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace.
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
*/
bootTimeoutMs?: number;
}
+18 -2
View File
@@ -74,8 +74,20 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
* (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.
*
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
*/
export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult {
export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
// failure rather than a 500 on every request.
//
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
// the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README.
await app.boot();
const server = Bun.serve({
...options,
fetch(request, server) {
@@ -117,7 +129,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// 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
@@ -133,5 +148,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
runtime: 'bun',
}),
),
),
});
}
+98 -3
View File
@@ -1,4 +1,28 @@
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
/**
* Names of every lifecycle event the framework emits over the {@link Bus}.
*
* ### The request pair is a guarantee
*
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
* consumer may open per-request state on the first and close it on the second without checking
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
* does.
*
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
* every response shape so that the next one cannot break it quietly. The alternative — documenting
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
* exactly when an operator is reading it.
*
* ### `request:end` is terminal and universal; the others are additional
*
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
* the only one of these carrying the real status. **Count it, and nothing else.**
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
*/
export type LifecycleEvent =
| 'boot:provider:start'
| 'boot:provider:ok'
@@ -6,6 +30,11 @@ export type LifecycleEvent =
| 'request:step:enter'
| 'request:step:leave'
| 'request:step:error'
// A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately
// *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its
// connection may live for hours, so `request:end` fires at the handler's return and these three
// describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is
// what lets a consumer join the two rather than watch them as unrelated streams of events.
| 'stream:open'
| 'stream:close'
| 'stream:error'
@@ -17,12 +46,18 @@ export type LifecycleEvent =
// came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
| 'request:start'
| 'request:end'
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
// also a throw, which is a thing a status alone cannot express.
| 'request:failed'
| 'route:matched'
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
// misreport the other, and "no route ran" is the fact a consumer actually wants.
// misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
// no route either, and answers 200. Read the status from the `request:end` that follows.
| 'route:unmatched';
/**
@@ -31,8 +66,39 @@ export type LifecycleEvent =
*
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
* name, and requiring a shape they cannot fill would only mean inventing values for it.
*
* ### One failed request produces three events
*
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
* All three carry the same `requestId`, and the first implementation anyone writes counts the
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
* outcome.
*
* The division of labour, which is the thing to build against:
*
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
* received. This is the request counter and the latency histogram.
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
* rendered `422` is also a throw. This is a separate error counter, not a second request
* counter.
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
*
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
* the outcome from `request:end` and only the message from `request:failed`.
*/
export interface EventPayload {
/**
* What the event is about, for a human reading a log line.
*
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
* which is bounded by construction.
*/
name: string;
scope?: string;
error?: unknown;
@@ -41,10 +107,23 @@ export interface EventPayload {
requestId?: string;
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
traceId?: string;
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */
/**
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
*
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
* that follows it: a single series for every path that was never a route, instead of a fallback
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
* starts with `/`.
*/
route?: string;
method?: string;
transport?: string;
/**
* The status the client received. Present on `request:end` always, and on `request:failed`
* except when a custom `onError` renderer threw while producing it — the one case where the
* framework does not know what was sent, and will not guess.
*/
status?: number;
}
@@ -58,6 +137,22 @@ export interface EventPayload {
*/
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
}
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
+18 -2
View File
@@ -51,8 +51,20 @@ declare const Deno: {
* 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.
*
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
*/
export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
export async function serveDeno(app: App, options?: DenoServeOptions): Promise<DenoServer> {
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
// failure rather than a 500 on every request.
//
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
// the first request would fix the failure in place and the runtime would answer from it forever,
// without ever reaching `onError`. This was documented as something the caller should remember to
// do, which made the correct use of a core helper depend on reading a README.
await app.boot();
// 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.
@@ -76,7 +88,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
// 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
@@ -101,5 +116,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
{ timeoutMs: ms, runtime: 'deno' },
),
),
),
});
}
+100 -2
View File
@@ -11,10 +11,106 @@ export interface StreamEncoder {
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
// being recognised across them would silently degrade back to an id-less `data:` frame.
const SSE_EVENT = Symbol.for('green-tea.sse-event');
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
export interface SseFields {
/**
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
* `@header('last-event-id')` and resume from there.
*/
id?: string;
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
event?: string;
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
retry?: number;
}
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
export interface SseEvent<T = unknown> extends SseFields {
readonly [SSE_EVENT]: true;
data: T;
}
/** Type guard: true when a stream item was built by {@link sse}. */
export function isSseEvent(item: unknown): item is SseEvent {
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
}
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
function assertFieldSafe(field: string, value: string): void {
if (!/[\r\n\0]/.test(value)) return;
throw new Error(
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
'one would end the field and let the rest of the value be read as further SSE fields. ' +
`Received ${JSON.stringify(value)}.`,
);
}
/**
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
* instead of a bare `data:` frame.
*
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
* marker in both directions and stores nothing — a source that can resume, resumes; one that
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
*
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
*
* @example
* ```ts
* @Sse('/feed')
* feed(@header('last-event-id') from: string) {
* return (async function* () {
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
* })();
* }
* ```
*/
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
// reconnection delay at the default rather than at the value the app asked for.
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
}
return { [SSE_EVENT]: true, data, ...fields };
}
/**
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
*/
function sseFrame(item: unknown): string {
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
let frame = '';
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
if (item.event !== undefined) frame += `event: ${item.event}\n`;
if (item.id !== undefined) frame += `id: ${item.id}\n`;
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
}
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
export const sseEncoder: StreamEncoder = {
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
encode: sseFrame,
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
ping: () => ': ping\n\n',
};
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
/** Newline-delimited JSON encoder: one JSON object per line. */
export const ndjsonEncoder: StreamEncoder = {
headers: { 'content-type': 'application/x-ndjson' },
encode: (item) => `${JSON.stringify(item)}\n`,
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
};
+31 -2
View File
@@ -43,7 +43,7 @@ export interface GraphNode {
}
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
const producedBy = new Map<string, GraphNode>();
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
@@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
for (const node of nodes) {
for (const key of node.needs) {
if (!seedKeys.includes(key) && !producedBy.has(key)) {
throw new Error(`missing dependency: ${key} needed by ${node.name}`);
throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
}
}
}
@@ -78,6 +78,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
return ordered;
}
/**
* Groups an already topo-sorted list into dependency levels: nothing in a level can constrain
* anything else in it, and a level depends only on the levels before it — so a level can run
* concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain
* nothing and are ignored.
*/
export function topoLevels(ordered: GraphNode[]): GraphNode[][] {
const producedBy = new Map<string, GraphNode>();
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
const depthOf = new Map<GraphNode, number>();
const levels: GraphNode[][] = [];
// One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's
// needs already has its depth by the time the node is reached.
for (const node of ordered) {
let depth = 0;
for (const key of node.needs) {
const producer = producedBy.get(key);
if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1);
}
depthOf.set(node, depth);
(levels[depth] ??= []).push(node);
}
return levels;
}
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
const producedBy = new Map<string, GraphNode>();
+1 -1
View File
@@ -129,7 +129,7 @@ function parseAcquired(
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body },
);
}
+80 -12
View File
@@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
@@ -23,15 +24,15 @@ import type { Bus } from '../bus';
* 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 the
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`.
* 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!();
// eslint-disable-next-line @typescript-eslint/no-require-imports
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
/**
@@ -132,7 +133,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
return injected;
}
@@ -143,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, req, opts?.onError);
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
injected,
outcome: {
@@ -191,6 +192,15 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/**
* The `route` reported for a request no route matched.
*
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
* single series where the concrete path would produce one per distinct URL.
*/
export const UNMATCHED_ROUTE = '<unmatched>';
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace {
route?: string;
@@ -211,6 +221,7 @@ export function handle(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const bus = opts?.bus;
@@ -226,10 +237,52 @@ export function handle(
bus.hasListeners('route:unmatched')
)
) {
return dispatch(routes, opts, req, undefined, undefined);
return dispatch(routes, opts, req, undefined, undefined, injected);
}
return observedDispatch(routes, opts, req, bus);
return observedDispatch(routes, opts, req, bus, injected);
}
/**
* Whether anything is listening for the request pair — the one check both adapters need before
* paying for a `performance.now()` on a request they are about to refuse.
*/
export function watchingRequests(bus: Bus | undefined): bus is Bus {
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
}
/**
* Emits the lifecycle pair for a request shed before routing.
*
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
* time a server sheds — under load, which is when it can least afford them.
*
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
* costs nothing for a subscriber of one.
*/
export function emitShedPair(
bus: Bus,
req: { method: string; url: string; requestId?: string; traceId?: string },
startedAt: number,
): void {
const name = `${req.method} ${req.url}`;
if (bus.hasListeners('request:start'))
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
if (bus.hasListeners('request:end'))
bus.emit('request:end', {
name,
method: req.method,
status: 503,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
}
async function observedDispatch(
@@ -237,6 +290,7 @@ async function observedDispatch(
opts: HttpOptions | undefined,
req: NeutralRequest,
bus: Bus,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0;
@@ -250,7 +304,7 @@ async function observedDispatch(
traceId: req.traceId,
});
const result = await dispatch(routes, opts, req, bus, trace);
const result = await dispatch(routes, opts, req, bus, trace, injected);
if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
@@ -276,8 +330,13 @@ async function dispatch(
req: NeutralRequest,
bus: Bus | undefined,
trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req);
// Both adapters compute this before routing, because a response written above `handle()` — a
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
const injected = precomputed ?? computeInjected(opts, req);
let path: string;
try {
@@ -287,15 +346,24 @@ async function dispatch(
}
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) };
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
}
const matched = resolveRoute(routes, req.method, path);
if (!matched) {
// `name` here is the path that arrived, and it is the one value in this payload that must never
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
// and some of them to get it wrong.
if (trace) trace.route = UNMATCHED_ROUTE;
if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', {
name: `${req.method} ${path}`,
route: UNMATCHED_ROUTE,
method: req.method,
requestId: req.requestId,
traceId: req.traceId,
@@ -342,7 +410,7 @@ async function dispatch(
traceId: req.traceId,
});
} catch (error) {
result = renderError(error, req, opts?.onError);
result = renderError(error, req, opts?.onError, opts?.logger);
}
if (isStreamResult(result)) {
+43
View File
@@ -0,0 +1,43 @@
/**
* Per-server/adapter request budget.
*
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
*/
export interface RequestGate {
/**
* Whether a budget is actually configured.
*
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
* per-request cost behind it should be skipped entirely.
*/
limited: boolean;
acquire(): boolean;
release(): void;
}
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
export function createRequestGate(limit: number | undefined): RequestGate {
let active = 0;
const limited = limit !== undefined && limit > 0;
return {
limited,
acquire(): boolean {
if (limit === undefined || limit <= 0) return true;
if (active >= limit) return false;
active++;
return true;
},
release(): void {
if (limit === undefined || limit <= 0) return;
if (active > 0) active--;
},
};
}
+80 -34
View File
@@ -13,8 +13,6 @@ export interface CompiledPattern {
segments: CompiledSegment[];
kinds: number[];
catchAll: boolean;
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
allStatic: boolean;
}
const compiledCache = new Map<string, CompiledPattern>();
@@ -160,7 +158,6 @@ export function compilePattern(pattern: string): CompiledPattern {
.filter((segment) => segment.kind !== 'catchAll')
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
catchAll: segments.at(-1)?.kind === 'catchAll',
allStatic: segments.every((segment) => segment.kind === 'static'),
};
compiledCache.set(pattern, compiled);
return compiled;
@@ -248,7 +245,10 @@ export function normalizeRequestPath(path: string): string {
}
function decodeSegment(value: string): string {
return decodeURIComponent(value);
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
// runs for every param segment of every candidate route the scan reaches.
return value.includes('%') ? decodeURIComponent(value) : value;
}
/**
@@ -262,7 +262,18 @@ function splitPath(path: string): string[] {
return path.split('/').filter(Boolean);
}
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined {
/**
* Matches one compiled pattern against a request's segments.
*
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
* several routes decoded the same string once per route. Position is all decoding depends on, so one
* array shared across the scan is the same answer for less work.
*/
function matchCompiled(
compiled: CompiledPattern,
pathSegs: string[],
decoded?: Array<string | undefined>,
): Record<string, string> | undefined {
const params: Record<string, string> = {};
for (let index = 0; index < compiled.segments.length; index++) {
@@ -280,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<st
continue;
}
const value = decodeSegment(pathSegs[index]);
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value;
}
@@ -293,10 +304,15 @@ export function matchPattern(pattern: string, path: string): Record<string, stri
return matchCompiled(compilePattern(pattern), splitPath(path));
}
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
function moreSpecific(a: string, b: string): number {
const scoreA = compilePattern(a);
const scoreB = compilePattern(b);
/**
* Orders patterns by exactness, then static/constrained/plain segment specificity.
*
* Takes compiled patterns rather than their source strings: it used to re-derive both through
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
*/
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
const scoreA = a;
const scoreB = b;
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
@@ -309,35 +325,65 @@ function moreSpecific(a: string, b: string): number {
return 0;
}
/** Finds the most specific route matching both method and path; ties keep registration order. */
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
const pathSegs = splitPath(path);
let best: MatchedRoute | undefined;
let bestPattern = '';
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
interface IndexedRoute {
def: RouteDef;
compiled: CompiledPattern;
}
for (const route of routes) {
if (route.method !== method) continue;
const compiled = compilePattern(route.pattern);
const params = matchCompiled(compiled, pathSegs);
if (!params) continue;
/**
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
* they were built from.
*
* A server hands the same array to every request, so this is built once and collected with the
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
* different array and gets its own index, so nothing has to remember to invalidate anything.
*/
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
// An all-static match ends the scan. Specificity ranks a literal segment above every other
// kind, so no pattern that also matches this path can outrank one made only of literals — and
// an equal rank keeps registration order, which is this route. Finishing the scan would
// re-derive the answer already in hand.
//
// The scan used to run to the end regardless: `/hello` cost the same whether it was declared
// first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per
// registered route on every request, and it grows with the route table.
if (compiled.allStatic) return { params, def: route };
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
const cached = routeIndexCache.get(routes);
if (cached) return cached;
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
best = { params, def: route };
bestPattern = route.pattern;
}
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. */
+104 -23
View File
@@ -1,15 +1,24 @@
import type http from 'http';
import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest } from './core';
import {
handle,
correlateRequest,
computeInjected,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { nodeRequire } from '../node-require';
interface HandlerConfig {
routes: RouteDef[];
@@ -43,17 +52,29 @@ export function createHttpServer(
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttp = require('http') as typeof import('http');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
const nodeHttp = nodeRequire<typeof import('http')>('http');
const nodeHttps = nodeRequire<typeof import('https')>('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server;
const maxConnections = opts?.limits?.maxConnections ?? 1000;
if (maxConnections > 0) server.maxConnections = maxConnections;
if (maxConnections > 0) {
server.maxConnections = maxConnections;
let lastDropWarn = 0;
server.on('drop', ({ remoteAddress, remotePort }) => {
const now = Date.now();
if (now - lastDropWarn < 60_000) return;
lastDropWarn = now;
opts?.logger?.warn(
`maxConnections (${maxConnections}) reached \u2014 dropped connection from ${remoteAddress ?? 'unknown'}:${remotePort ?? 'unknown'}`,
{ maxConnections, remoteAddress, remotePort },
);
});
}
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
@@ -73,6 +94,7 @@ function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, trustProxy } = cfg;
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
// Install the security-header patch BEFORE any routing/response so every path
@@ -80,23 +102,74 @@ function createRequestHandler(cfg: HandlerConfig) {
const secure = deriveSecure(req, trustProxy);
// Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
// One computation for the whole request: this object is patched into every response below, and
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
// `cors.origins` may be a predicate with a network call in it.
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(bus);
const startedAt = watching ? performance.now() : 0;
const result = await handle(routes, opts, {
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
});
try {
if (!gate.acquire()) {
if (watching)
emitShedPair(
bus,
{
method: req.method ?? 'GET',
url: req.url ?? '/',
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
res.writeHead(503, {
'content-type': 'application/json',
'retry-after': '1',
connection: 'close',
});
res.end(JSON.stringify({ error: 'Service Unavailable' }));
return;
}
// Both the flag and the listener are skipped when no budget is configured, which is most
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
// with nothing on the other side of it.
if (gate.limited) {
acquired = true;
res.once('close', () => {
if (!acquired) return;
acquired = false;
gate.release();
});
}
result = await handle(
routes,
opts,
{
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
},
injected,
);
} finally {
if (acquired) {
acquired = false;
gate.release();
}
}
if ('preflight' in result) {
res.writeHead(204, result.preflight);
@@ -105,7 +178,15 @@ function createRequestHandler(cfg: HandlerConfig) {
}
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return;
}
@@ -131,7 +212,7 @@ function readRequestBytes(
return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }),
(error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError);
const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
},
);
+125
View File
@@ -0,0 +1,125 @@
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
import type { Logger } from '../logger';
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
type Signal = (typeof SIGNALS)[number];
interface SignalApi {
runtime: string;
on(signal: Signal, handler: () => void): void;
off(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface DenoSignals {
addSignalListener(signal: Signal, handler: () => void): void;
removeSignalListener(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface ProcessSignals {
on(signal: Signal, handler: () => void): unknown;
off?(signal: Signal, handler: () => void): unknown;
removeListener?(signal: Signal, handler: () => void): unknown;
exit(code: number): void;
}
/**
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
* listener holds the process open until it is removed. Node and Bun share `process`.
*/
function signalApi(): SignalApi | undefined {
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
if (typeof deno?.addSignalListener === 'function')
return {
runtime: 'deno',
on: (signal, handler) => deno.addSignalListener(signal, handler),
off: (signal, handler) => deno.removeSignalListener(signal, handler),
exit: (code) => deno.exit(code),
};
const proc = (globalThis as { process?: ProcessSignals }).process;
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
const remove = proc.off ?? proc.removeListener;
return {
runtime: 'node',
on: (signal, handler) => void proc.on(signal, handler),
off: (signal, handler) => void remove?.call(proc, signal, handler),
exit: (code) => proc.exit(code),
};
}
return undefined;
}
/**
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
* the process from exiting on its own.
*
* The close is expected to unregister first thing, which leaves a **second signal falling through
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
*
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
* not a clean one and an orchestrator should be told.
*/
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
const api = signalApi();
if (!api) {
logger.warn(
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
);
return () => {};
}
const registered: Array<[Signal, () => void]> = [];
const remove = (): void => {
while (registered.length) {
const [signal, handler] = registered.pop()!;
api.off(signal, handler);
}
};
for (const signal of SIGNALS) {
const handler = (): void => {
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
void close().then(
() => api.exit(0),
(error: unknown) => {
logger.error(`shutdown failed after ${signal}`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
api.exit(1);
},
);
};
try {
api.on(signal, handler);
registered.push([signal, handler]);
} catch (error) {
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
// platform does have beats refusing to start over the one it does not.
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
}
}
return remove;
}
+10 -4
View File
@@ -2,7 +2,7 @@ import type http from 'http';
import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
const PING_MS = 15_000;
@@ -35,10 +35,16 @@ export async function pipeStream(
bus?: Bus,
name = '',
streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> {
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
// is always the route pattern, never the concrete path the request events can carry — but a
// consumer following the documented contract labels on `route` and would otherwise find it
// absent on the longest-lived thing the server does. See `EventPayload.name`.
const trace = { name, route: name, ...correlation };
res.writeHead(200, encoder.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
@@ -76,13 +82,13 @@ export async function pipeStream(
}
}
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame);
} finally {
if (ping) clearInterval(ping);
streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end();
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}
+4
View File
@@ -5,11 +5,13 @@ import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
/** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
requestTimeoutMs?: number; // default 30_000
headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000
@@ -24,6 +26,8 @@ export interface HttpOptions {
* a separate channel for it.
*/
bus?: Bus;
/** Where this server writes diagnostics. Optional because `createHttpServer` takes no options at all in tests. */
logger?: Logger;
limits?: RequestLimits;
streams?: Set<() => void>;
tls?: TlsOptions;
+141 -33
View File
@@ -1,33 +1,85 @@
import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
import type { Bus, Correlation } from '../bus';
import { createRequestGate } from './request-gate';
import {
handle,
computeInjected,
correlateRequest,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
* cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the
* lifecycle of a stream must not depend on which adapter is serving it.
*/
export function asReadableStream(
source: AsyncIterable<unknown>,
encoder: StreamEncoder,
bus?: Bus,
name = '',
correlation: Correlation = {},
): ReadableStream<Uint8Array> {
const iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder();
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
// says label on `route`, so both are carried.
const trace = { name, route: name, ...correlation };
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
// its own path — so the close is latched rather than emitted from each of the three exits.
let closed = false;
const close = (): void => {
if (closed) return;
closed = true;
bus?.emit('stream:close', trace);
};
return new ReadableStream<Uint8Array>({
start() {
bus?.emit('stream:open', trace);
},
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
close();
controller.close();
return;
}
const encoded = encoder.encode(value);
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
controller.enqueue(bytes);
controller.enqueue(frame(encoder.encode(value)));
} catch (err) {
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() {
close();
await iterator.return?.();
},
});
@@ -68,7 +120,7 @@ function readFetchBytes(
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
@@ -106,11 +158,18 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult): Response {
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
const body = asReadableStream(
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
correlation,
);
return new Response(body, { headers });
}
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
@@ -127,6 +186,7 @@ function outcomeToResponse(result: HandleResult): Response {
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (request: Request): Promise<Response> => {
const url = new URL(request.url);
@@ -139,31 +199,79 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers });
const result = await handle(routes, opts, {
...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()
: '',
});
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(opts?.bus);
const startedAt = watching ? performance.now() : 0;
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
if ('preflight' in result) {
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
try {
if (!gate.acquire()) {
if (watching)
emitShedPair(
opts!.bus!,
{
method: request.method,
url: path,
requestId: correlation.requestId,
traceId: correlation.traceId,
},
startedAt,
);
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
});
}
acquired = gate.limited;
result = await handle(
routes,
opts,
{
...correlation,
method: request.method,
url: path,
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();
}
return outcomeToResponse(result);
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries.
if ('preflight' in result) {
return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
});
}
return outcomeToResponse(result, opts?.bus, correlation);
};
}
+2 -2
View File
@@ -1,6 +1,7 @@
import { channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
/**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
@@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor {
if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws') as SocketCtor;
return nodeRequire<SocketCtor>('ws');
}
/**
+9 -3
View File
@@ -1,5 +1,6 @@
import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
@@ -109,6 +110,11 @@ export async function runWsConnection(
): Promise<void> {
const { closer } = trackConnection(socket, streams);
const name = route.def.pattern;
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
// keeps one identity per connection instead of one per emitter.
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => {
@@ -117,7 +123,7 @@ export async function runWsConnection(
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name });
bus?.emit('stream:open', trace);
try {
const outbound = await route.def.open({
@@ -129,9 +135,9 @@ export async function runWsConnection(
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
bus?.emit('stream:error', { ...trace, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', { name });
bus?.emit('stream:close', trace);
}
}
+2 -2
View File
@@ -3,14 +3,14 @@ import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
import { nodeRequire } from '../node-require';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null {
try {
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
// support don't fail. When absent this throws and we fall back to null (501 on upgrade).
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws').WebSocketServer;
return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
} catch {
return null;
}
+23 -7
View File
@@ -5,8 +5,16 @@
*/
import 'reflect-metadata';
/** Package version, replaced at publish time. */
export const VERSION = '26.8.0-beta.0';
/**
* Package version. Kept in step with `package.json` and `deno.json` by hand, and pinned to them by
* `test/package-metadata.test.ts`.
*
* It used to say it was "replaced at publish time", which nothing ever did — not `tsup`, not
* `stage.yml`, not `release.yml`, which only ever *reads* the version out of `package.json`. So the
* constant drifted two releases behind while the comment explained why it could not, and the only
* test touching it checked the CalVer shape, which a stale version satisfies perfectly.
*/
export const VERSION = '26.9.0-beta.2';
// Application
export { createApp } from './app';
@@ -40,8 +48,10 @@ export {
Options,
Html,
} from './metadata';
export type { Transport, HttpMethod, RouteDecorator } from './metadata';
export type { Plugin } from './plugin';
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals
export { JsonTransformer } from './transformers';
@@ -54,11 +64,16 @@ export {
NotModified,
ValidationError,
TransportMismatchError,
HTTP_ERROR,
VALIDATION_ERROR,
isHttpError,
isValidationError,
} from './signals';
export type { HttpErrorLike } from './signals';
// Bus & flow
export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
@@ -74,11 +89,12 @@ export type { Logger, LogLevel, LogFields } from './logger';
export { channel, isAsyncIterable } from './channel';
export type { Channel } from './channel';
export { Rooms } from './rooms';
export { sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder } from './encoders';
export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation
export type { RequestLimits } from './http';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema';
+30 -18
View File
@@ -218,7 +218,7 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
// `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 });
hs.resolve({ socket: hs.socket, manifest: { steps: frame.steps, routes: frame.routes }, heartbeat });
}
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
@@ -323,9 +323,9 @@ function openSession(args: SessionArgs): Promise<Session> {
});
}
/** 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}`));
/** A manifest's step tokens, flattened to the set the refusal check compares. */
function stepKeys(manifest: Manifest): Set<string> {
return new Set(manifest.steps);
}
/**
@@ -345,12 +345,12 @@ function routeKeys(manifest: Manifest): Set<string> {
* 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 steps = stepKeys(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 step of booted.steps) {
if (!steps.has(step)) missing.push(`step '${step}'`);
}
for (const route of booted.routes) {
@@ -393,8 +393,6 @@ export function connectLink(args: {
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;
@@ -407,7 +405,7 @@ export function connectLink(args: {
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: [] },
manifest: { steps: [], 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
@@ -453,7 +451,7 @@ export function connectLink(args: {
};
/** 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 adopt = (session: Session): boolean => {
const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) {
@@ -478,7 +476,6 @@ export function connectLink(args: {
refusalLogged = '';
state.socket = session.socket;
args.bus?.emit('mesh:connect', { name: args.url });
if (reconnected) args.onReconnect?.();
return true;
};
@@ -494,7 +491,7 @@ export function connectLink(args: {
return;
}
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
if (!adopt(session)) 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.
@@ -502,10 +499,25 @@ export function connectLink(args: {
}
};
return openSession(sessionArgs(() => endSession(0))).then((session) => {
link.manifest = session.manifest;
adopt(session, 0, false);
return openSession(sessionArgs(() => endSession(0))).then(
(session) => {
link.manifest = session.manifest;
adopt(session);
return link;
});
return link;
},
(error) => {
// The first connect failed, so this `Link` never escaped — nobody holds it and nobody can
// ever call `close()` on it. But `openSession`'s abort listener has already run `onEnd`,
// which scheduled a retry: left alone, that supervisor reconnects forever to a handle no
// caller has, and `closeLinks` cannot reach it because the link was never pushed to
// `meshLinks`. Boot already retries above this (`connectUntilDeadline`), so a second
// supervisor underneath it is pure leak — every failed attempt used to leave one behind.
// Reconnection for a link that *did* connect is untouched: this path runs only on the
// initial rejection, and a session that drops later still goes through `endSession`.
state.closed = true;
clearTimeout(state.retry);
throw error;
},
);
}
+29 -9
View File
@@ -18,6 +18,14 @@
*
* 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.
*
* **One exception has been taken, and its terms are the point.** The manifest's `scopes` field was
* renamed to `steps` at v1 — a rename, which the first rule above would otherwise cover — without a
* bump. It was allowed because there is no deployed pair the rename could split: mesh is alpha,
* every app using it is gated behind `experimental: true`, and both peers ship out of this one
* repo, so a teacup and a teapot are always on the same version. Each of those three has to hold
* for the exception to; the first mesh release that drops `experimental` retires it, and a rename
* after that earns a bump like any other.
*/
export const MESH_PROTOCOL_VERSION = 1;
@@ -43,19 +51,21 @@ export interface RequestEnvelope {
correlation?: { requestId?: string; traceId?: string };
}
/** Manifest entry for an exported scope token and its lifetime. */
export interface ScopeEntry {
token: string;
scope: 'app' | 'request';
}
/** Manifest entry for an exported route. */
export interface RouteEntry {
method: string;
pattern: string;
}
/** A mesh server's advertised scopes and routes. */
/**
* A mesh server's advertised steps and routes.
*
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
* lazy — the token exists in the teacup's graph, and running it is an RPC.
*/
export interface Manifest {
scopes: ScopeEntry[];
steps: string[];
routes: RouteEntry[];
}
@@ -68,7 +78,7 @@ export interface Manifest {
*/
export type Frame =
| { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
@@ -78,6 +88,9 @@ export type Frame =
const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
/** A manifest route entry: both fields reach `compilePattern`, so both must really be strings. */
const isRouteEntry = (value: unknown): boolean =>
isObject(value) && isString((value as RouteEntry).method) && isString((value as RouteEntry).pattern);
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
@@ -94,7 +107,14 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
},
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
// Array.isArray above already guarantees this, but TS does not carry that narrowing through a
// `never`-typed callback parameter — the cast is safe, not a bypass.
if (!(frame.steps as unknown[]).every(isString)) bad('every step must be a string');
// Checked for the same reason steps are: past `decode` a route entry goes straight to
// `compilePattern`, where a non-string `pattern` dies as a boot `TypeError` about a peer's
// frame — a failure that reads like a green-tea bug rather than a malformed manifest.
if (!(frame.routes as unknown[]).every(isRouteEntry)) bad('every route must have a string method and pattern');
},
'rpc-req': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string');
+8 -17
View File
@@ -37,27 +37,18 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
};
}
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */
export function buildRemote(link: Link): {
providers: RemoteScopeNode[];
steps: RemoteScopeNode[];
routes: RemoteRoute[];
} {
const providers: RemoteScopeNode[] = [];
const steps: RemoteScopeNode[] = [];
for (const scope of link.manifest.scopes) {
const node: RemoteScopeNode = {
name: scope.token,
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
};
(scope.scope === 'app' ? providers : steps).push(node);
}
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
name: token,
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
}));
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method,
pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
}));
return { providers, steps, routes };
return { steps, routes };
}
+5 -15
View File
@@ -42,19 +42,9 @@ const HANDSHAKE_TIMEOUT_MS = 10_000;
*/
const MAX_FRAME_CHARS = 4_000_000;
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
export function buildManifest(args: {
providers: string[]; // exported provider tokens (app-scope)
steps: string[]; // exported step tokens (request-scope)
routes: RouteEntry[]; // exported buffered routes
}): Manifest {
return {
scopes: [
...args.providers.map((token) => ({ token, scope: 'app' as const })),
...args.steps.map((token) => ({ token, scope: 'request' as const })),
],
routes: args.routes,
};
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
return { steps: [...args.steps], routes: args.routes };
}
function safeEqual(left: string, right: string): boolean {
@@ -115,7 +105,7 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: deps.manifest.scopes,
steps: deps.manifest.steps,
routes: deps.manifest.routes,
}),
);
@@ -244,7 +234,7 @@ export function createMeshControl(deps: MeshControlDeps): {
path: string;
handle: (socket: WsSocket) => Promise<void>;
} {
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
const exportedScopes = new Set(deps.manifest.steps);
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return {
+11 -7
View File
@@ -15,6 +15,12 @@ export interface ProviderMeta {
provides: string;
needs: string[];
optional: boolean;
/**
* Always refused. `@Provider`'s options no longer declare `export`, so TypeScript rejects it at
* the decorator and this can only be true for a JavaScript caller. It is still recorded so that
* caller reaches `collectProviders`' boot error, which names the provider and the replacement,
* rather than having the option silently ignored.
*/
export: boolean;
}
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
@@ -58,18 +64,16 @@ const K = {
};
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
export function Provider(opts: {
provides: string;
needs?: string[];
optional?: boolean;
export?: boolean;
}): ClassDecorator {
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
return (target) => {
const meta: ProviderMeta = {
provides: opts.provides,
needs: opts.needs ?? [],
optional: opts.optional ?? false,
export: opts.export ?? false,
// Read through a cast because the options type deliberately does not offer `export`: only a
// `@Step` or a route is exportable, and the option's only behaviour was to throw at boot.
// A JavaScript caller can still pass it, and recording it is what routes them to that error.
export: (opts as { export?: boolean }).export ?? false,
};
Reflect.defineMetadata(K.provider, meta, target);
};
+2 -2
View File
@@ -1,6 +1,7 @@
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
import { Readable } from 'stream';
import { HttpError } from './signals';
import { nodeRequire } from './node-require';
/** A single uploaded file part decoded from a multipart body. */
export interface UploadedFile {
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
try {
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('busboy');
return nodeRequire('busboy');
} catch {
return null;
}
+44
View File
@@ -0,0 +1,44 @@
// src/node-require.ts — one `require` that survives being published as source.
type Require = <T>(id: string) => T;
interface NodeProcess {
cwd?: () => string;
getBuiltinModule?: (id: string) => unknown;
}
let cached: Require | null | undefined;
function resolveRequire(): Require | undefined {
// The CJS build has a native one, and tsup gives the ESM build one through a `createRequire`
// banner (tsup.config.ts). Both npm paths stop here.
if (typeof require === 'function') return require as Require;
// JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`.
// `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all
// three do it *synchronously* — which is the whole requirement, since every caller here sits on
// a sync path that a dynamic `import()` could not serve.
const proc = (globalThis as { process?: NodeProcess }).process;
const nodeModule = proc?.getBuiltinModule?.('node:module') as
{ createRequire?: (from: string) => Require } | undefined;
if (!nodeModule?.createRequire || !proc?.cwd) return undefined;
// Resolve from the application's directory rather than from this file: served from JSR this
// module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer
// dependency such as `busboy` is installed in the app that asked for it.
return nodeModule.createRequire(`${proc.cwd()}/`);
}
/**
* Loads a Node builtin or an installed package, synchronously.
*
* Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely
* out of reach. Every caller already guards for that and reports it in its own terms; what they
* must not do is report it when the module is in fact reachable, which is what a bare `require`
* caused on JSR by failing with `ReferenceError` before any of them was consulted.
*/
export function nodeRequire<T>(id: string): T {
if (cached === undefined) cached = resolveRequire() ?? null;
if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`);
return cached<T>(id);
}
+30 -11
View File
@@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep {
@@ -113,9 +114,10 @@ export async function runPipeline(args: {
bus: Bus;
transport: Transport;
onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation;
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args;
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
@@ -137,16 +139,33 @@ export async function runPipeline(args: {
const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError(
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
);
let status: number | undefined;
try {
const rendered = renderError(
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
logger,
);
status = rendered.status;
return rendered;
} finally {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
//
// Emitted after the render rather than before it, because the status is only decided there:
// `onError` may turn any throw into any status, so deriving one from the error would be a
// guess that a custom renderer makes wrong.
//
// In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
}
}
}
+34 -5
View File
@@ -14,7 +14,18 @@ export interface ScopeNode {
export interface ScopeApi {
add(node: ScopeNode): void;
}
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
/**
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
*
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
*
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
* would turn a one-way observation channel into something any node can forge events on.
* `@needs('bus')` fails at boot and says so.
*/
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
@@ -26,8 +37,18 @@ export interface PluginApi {
*/
onShutdown(fn: TeardownFn): void;
}
/** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void;
/**
* A plugin: a named object that wires itself up through the provided PluginApi.
*
* The name is a field rather than `fn.name` because `fn.name` cannot be relied on: an arrow
* returned straight from a factory has `""`, `const plugin = …` reports `"plugin"`, and a minifier
* rewrites both. The name is what `plugin:mounted` reports and what a failed mount is blamed on, so
* it has to be the author's word, not the bundler's.
*/
export interface Plugin {
readonly name: string;
mount(api: PluginApi): void;
}
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
@@ -42,6 +63,14 @@ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdow
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
try {
plugin.mount(api);
} catch (error) {
// Without the name this surfaces as somebody else's stack trace: mounting happens inside
// createApp, so the application sees a throw from a line it never wrote.
throw new Error(`plugin "${plugin.name}" failed to mount: ${(error as Error).message}`, { cause: error });
}
bus.emit('plugin:mounted', { name: plugin.name });
}
+26 -5
View File
@@ -1,5 +1,7 @@
// src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */
export interface TlsOptions {
key: Buffer | string;
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
return headers;
}
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
if (spec === '*') return true;
if (typeof spec === 'function') return spec(origin);
if (Array.isArray(spec)) return spec.includes(origin);
return spec === origin;
if (typeof spec !== 'function') return spec === origin;
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
// before the region where errors convert to a response, so a throw here would leave the request
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
// has not said yes, and a broken allowlist must never widen into an open one.
try {
return spec(origin);
} catch (error) {
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
origin,
err: error instanceof Error ? error.message : String(error),
});
return false;
}
}
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers {
const headers: Headers = {};
const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) {
@@ -112,8 +128,13 @@ export function resolveCors(
export function corsPreflightHeaders(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): Headers {
const headers = resolveCors(opts, req);
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
// response carries. Re-deriving here would consult `origins` a second time for the same request —
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
// preflight-only keys below belong to this 204, not to the shared object.
const headers: Headers = { ...resolved };
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
', ',
+35 -3
View File
@@ -1,11 +1,36 @@
import type { StandardIssue } from './standard-schema';
/**
* Brands, so an error is recognised across two copies of core — an app that installed one from npm
* and a plugin that brought another from JSR, or two npm versions npm could not dedupe.
* `instanceof` cannot do that: each copy has its own class identity.
*
* `Symbol.for` is registry-wide, so both copies resolve the same symbol. The *string* is the public
* protocol (`.specs/2026-09-15-plugin-ecosystem-design.md`, 1.2): a plugin that imports only types
* cannot import this constant, so it writes `Symbol.for('green-tea.http-error')` itself.
*
* `unique symbol` is required by TypeScript for a computed class field, and `Symbol.for` on a `const`
* satisfies it.
*/
export const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
export const VALIDATION_ERROR: unique symbol = Symbol.for('green-tea.validation-error');
/** The shape core reads off a branded error. Anything carrying the brand should satisfy it. */
export interface HttpErrorLike {
status: number;
message: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* Error carrying an HTTP status code and optional response body. Base of all signals.
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
* rather than requiring a special case in the error renderer.
*/
export class HttpError extends Error {
readonly [HTTP_ERROR] = true;
constructor(
readonly status: number,
message?: string,
@@ -47,6 +72,8 @@ export class Redirect extends HttpError {
/** 422 raised when request input fails Standard Schema validation. */
export class ValidationError extends HttpError {
readonly [VALIDATION_ERROR] = true;
constructor(
public issues: StandardIssue[],
public source: string,
@@ -68,7 +95,12 @@ export class TransportMismatchError extends HttpError {
}
}
/** Type guard: true if `error` is an {@link HttpError}. */
export function isHttpError(error: unknown): error is HttpError {
return error instanceof HttpError;
/** Type guard: true if `error` carries the HTTP-error brand — this copy's or another's. */
export function isHttpError(error: unknown): error is HttpErrorLike {
return typeof error === 'object' && error !== null && HTTP_ERROR in error;
}
/** Type guard: true if `error` carries the validation brand. */
export function isValidationError(error: unknown): error is ValidationError {
return typeof error === 'object' && error !== null && VALIDATION_ERROR in error;
}
+31 -4
View File
@@ -1,6 +1,7 @@
import { isHttpError, ValidationError } from './signals';
import { isHttpError, isValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
@@ -34,7 +35,7 @@ export const JsonTransformer: TransformerFn = (value) => ({
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
*/
export function errorToResponse(error: unknown): ErrorResponse {
if (error instanceof ValidationError) {
if (isValidationError(error)) {
return {
status: 422,
headers: { 'content-type': 'application/json' },
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
}
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
return onError?.(error, req) ?? errorToResponse(error);
export function renderError(
error: unknown,
req: ErrorRequest,
onError?: ErrorRenderer,
logger?: Logger,
): ErrorResponse {
if (!onError) return errorToResponse(error);
// `onError` is user code, it runs on the request path, and it runs *after something already went
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
// occurs, the code written to report it fails, and the process ends instead of degrading.
//
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
// custom renderer and no matching route is one request away from exiting.
//
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
// overrides and therefore the honest thing to fall back to: the original error still gets its
// response. The renderer's own failure is reported separately, because it is a different error
// from the request's and a reader chasing the wrong one loses an afternoon.
try {
return onError(error, req) ?? errorToResponse(error);
} catch (rendererError) {
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
rendering: error instanceof Error ? error.message : String(error),
});
return errorToResponse(error);
}
}
+8 -9
View File
@@ -3,6 +3,7 @@
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
import { nodeRequire } from './node-require';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
@@ -58,12 +59,12 @@ export interface ViewsContext {
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
* filesystem should hear about it here rather than at the first request. */
function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('node:path') as typeof import('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
@@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver {
let nodePath: typeof import('node:path');
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
fs = require('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
fs = nodeRequire('node:fs');
nodePath = nodeRequire('node:path');
} catch {
throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
+59
View File
@@ -0,0 +1,59 @@
// test/app-boot.test.ts
import { describe, expect, it, vi } from 'vitest';
import { createApp, Get, Module, Route, needs } from '../src/index';
import type { Plugin } from '../src/index';
@Route('/')
class Ctl {
@Get('/x')
x(@needs('thing') thing: string) {
return { thing };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const plugin = (run: () => Promise<Record<string, unknown>>): Plugin => ({
name: 'thing',
mount({ scope }) {
scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run });
},
});
describe('app.boot()', () => {
it('surfaces a failing provider instead of leaving it for the first request', async () => {
const app = createApp({ modules: [M], plugins: [plugin(async () => { throw new Error('bad key'); })] });
await expect(app.boot()).rejects.toThrow(/bad key/);
});
it('runs provider factories exactly once, and serves afterwards', async () => {
const run = vi.fn(async () => ({ thing: 'ok' }));
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await app.boot();
await app.boot();
const response = await app.fetch(new Request('http://x/x'));
expect(run).toHaveBeenCalledTimes(1);
expect(await response.json()).toEqual({ thing: 'ok' });
});
// The memo keeps the rejection, which is exactly why a failed boot answers 500 for the life of
// the process instead of retrying. It is the documented behaviour, so it gets a test rather than
// a sentence: if it ever starts retrying, the guide in Task 7 becomes wrong.
it('keeps a failed boot failed', async () => {
const run = vi.fn(async () => {
throw new Error('bad key');
});
const app = createApp({ modules: [M], plugins: [plugin(run)] });
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.boot()).rejects.toThrow(/bad key/);
await expect(app.fetch(new Request('http://x/x'))).rejects.toThrow(/bad key/);
expect(run).toHaveBeenCalledTimes(1);
});
});
+6 -3
View File
@@ -66,9 +66,12 @@ describe('app.upgrade', () => {
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
const seen: string[] = [];
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
const logger = {
name: 'ws-step-logger',
mount: (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
},
};
const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
const { socket, inbound, sent } = fakeSocket();
+38 -25
View File
@@ -56,7 +56,10 @@ test('ready() is a no-op on a non-mesh app, so one protocol works for both', asy
test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
const logger = {
name: 'step-logger',
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -256,17 +259,20 @@ describe('per-route subgraph slicing', () => {
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = [];
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
});
const observer = {
name: 'side-effect-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
}),
};
@Route('/')
class Ctl {
@Get('/free') free() {
@@ -285,17 +291,20 @@ describe('per-route subgraph slicing', () => {
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any;
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
});
const observer = {
name: 'audit-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
}),
};
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
@@ -603,7 +612,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
// This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
@@ -618,7 +631,7 @@ describe('rooms auto-provide', () => {
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
});
});
+43
View File
@@ -76,3 +76,46 @@ describe('renderMarkdown', () => {
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
});
});
describe('renderMarkdown runtime matrix', () => {
const base = {
env: { date: '2026-09-01', commit: 'abc1234', node: 'v22', os: 'darwin', cpu: 'M4', ram: '69 GB', pinned: false },
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
scenarios: [],
stepScaling: [],
secureCost: [],
};
it('renders one column per runtime and one row per scenario', () => {
const md = renderMarkdown({
...base,
runtimes: [
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
{ runtime: 'bun', scenario: 'JSON hello', reqSec: 120_000 },
],
} as never);
expect(md).toContain('## green-tea across runtimes');
expect(md).toContain('| Scenario | node | bun |');
expect(md).toContain('| JSON hello | 90,000 | 120,000 |');
});
it('marks a runtime that produced no number rather than printing a zero', () => {
// A skipped runtime must not read as "it ran and scored nothing".
const md = renderMarkdown({
...base,
runtimes: [
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
{ runtime: 'deno', scenario: 'Route param', reqSec: 80_000 },
],
} as never);
expect(md).toContain('| JSON hello | 90,000 | — |');
expect(md).toContain('| Route param | — | 80,000 |');
});
it('omits the section entirely when no runtime was measured', () => {
expect(renderMarkdown({ ...base, runtimes: [] } as never)).not.toContain('across runtimes');
expect(renderMarkdown(base as never)).not.toContain('across runtimes');
});
});
+205
View File
@@ -0,0 +1,205 @@
// Independent providers boot concurrently; dependent ones still wait.
//
// The graph already proved which providers cannot constrain each other — that is what the topo
// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies
// instead of its longest chain, for no ordering anyone declared.
//
// Timing is asserted structurally rather than by clock: "all three entered before any left" is
// the same claim as "they overlapped" and does not get flaky on a loaded CI box.
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { Get, Module, Provider, Route, type Ctor } from '../src/metadata';
import { createApp } from '../src/app';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
}
/** Boots the app by serving one request — providers are lazy until something is actually served. */
async function boot(module: Ctor, logger = silentLogger()): Promise<void> {
const app = createApp({ modules: [module], logger });
await app.fetch(new Request('http://x/ping'));
await app.close();
}
describe('provider boot concurrency', () => {
it('overlaps providers that do not depend on each other', async () => {
const log: string[] = [];
const independent = (name: string): Ctor => {
@Provider({ provides: name })
class P {
async provide() {
log.push(`${name}:in`);
await sleep(10);
log.push(`${name}:out`);
return { [name]: name };
}
}
return P;
};
@Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] })
class M {}
await boot(M);
// Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit.
expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']);
expect(log).toHaveLength(6);
});
it('still waits for a provider its dependant needs', async () => {
const log: string[] = [];
@Provider({ provides: 'base' })
class Base {
async provide() {
log.push('base:in');
await sleep(10);
log.push('base:out');
return { base: 1 };
}
}
@Provider({ provides: 'derived', needs: ['base'] })
class Derived {
provide(ctx: { base: number }) {
log.push('derived:in');
return { derived: ctx.base + 1 };
}
}
// Declared out of order on purpose: the wait is the graph's doing, not the array's.
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] })
class M {}
await boot(M);
expect(log).toEqual(['base:in', 'base:out', 'derived:in']);
});
it('gives a dependant every value from its level, not just the one that finished first', async () => {
@Provider({ provides: 'slow' })
class Slow {
async provide() {
await sleep(15);
return { slow: 'slow' };
}
}
@Provider({ provides: 'fast' })
class Fast {
provide() {
return { fast: 'fast' };
}
}
let seen: Record<string, unknown> = {};
@Provider({ provides: 'joined', needs: ['slow', 'fast'] })
class Joined {
provide(ctx: Record<string, unknown>) {
seen = { slow: ctx.slow, fast: ctx.fast };
return { joined: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] })
class M {}
await boot(M);
expect(seen).toEqual({ slow: 'slow', fast: 'fast' });
});
it('tears down in reverse boot order even though boot is concurrent', async () => {
const disposed: string[] = [];
const independent = (name: string, delay: number): Ctor => {
@Provider({ provides: name })
class P {
async provide() {
await sleep(delay);
return { [name]: name };
}
dispose() {
disposed.push(name);
}
}
return P;
};
// `c` finishes first and `a` last — completion order is the reverse of declaration order, so a
// teardown registered as each one lands would come out in a different order than this.
@Module({
mountpoint: '/',
controllers: [Ctl],
providers: [independent('a', 20), independent('b', 10), independent('c', 1)],
})
class M {}
await boot(M);
expect(disposed).toEqual(['c', 'b', 'a']);
});
it('fails the boot on a required provider, and still registers its siblings for teardown', async () => {
const disposed: string[] = [];
@Provider({ provides: 'ok' })
class Ok {
async provide() {
await sleep(10); // still in flight when its sibling rejects
return { ok: true };
}
dispose() {
disposed.push('ok');
}
}
@Provider({ provides: 'broken' })
class Broken {
provide(): never {
throw new Error('no pool');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
// The sibling booted — it was already in flight — so whatever it opened has to be closeable.
await app.close();
expect(disposed).toEqual(['ok']);
});
it('degrades an optional provider without taking its level down', async () => {
const logger = silentLogger();
@Provider({ provides: 'flaky', optional: true })
class Flaky {
provide(): never {
throw new Error('nope');
}
}
@Provider({ provides: 'solid' })
class Solid {
provide() {
return { solid: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] })
class M {}
const app = createApp({ modules: [M], logger });
await app.fetch(new Request('http://x/ping'));
expect(app.degraded()).toEqual(['flaky']);
await app.close();
});
});
+8 -8
View File
@@ -8,14 +8,14 @@
// 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 { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { runtime: 'bun' } };
}
}
@@ -25,7 +25,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -48,9 +48,9 @@ function freePort(): number {
}
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
function startTeapot(port: number) {
async function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveBun(app, { port });
const server = await serveBun(app, { port });
return {
stop: async () => {
@@ -64,7 +64,7 @@ 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);
let teapot = await startTeapot(port);
const teacup = createApp({
modules: [TeacupModule],
@@ -88,7 +88,7 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
teapot = startTeapot(port);
teapot = await startTeapot(port);
await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
+8 -8
View File
@@ -1,4 +1,4 @@
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming
// Real Bun integration test for mesh: a teapot exporting its steps and a teacup consuming
// them, both under the actual Bun runtime, driven entirely through serveBun.
//
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
@@ -8,14 +8,14 @@
// 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 { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx', runtime: 'bun' } };
}
}
@@ -25,7 +25,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -42,14 +42,14 @@ const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
});
const cServer = serveBun(teacup, { port: 0 });
const cServer = await serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
@@ -67,7 +67,7 @@ test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () =>
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
+36 -8
View File
@@ -6,7 +6,7 @@
// 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 { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
@@ -25,7 +25,7 @@ class Ctl {
class M {}
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
const server = await 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
@@ -40,7 +40,7 @@ test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', a
});
test('serveBun close() drains an in-flight request rather than cutting it', async () => {
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
const server = await 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
@@ -57,15 +57,43 @@ test('serveBun close() runs registered teardown', async () => {
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
})],
plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
}),
}],
});
const server = serveBun(app, { port: 0 });
const server = await 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']);
});
// The boot gate, which is why serveBun is async. Before it, a provider that threw was memoized as a
// rejection and answered 500 to every request from the runtime, never reaching onError — so the
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
@Provider({ provides: 'key' })
class BadKey {
provide(): never {
throw new Error('no such key file');
}
}
@Route('/')
class NeedsKey {
@Get('/signed')
signed(@needs('key') key: string) {
return { key };
}
}
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
class KeyModule {}
test('serveBun rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
});
+1 -1
View File
@@ -26,7 +26,7 @@ class M {}
test('serveBun: HTTP + WebSocket round-trip', async () => {
const app = createApp({ modules: [M] });
const server = serveBun(app, { port: 0 });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
+76
View File
@@ -0,0 +1,76 @@
// 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 = {
name: 'bus-observer',
mount(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();
});
});
+7 -1
View File
@@ -29,7 +29,13 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
});
const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App);
// `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
const handleSignals = <T,>(closer: T): T => closer;
// `serveDeno` boots before it binds, so the stub needs the gate even though this test never
// exercises it.
const boot = vi.fn().mockResolvedValue(undefined);
await serveDeno({ upgrade, handleSignals, boot } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
+1 -1
View File
@@ -22,7 +22,7 @@ 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) });
const server = await 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(); } };
+7 -7
View File
@@ -10,14 +10,14 @@
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
const SECRET = 's3cr3t';
const NODE_PEER = 'test/interop/_node-peer.ts';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@@ -27,7 +27,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -112,7 +112,7 @@ Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
try {
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(res.status, 200);
// the config came from the Node process: proof the scope crossed the runtime boundary
// the config came from the Node process: proof the remote step crossed the runtime boundary
assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'node' },
auth: { token: 'abc' },
@@ -127,7 +127,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
let port = 0;
const { serveDeno } = await import('../../src/deno.ts');
const server = serveDeno(teapot, {
const server = await serveDeno(teapot, {
port: 0,
onListen: (addr) => {
port = addr.port;
@@ -140,7 +140,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
try {
const result = await firstJsonLine(node);
assertEquals(result.ok, true);
// the Node peer resolved a scope served by Deno's app.upgrade control channel
// the Node peer ran a step served by Deno's app.upgrade control channel
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
assertEquals(result.body.auth, { token: 'abc' });
} finally {
+5 -5
View File
@@ -7,14 +7,14 @@
// 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 { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { runtime: 'deno' } };
}
}
@@ -24,7 +24,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -49,7 +49,7 @@ function freePort(): number {
/** 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 });
const server = await serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
+6 -6
View File
@@ -1,4 +1,4 @@
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming
// Real Deno integration test for mesh: a teapot exporting its steps and a teacup consuming
// them, both under the actual Deno runtime, driven entirely through serveDeno.
//
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
@@ -13,14 +13,14 @@
// including Node-only modules this test never executes. tsc covers those.
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@@ -30,7 +30,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -46,7 +46,7 @@ class TeacupModule {}
/** Starts an app on Deno and resolves once its port is known. */
async function serve(app: ReturnType<typeof createApp>) {
let port = 0;
const server = serveDeno(app, {
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
+46 -9
View File
@@ -5,7 +5,7 @@
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { createApp, Route, Get, Module } from '../../src/index.ts';
import { createApp, Route, Get, Module, Provider, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
@@ -30,7 +30,7 @@ const portOf = (server: { addr?: { port: number } }): number => server.addr!.por
// 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: () => {} });
const server = await 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
@@ -45,7 +45,7 @@ Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without for
});
Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => {
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const server = await 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
@@ -58,7 +58,7 @@ Deno.test('serveDeno close() drains an in-flight request rather than cutting it'
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: () => {} });
const server = await 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
@@ -72,15 +72,52 @@ Deno.test('serveDeno close() runs registered teardown', async () => {
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');
})],
plugins: [{
name: 'teardown-probe',
mount: (api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
}),
}],
});
const server = serveDeno(app, { port: 0 });
const server = await 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(',')}`);
});
// The boot gate, which is why serveDeno is async. Before it, a provider that threw was memoized as
// a rejection and answered 500 to every request from the runtime, never reaching onError — so the
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
@Provider({ provides: 'key' })
class BadKey {
provide(): never {
throw new Error('no such key file');
}
}
@Route('/')
class NeedsKey {
@Get('/signed')
signed(@needs('key') key: string) {
return { key };
}
}
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
class KeyModule {}
Deno.test('serveDeno rejects when a provider fails, instead of binding a port that 500s', async () => {
const app = createApp({ modules: [KeyModule] });
let message = '';
try {
await serveDeno(app, { port: 0, onListen: () => {} });
} catch (error) {
message = (error as Error).message;
}
if (!message.includes('no such key file')) {
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
}
});
+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();
});
+1 -1
View File
@@ -37,7 +37,7 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
const app = createApp({ modules: [M] });
let port = 0;
const server = serveDeno(app, {
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
+73
View File
@@ -80,3 +80,76 @@ describe('HttpError body', () => {
server.close();
});
});
// `onError` is user code, on the request path, running *after something already went wrong*. An
// unguarded throw here was the worst-timed crash in the framework: the error occurs, the code
// written to report it fails, and the process ends instead of degrading. It was also easy to
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
// route was one request away from exiting.
describe('an onError that throws', () => {
const exploding: ErrorRenderer = () => {
throw new Error('renderer exploded');
};
@Route('/x')
class Boom {
@Get('/boom') boom() {
throw new HttpError(503, 'Service Unavailable');
}
}
@Module({ mountpoint: '/', controllers: [Boom] })
class BoomModule {}
it('falls back to the built-in rendering rather than losing the response', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/x/boom'));
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
});
// The path that needed no thrown handler at all.
it('survives a 404, which the renderer also produces', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/nothing-here'));
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
});
it('reports the renderer as the thing that failed, not the request', async () => {
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
const logger = {
debug() {},
info() {},
warn() {},
error(msg: string, fields?: Record<string, unknown>) {
logged.push({ msg, fields });
},
};
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
await app.fetch(new Request('http://x/x/boom'));
expect(logged).toHaveLength(1);
expect(logged[0].msg).toMatch(/onError/);
// Both errors named, because a reader chasing the wrong one loses an afternoon.
expect(logged[0].fields?.err).toBe('renderer exploded');
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
});
it('answers over a real Node server instead of exiting the process', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const server = await app.listen(0);
const port = (server.address() as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
expect(res.status).toBe(503);
// Still serving — the point of the whole test.
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
await app.close();
});
});
+1
View File
@@ -0,0 +1 @@
served
+1
View File
@@ -0,0 +1 @@
<h1>Dash</h1>
+1
View File
@@ -0,0 +1 @@
<h1>Hi {{ name }}</h1>
+29 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, test } from 'vitest';
import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph';
import { topoSort, topoLevels, GraphNode, subgraphFor, nearest } from '../src/graph';
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
({ name, needs, provides, origin: 'test' });
@@ -42,6 +42,34 @@ describe('subgraphFor', () => {
});
});
describe('topoLevels', () => {
const levels = (ordered: GraphNode[]): string[][] => topoLevels(ordered).map((l) => l.map((n) => n.name));
it('puts nodes that cannot constrain each other in the same level', () => {
expect(levels([N('a'), N('b'), N('c')])).toEqual([['a', 'b', 'c']]);
});
it('pushes a node past every producer it needs, not just its first', () => {
// `late` needs a depth-0 and a depth-1 node, so it belongs at 2 — taking the max, not the first.
const ordered = [N('config'), N('db', ['config']), N('late', ['config', 'db'])];
expect(levels(ordered)).toEqual([['config'], ['db'], ['late']]);
});
it('ignores needs nothing here produces, so a seed does not push a node down a level', () => {
expect(levels([N('a'), N('user', ['req', 'params'])])).toEqual([['a', 'user']]);
});
it('leaves no gaps, so every level has something to run', () => {
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
expect(topoLevels(ordered).every((level) => level.length > 0)).toBe(true);
});
it('keeps every node exactly once', () => {
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
expect(topoLevels(ordered).flat().map((n) => n.name).sort()).toEqual(['a', 'b', 'c', 'solo']);
});
});
describe('nearest', () => {
it('suggests a close candidate (edit distance <= 2)', () => {
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
+292 -1
View File
@@ -1,4 +1,8 @@
import { describe, expect, it, test } from 'vitest';
import { describe, expect, it, test, vi } from 'vitest';
import * as net from 'node:net';
import { ServerResponse } from 'node:http';
import { once } from 'node:events';
import { Bus } from '../src/bus';
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
@@ -143,6 +147,185 @@ describe('request hardening', () => {
server.close();
});
it('warns when maxConnections drops a real connection and throttles repeated warnings', async () => {
const logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const server = createHttpServer([], [], undefined, undefined, {
logger,
limits: { maxConnections: 1 },
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const first = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(first, 'connect');
const waitForClose = (socket: net.Socket): Promise<void> =>
new Promise((resolve) => {
socket.on('error', () => undefined);
socket.once('close', () => resolve());
});
const second = net.createConnection({ host: '127.0.0.1', port: address.port });
const third = net.createConnection({ host: '127.0.0.1', port: address.port });
const secondClosed = waitForClose(second);
const thirdClosed = waitForClose(third);
try {
await Promise.all([secondClosed, thirdClosed]);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('maxConnections (1) reached \u2014 dropped connection from'),
expect.objectContaining({
maxConnections: 1,
remoteAddress: '127.0.0.1',
}),
);
} finally {
first.destroy();
second.destroy();
third.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
started = resolve;
});
const bus = new Bus();
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
bus.on('request:end', (event) => {
ended.push(event);
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{
limits: { maxConcurrentRequests: 1 },
cors: { origins: 'https://example.com' },
},
);
await new Promise<void>((resolve) => server.listen(0, resolve));
const first = fetch(`${getUrl(server)}/slow`);
await firstStarted;
const rejected = await fetch(`${getUrl(server)}/slow`, {
headers: { origin: 'https://example.com' },
});
expect(rejected.status).toBe(503);
expect(rejected.headers.get('content-type')).toBe('application/json');
expect(rejected.headers.get('retry-after')).toBe('1');
expect(rejected.headers.get('connection')).toBe('close');
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
expect(ended).toHaveLength(1);
expect(ended[0]).toMatchObject({
method: 'GET',
status: 503,
});
expect(ended[0].requestId).toBeTruthy();
release();
const firstResponse = await first;
expect(firstResponse.status).toBe(200);
const afterRelease = await fetch(`${getUrl(server)}/slow`);
expect(afterRelease.status).toBe(200);
server.close();
});
it('releases a request slot when the client disconnects before the handler settles', async () => {
let started!: () => void;
const handlerStarted = new Promise<void>((resolve) => {
started = resolve;
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/hang',
transport: 'buffer',
handler: async () => {
started();
await new Promise(() => {});
return { status: 200, headers: {}, body: 'never' };
},
},
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
[],
undefined,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const responseClosed = new Promise<void>((resolve) => {
server.once('request', (_req, res) => {
res.once('close', resolve);
});
});
const client = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(client, 'connect');
client.write('GET /hang HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n');
await handlerStarted;
client.destroy();
await responseClosed;
const afterDisconnect = await fetch(`${getUrl(server)}/ok`);
expect(afterDisconnect.status).toBe(200);
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
const server = createHttpServer(
@@ -170,4 +353,112 @@ describe('request hardening', () => {
expect(await res.json()).toEqual({ a: '1', b: 'two' });
server.close();
});
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
const warn = vi.fn();
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[],
undefined,
undefined,
{
cors: {
origins: () => {
throw new Error('lookup failed');
},
},
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any,
},
);
await new Promise<void>((r) => server.listen(0, r));
// Only a request carrying an Origin reaches the predicate — which is why a suite that forgets
// the header watches this crash in production instead.
const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } });
expect(res.status).toBe(200);
expect(res.headers.get('access-control-allow-origin')).toBeNull();
expect(warn).toHaveBeenCalled();
// The security headers still land: one broken predicate must not strip the rest.
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
server.close();
});
// `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a
// tenant query. Running one twice for a GET and three times for a preflight charges the caller's
// latency budget and their backend for an answer whose inputs did not change in between.
it('consults a cors.origins predicate once per request, not once per header computation', async () => {
let calls = 0;
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ cors: { origins: () => { calls++; return true; } } },
);
await new Promise<void>((r) => server.listen(0, r));
const origin = { origin: 'https://a.com' };
const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin });
expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetch(`${getUrl(server)}/ping`, {
method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
// No Origin header never reaches the predicate at all — that part was already right.
calls = 0;
await fetch(`${getUrl(server)}/ping`);
expect(calls).toBe(0);
server.close();
});
// `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of
// apps used to pay a closure and an EventEmitter registration per request for a feature that is
// off. Small in absolute terms, and on the hot path, which is why it is asserted rather than
// trusted: a `res.once('close')` is exactly the kind of line that comes back.
it('registers no per-request close listener when no request budget is configured', async () => {
const closeListeners: string[] = [];
// Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only
// needs to see the event name before handing the call straight back to the real one.
const proto = ServerResponse.prototype as unknown as {
once(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
};
const realOnce = proto.once;
const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) {
if (event === 'close') closeListeners.push('close');
return realOnce.call(this, event, listener);
});
try {
const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]);
await new Promise<void>((r) => unlimited.listen(0, r));
expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200);
expect(closeListeners).toHaveLength(0);
unlimited.close();
// With a budget set, the listener is what releases the slot on a client disconnect, so it
// has to come back — the guard is about the unset case, not about dropping the feature.
const limited = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ limits: { maxConcurrentRequests: 4 } },
);
await new Promise<void>((r) => limited.listen(0, r));
expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200);
expect(closeListeners.length).toBeGreaterThan(0);
limited.close();
} finally {
spy.mockRestore();
}
});
});
+4 -4
View File
@@ -10,13 +10,13 @@
// teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}}
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = process.env.MESH_SECRET ?? 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx', runtime: 'node' } };
}
}
@@ -26,7 +26,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
+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 = await 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);
});
});
+184 -10
View File
@@ -1,3 +1,4 @@
import * as net from 'node:net';
import { describe, it, expect } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@@ -20,6 +21,38 @@ class LocalCtl {
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
@Route('/ping')
class PingCtl {
@Get('/')
ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class LocalOnlyModule {}
// A step (not a route handler) needing 'auth' so the missing-dependency check that fires is
// `topoSort`'s — the one that gets the "these teapots did not connect" note — rather than the
// route-level `assertNeedsSatisfiable` check, which is untouched by this change.
@Step({ provides: 'profile', needs: ['auth'] })
class NeedsAuth {
run() {
return { profile: {} };
}
}
@Module({ mountpoint: '/api', steps: [NeedsAuth] })
class NeedsAuthModule {}
/** A free port, taken by opening and immediately closing a server on port 0. */
const freePort = async (): Promise<number> =>
new Promise<number>((resolve) => {
const probe = net.createServer();
probe.listen(0, () => {
const { port } = probe.address() as { port: number };
probe.close(() => resolve(port));
});
});
const collect = () => {
const lines: string[] = [];
return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } };
@@ -27,13 +60,7 @@ const collect = () => {
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 port = await freePort();
const { lines, logger } = collect();
const teacup = createApp({
@@ -78,8 +105,36 @@ describe('mesh boot retry', () => {
});
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);
// exhausting the budget is no longer fatal by itself (that's the point of this change) —
// the boot still fails here because `who` needs 'auth' and nothing local provides it. The
// exact message, not a bare /mesh/ match (which would also match this message's own
// "(local or connected mesh)" wording for an unrelated reason).
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(
/needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i,
);
expect(lines.some((l) => l.includes('starting without it'))).toBe(true);
} finally {
await teacup.close();
}
}, 15_000);
it('names the absent teapot when a route handler needs its token directly', async () => {
// `who` needs 'auth' via `@needs`, not through a `@Step` — this goes through
// `assertNeedsSatisfiable`, a different check than `topoSort`'s, and must carry the same note.
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }],
secret: 's',
bootTimeoutMs: 300,
},
});
try {
await expect(teacup.ready()).rejects.toThrow(
/needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect.*127\.0\.0\.1:9/i,
);
} finally {
await teacup.close();
}
@@ -116,6 +171,123 @@ describe('mesh boot retry', () => {
}
}, 40_000);
it('boots when a teapot is unreachable and nothing local needs it', async () => {
const teacup = createApp({
modules: [LocalOnlyModule], // declares no needs on a remote token
experimental: true,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }],
secret: 's',
bootTimeoutMs: 300,
},
});
try {
await expect(teacup.ready()).resolves.toBeUndefined();
const res = await teacup.fetch(new Request('http://x/api/ping'));
expect(res.status).toBe(200);
} finally {
await teacup.close();
}
}, 15_000);
it('names the teapot in the log a later 404 points back to', async () => {
// A route the absent teapot would have exported 404s, because nothing was ever registered for a
// manifest that never arrived. That is the right status — you cannot serve what was never
// declared — but a bare 404 is indistinguishable from a typo in the path. The boot log is the
// only place the two are told apart, so it has to name *which* teapot and say that no manifest
// was exchanged. The unreachable error itself is a socket error and does not reliably carry
// the url, so the url is passed in rather than scraped out of the message.
const { lines, logger } = collect();
const teacup = createApp({
modules: [LocalOnlyModule],
experimental: true,
logger,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }],
secret: 's',
bootTimeoutMs: 300,
},
});
try {
await teacup.ready();
const gaveUp = lines.find((line) => line.includes('starting without it'));
expect(gaveUp).toBeDefined();
expect(gaveUp).toContain('ws://127.0.0.1:9/x');
expect(gaveUp).toMatch(/no manifest was ever exchanged/i);
expect(gaveUp).toMatch(/404/);
// and the retry lines on the way there name it too, so a deploy tailing logs sees which one
expect(lines.some((line) => /retrying/.test(line) && line.includes('ws://127.0.0.1:9/x'))).toBe(true);
} finally {
await teacup.close();
}
}, 15_000);
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
const teacup = createApp({
modules: [NeedsAuthModule], // a step with needs: ['auth']
experimental: true,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }],
secret: 's',
bootTimeoutMs: 300,
},
});
try {
await expect(teacup.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
} finally {
await teacup.close();
}
}, 15_000);
it('leaves no reconnect supervisor behind when the boot never reached its teapot', async () => {
// Every failed boot attempt used to leak one. `openSession`'s abort listener runs `onEnd` even
// when the connect promise *rejects*, and `onEnd` schedules a retry — but a link that never
// resolved was never handed to anyone, so it was never pushed to `meshLinks` and `close()`
// could not reach it. Before the app was allowed to start without a teapot the process died
// with them; now it survives, and each one holds a socket open forever.
const port = await freePort();
const { logger } = collect();
const teacupConnects: string[] = [];
const teacup = createApp({
modules: [LocalOnlyModule], // nothing local needs the teapot, so the boot is allowed to finish
experimental: true,
logger,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }],
timeoutMs: 200,
bootTimeoutMs: 600, // several attempts, each of which used to leave a supervisor running
reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, // a leak would hammer, not trickle
},
});
teacup.bus.on('mesh:connect', (event) => teacupConnects.push(event.name));
await teacup.ready();
await teacup.close();
// Only now does the teapot arrive. Nothing in this process holds a link to it.
const teapotConnects: string[] = [];
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
teapot.bus.on('mesh:connect', (event) => teapotConnects.push(event.name));
const server = await teapot.listen(port);
try {
await new Promise((r) => setTimeout(r, 500)); // ~8 retries at the bounds above
expect(teacupConnects).toEqual([]);
// the teapot side, so this fails on a socket that opened even if the teacup never adopted it
expect(teapotConnects).toEqual([]);
} finally {
await teapot.close();
server.close();
}
}, 15_000);
it('bootTimeoutMs: 0 makes one attempt, as before', async () => {
const { lines, logger } = collect();
const teacup = createApp({
@@ -130,7 +302,9 @@ describe('mesh boot retry', () => {
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(
/needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i,
);
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
} finally {
await teacup.close();
+2 -2
View File
@@ -103,7 +103,7 @@ describe('mesh rpc errors', () => {
const frame = decode(data.toString());
if (!authed && frame.type === 'hello') {
authed = true;
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
ws.send(encode({ type: 'manifest', v: V, steps: ['billing'], routes: [] }));
return;
}
if (frame.type === 'rpc-req') {
@@ -130,7 +130,7 @@ describe('teapot hardening', () => {
const control = () =>
createMeshControl({
secret: 'good',
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
manifest: { steps: ['auth'], routes: [] },
resolveScope: async () => 'value',
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
});
+111 -9
View File
@@ -3,9 +3,9 @@ import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx' } };
}
}
@@ -22,9 +22,40 @@ class SvcCtl {
return { pong: true };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [SvcCtl] })
@Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [SvcCtl] })
class TeapotModule {}
/** A step slow enough that the teapot can be killed while its RPC is still on the wire. */
@Step({ provides: 'slow', needs: [], export: true })
class Slow {
async run() {
await new Promise((resolve) => setTimeout(resolve, 2_000));
return { slow: { done: true } };
}
}
@Route('/svc')
class SlowRouteCtl {
@Get('/slow', { export: true })
async slow() {
await new Promise((resolve) => setTimeout(resolve, 2_000));
return { done: true };
}
}
@Module({ mountpoint: '/api', steps: [Slow], controllers: [SlowRouteCtl] })
class SlowTeapotModule {}
@Route('/local')
class SlowCtl {
@Get('/slow')
slow(@needs('slow') slow: any) {
return { slow };
}
}
@Module({ mountpoint: '/api', controllers: [SlowCtl] })
class SlowTeacupModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
@@ -85,10 +116,59 @@ describe('mesh link failure', () => {
await teacup.close();
});
it('keeps serving an app-scope remote from cache after the link drops', async () => {
// Not a bug, but worth pinning: an app-scope export is resolved once and memoised, so it
// survives its teapot — with a value that can go stale. Reconciling on reconnect is a
// known gap (see the mesh guide), and this test is what would catch it changing by accident.
// The tests above kill the teapot *between* requests, so the link is already down when the next
// one arrives and `rpc` fails before it sends anything. These two kill it with the RPC in flight,
// which is the case that can hang: the request is parked on a promise waiting for an `rpc-res`
// frame that is never coming. `endSession` has to reject what was waiting, not just stop
// accepting new work. The assertion is on 503 specifically rather than "not 200" — a 504 would
// mean the per-RPC timeout caught it instead, which is a much slower and much worse answer.
it('answers 503 when the teapot dies with a step RPC still in flight', async () => {
const teapot = createApp({ modules: [SlowTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [SlowTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
await teacup.ready();
const inFlight = teacup.fetch(new Request('http://x/api/local/slow'));
await new Promise((r) => setTimeout(r, 100)); // let the rpc-req reach the teapot
await teapot.close();
const res = await inFlight;
expect(res.status).toBe(503);
await teacup.close();
}, 10_000);
it('answers 503 when the teapot dies with a proxied route RPC still in flight', async () => {
const teapot = createApp({ modules: [SlowTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [SlowTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
await teacup.ready();
const inFlight = teacup.fetch(new Request('http://x/api/svc/slow'));
await new Promise((r) => setTimeout(r, 100));
await teapot.close();
const res = await inFlight;
expect(res.status).toBe(503);
await teacup.close();
}, 10_000);
it('answers 503 on an exported step that used to be a cached app-scope provider', async () => {
// Superseded by "forbid exporting a provider": `config` used to be an app-scope @Provider,
// resolved once and memoised so it kept answering (stale) after the teapot died — a known gap
// the old test pinned on purpose. A provider can no longer be exported at all, so `config` is
// now a @Step like everything else on the wire: request-scope, re-run every time, and gone
// the moment its teapot is. This is the same 503 as the other cases in this file, which is
// the point — there is no more "cached" category left to special-case.
@Route('/cached')
class CachedCtl {
@Get('/cfg')
@@ -113,9 +193,31 @@ describe('mesh link failure', () => {
await new Promise((r) => setTimeout(r, 50));
const after = await teacup.fetch(new Request('http://x/api/cached/cfg'));
expect(after.status).toBe(200); // cached, so still answering
expect(await after.json()).toEqual({ config: { region: 'mx' } });
expect(after.status).toBe(503);
await teacup.close();
});
});
describe('provider export', () => {
it('refuses to boot when a provider is exported over the mesh', async () => {
// `as any` is load-bearing, not laziness: `export` is not in `@Provider`'s options type, so a
// TypeScript caller cannot write this at all. The cast is how the test reaches the runtime
// backstop that a JavaScript caller would hit.
@Provider({ provides: 'db', needs: [], export: true } as any)
class Db {
provide() {
return { db: { query: () => [] } };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class AppModule {}
// `experimental: true` so the boot reaches module/provider collection instead of stopping
// at the earlier "mesh is an alpha feature" gate — this check is about the provider's own
// declared metadata (`export: true` on a factory), not about whether mesh is wired up.
expect(() => createApp({ modules: [AppModule], experimental: true, mesh: { secret: 's' } })).toThrow(
/provider 'db' cannot be exported/i,
);
});
});
+7 -7
View File
@@ -1,14 +1,14 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
import { channel } from '../../src/channel';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
@Step({ provides: 'config', needs: [], export: true })
class Config {
provide() {
run() {
return { config: { region: 'mx' } };
}
}
@@ -18,7 +18,7 @@ class Auth {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
@Module({ mountpoint: '/api', steps: [Config, Auth] })
class TeapotModule {}
@Route('/local')
@@ -134,7 +134,7 @@ describe('mesh over app.fetch (no listen)', () => {
const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`);
// the remote provider and step spliced into the local route's chain
expect(chain).toContain('provider:config');
expect(chain).toContain('step:config');
expect(chain).toContain('step:auth');
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
@@ -183,7 +183,7 @@ describe('mesh over app.fetch (no listen)', () => {
await teacup.ready();
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config');
expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('step:config');
expect(teacup.explain('/api/local/who')).toBeTruthy();
await teacup.close();
@@ -276,7 +276,7 @@ describe('mesh control over app.upgrade (no listen)', () => {
expect(peer.sent[0]).toMatchObject({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]),
steps: expect.arrayContaining(['config']),
});
await teapot.close();
});
+1 -1
View File
@@ -21,7 +21,7 @@ function startTeapot(opts: { answerPings: boolean }) {
seen.push(frame.type);
if (frame.type === 'hello') {
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] }));
ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] }));
}
if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } }));
+53 -4
View File
@@ -1,10 +1,10 @@
import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx' } }; } }
@Step({ provides: 'config', needs: [], export: true })
class Config { run() { return { config: { region: 'mx' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@@ -12,7 +12,7 @@ class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ??
@Route('/remote')
class RemoteCtl { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [RemoteCtl] })
@Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [RemoteCtl] })
class TeapotModule {}
@Route('/local')
@@ -93,6 +93,55 @@ describe('mesh skeleton integration', () => {
tServer.close(); cServer.close();
});
it('re-runs the RPC on every request rather than caching a boot value', async () => {
// A dedicated single-step teapot/teacup pair, not the shared TeapotModule above: exporting
// two scopes (config + auth) makes resolveScope re-run the whole step graph per scope RPC,
// which would make a call counter here track that unrelated behaviour instead of the thing
// this test guards. With one exported step, a per-request counter is unambiguous: a step
// re-runs where a provider used to be resolved once at boot and cached for the process
// lifetime — this is the regression guard for removing the remote app-scope splice, proving
// it does not quietly reintroduce a cached value.
let calls = 0;
@Step({ provides: 'counter', needs: [], export: true })
class Counter {
run() {
calls += 1;
return { counter: calls };
}
}
@Module({ mountpoint: '/api', steps: [Counter] })
class CounterTeapotModule {}
@Route('/local')
class CounterLocalCtl {
@Get('/counter')
counter(@needs('counter') counter: number) {
return { counter };
}
}
@Module({ mountpoint: '/api', controllers: [CounterLocalCtl] })
class CounterTeacupModule {}
const teapot = createApp({ modules: [CounterTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const tPort = (tServer.address() as any).port;
const url = `ws://127.0.0.1:${tPort}/__mesh__/control`;
const teacup = createApp({
modules: [CounterTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const cServer = await teacup.listen(0);
const cPort = (cServer.address() as any).port;
const hit = () => fetch(`http://127.0.0.1:${cPort}/api/local/counter`).then((r) => r.json() as Promise<{ counter: number }>);
expect((await hit()).counter).toBe(1);
expect((await hit()).counter).toBe(2);
tServer.close(); cServer.close();
});
it('mesh is gated behind experimental: true', () => {
expect(() => createApp({ modules: [TeapotModule], mesh: { secret: SECRET } })).toThrow(/alpha feature/);
});
+6 -6
View File
@@ -16,7 +16,7 @@ function startTeapot(secret = 'good') {
ws.on('message', (d) => {
const f = decode(d.toString());
if (!authed) {
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] })); }
else ws.close(1008);
return;
}
@@ -36,7 +36,7 @@ function startSilentTeapot(secret = 'good') {
wss.on('connection', (ws) => {
ws.on('message', (d) => {
const f = decode(d.toString());
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
// ignore rpc-req entirely
});
});
@@ -48,7 +48,7 @@ function startSilentTeapot(secret = 'good') {
function startSkewedTeapot() {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any)));
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, steps: [], routes: [] } as any)));
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
@@ -68,7 +68,7 @@ describe('WebSocket client implementations', () => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good', Ctor });
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
expect(link.manifest.steps).toEqual(['auth']);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
link.close();
t.close();
@@ -86,7 +86,7 @@ describe('connectLink', () => {
wss.on('connection', (ws) =>
ws.on('message', (d) => {
seen.push(decode(d.toString()));
ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
}),
);
const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`;
@@ -105,7 +105,7 @@ describe('connectLink', () => {
it('handshakes and exposes the manifest', async () => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good' });
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
expect(link.manifest.steps).toEqual(['auth']);
link.close(); t.close();
});
+33 -4
View File
@@ -11,7 +11,7 @@ describe('protocol codec', () => {
{
type: 'manifest',
v: V,
scopes: [{ token: 'auth', scope: 'request' }],
steps: ['auth'],
routes: [{ method: 'GET', pattern: '/u/:id' }],
},
{ type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env },
@@ -21,6 +21,35 @@ describe('protocol codec', () => {
for (const f of frames) expect(decode(encode(f))).toEqual(f);
});
it('encodes a manifest of step names', () => {
const frame = decode(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] }));
expect(frame).toEqual({ type: 'manifest', v: V, steps: ['auth'], routes: [] });
});
it('rejects a manifest whose steps are not an array', () => {
expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: 'auth', routes: [] }))).toThrow(
/steps and routes must be arrays/,
);
});
it('rejects a manifest whose steps array contains a non-string element', () => {
expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [123], routes: [] }))).toThrow(
/every step must be a string/,
);
});
it('rejects a manifest whose routes array contains a malformed entry', () => {
// Not a hole that was open — `compilePattern` would have thrown downstream — but it threw a
// `TypeError` at boot instead of naming the peer's frame as the malformed thing it is.
const routes = [{ method: 5, pattern: {} }];
expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [], routes }))).toThrow(
/every route must have a string method and pattern/,
);
expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [], routes: ['GET /x'] }))).toThrow(
/every route must have a string method and pattern/,
);
});
it('throws on malformed json', () => {
expect(() => decode('{not json')).toThrow();
});
@@ -46,7 +75,7 @@ describe('protocol codec', () => {
describe('protocol versioning', () => {
it('carries the protocol version on the handshake frames', () => {
const hello = decode(encode({ type: 'hello', v: V, secret: 's' }));
const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
const manifest = decode(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
expect(hello).toMatchObject({ v: V });
expect(manifest).toMatchObject({ v: V });
@@ -54,7 +83,7 @@ describe('protocol versioning', () => {
it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => {
expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i);
expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i);
expect(() => decode(JSON.stringify({ type: 'manifest', steps: [], routes: [] }))).toThrow(/malformed manifest/i);
});
});
@@ -64,7 +93,7 @@ describe('protocol field validation', () => {
it.each([
['hello without secret', { type: 'hello', v: V }],
['hello with non-string secret', { type: 'hello', v: V, secret: 42 }],
['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }],
['manifest with non-array steps', { type: 'manifest', v: V, steps: 'nope', routes: [] }],
['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }],
['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }],
['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }],
+18 -27
View File
@@ -20,7 +20,7 @@ function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true
if (!authed) {
if (frame.type === 'hello' && frame.secret === 'good') {
authed = true;
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
ws.send(encode({ type: 'manifest', v: V, steps: manifest.steps, routes: manifest.routes }));
} else ws.close(1008);
return;
}
@@ -54,13 +54,13 @@ async function freePort(): Promise<number> {
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
const STEPS: Manifest = { steps: ['auth'], routes: [] };
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
describe('mesh reconnection', () => {
it('reconnects to the same teapot and serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
let teapot = await teapotOn(port, STEPS);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
@@ -70,7 +70,7 @@ describe('mesh reconnection', () => {
// the window where the link is down answers immediately rather than after timeoutMs
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
teapot = await teapotOn(port, STEPS, { ok: 'again' });
await settle(300);
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
@@ -80,7 +80,7 @@ describe('mesh reconnection', () => {
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
let teapot = await teapotOn(port, STEPS);
const warnings: string[] = [];
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
@@ -89,11 +89,11 @@ describe('mesh reconnection', () => {
await settle(50);
// comes back exporting nothing — the graph was validated against 'auth' at boot
teapot = await teapotOn(port, { scopes: [], routes: [] });
teapot = await teapotOn(port, { steps: [], routes: [] });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
expect(warnings.some((w) => w.includes("step 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
// logged once per distinct manifest, not once per attempt
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
@@ -103,7 +103,7 @@ describe('mesh reconnection', () => {
it('stops reconnecting once the application closes the link', async () => {
const port = await freePort();
const teapot = await teapotOn(port, SCOPES);
const teapot = await teapotOn(port, STEPS);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
await teapot.close();
@@ -111,7 +111,7 @@ describe('mesh reconnection', () => {
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
// which is what would leave app.close() with a process that cannot exit
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
const revived = await teapotOn(port, STEPS, { ok: 'revived' });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
@@ -120,11 +120,11 @@ describe('mesh reconnection', () => {
it('reconnect: false keeps the old fail-once behaviour', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
let teapot = await teapotOn(port, STEPS);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
await teapot.close();
teapot = await teapotOn(port, SCOPES);
teapot = await teapotOn(port, STEPS);
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
@@ -135,10 +135,7 @@ describe('mesh reconnection', () => {
describe('missingFromManifest', () => {
const booted: Manifest = {
scopes: [
{ token: 'auth', scope: 'request' },
{ token: 'config', scope: 'app' },
],
steps: ['auth', 'config'],
routes: [{ method: 'GET', pattern: '/svc/:id' }],
};
@@ -148,30 +145,24 @@ describe('missingFromManifest', () => {
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
const wider: Manifest = {
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
steps: [...booted.steps, 'billing'],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
};
expect(missingFromManifest(booted, wider)).toEqual([]);
});
it('accepts a route parameter that was only renamed', () => {
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
const renamed: Manifest = { steps: booted.steps, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
expect(missingFromManifest(booted, renamed)).toEqual([]);
});
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
const flipped: Manifest = {
scopes: [
{ token: 'auth', scope: 'app' },
{ token: 'config', scope: 'app' },
],
routes: booted.routes,
};
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
it('reports a step token that vanished, since the graph resolved it under the old manifest', () => {
const shrunk: Manifest = { steps: ['config'], routes: booted.routes };
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
});
it('reports a missing route by method and pattern', () => {
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
const routeless: Manifest = { steps: booted.steps, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
});
});
+6 -7
View File
@@ -3,20 +3,19 @@ import { buildRemote, envelopeFrom } from '../../src/mesh/teacup';
import type { Link } from '../../src/mesh/link';
const fakeLink = (calls: any[]): Link => ({
manifest: { scopes: [{ token: 'config', scope: 'app' }, { token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] },
manifest: { steps: ['config', 'auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] },
rpc: async (kind, name, ctx) => { calls.push({ kind, name, ctx }); return name === 'config' ? { url: 'db://x' } : { id: 'u1' }; },
close() {},
});
describe('teacup buildRemote', () => {
it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => {
it('makes a step node per manifest token, with RPC runners returning merge objects', async () => {
const calls: any[] = [];
const { providers, steps } = buildRemote(fakeLink(calls));
expect(providers.map((p) => p.name)).toEqual(['config']);
expect(steps.map((s) => s.name)).toEqual(['auth']);
expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } });
const { steps } = buildRemote(fakeLink(calls));
expect(steps.map((s) => s.name)).toEqual(['config', 'auth']);
expect(await steps[0].run({})).toEqual({ config: { url: 'db://x' } });
const ctx = { req: {}, params: { id: '9' }, query: {}, body: undefined, headers: { x: '1' } };
expect(await steps[0].run(ctx)).toEqual({ auth: { id: 'u1' } });
expect(await steps[1].run(ctx)).toEqual({ auth: { id: 'u1' } });
expect(calls.find((c) => c.name === 'auth').ctx).toMatchObject({ params: { id: '9' }, headers: { x: '1' } });
});
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more