10 Commits
Author SHA1 Message Date
chrnx 0218508a96 docs(readme): lead with what the framework owns, not with what it is not
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Failing after 3m33s
CI / runtimes (bun) (pull_request) Successful in 33s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 11s
Follows the website copy strategy, translated from marketing register into the
one this file is read in. The strategy's own summary of the change applies
here too: stop selling simplicity because the framework is small, start
selling simplicity because the framework carries the infrastructure.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:44:49 -05:00
chrnx 24feca481c feat: shutdown teardown for plugins, providers and applications
Closing a connection meant writing process.on('SIGTERM') by hand: closeApp
drained the server and mesh links and knew nothing about the graph, and the
Bus had no shutdown event at all, so a plugin could not even observe that the
app was going away.

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:37:31 -05:00
22 changed files with 939 additions and 34 deletions

No files matched your search

+1 -1
View File
@@ -80,4 +80,4 @@ GitHub does not run workflows on fork pull requests until a maintainer approves
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
- New public API needs a note in `README.md`.
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
+63
View File
@@ -8,12 +8,75 @@ npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
## [26.8.0-beta.1] - 2026-08-17
### Added
- **Observability: a correlated lifecycle event stream and an injectable logger.** Every request is
given an id — an incoming `x-request-id` is adopted rather than replaced — and every event of that
request carries it, alongside the matched route *pattern* (never the concrete URL, which would give
a metrics backend one label per distinct path). Each step reports its own duration. `createApp({
logger })` accepts any object with `debug`/`info`/`warn`/`error`; the default writes structured JSON,
or a readable line on a TTY, decided once at boot. Nothing in core writes to `console`, enforced by a
lint rule rather than by intention. `createApp({ logRequests: true })` logs one line per request, off
by default. New exports: `Logger`, `LogLevel`, `LogFields`, `createDefaultLogger`,
`withConsoleFallback`, `logRequests`, `LifecycleEvent`, `EventPayload`, `Correlation`.
No metrics registry and no OpenTelemetry exporter in core — those live outside it, because core
keeps one runtime dependency. A `traceparent` header is carried through untouched for an exporter to
interpret; core implements no propagation spec. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
- **A bounded `close()` on the Deno and Bun adapters**, and `createApp({ shutdownTimeoutMs })` for the
Node one. `app.close()` returns at its no-server guard on Deno and Bun, so the deadline lives on the
server `serveDeno()`/`serveBun()` returns. One difference the deadline cannot hide: Node and Bun
force the remainder shut, while Deno cannot — aborting a server that is already draining throws from
Deno's own listener, so there the deadline bounds how long `close()` waits, not when connections die.
- Shutdown is now an extension point. A `@Provider` may declare `dispose()`, a plugin may call
`api.onShutdown(fn)`, and an application may pass `createApp({ hooks: [{ onShutdown }] })` — three
doors into one registry, so an app closing a connection no longer writes `process.on('SIGTERM')`
by hand. Callbacks are **awaited**, unlike `bus.on` listeners, and take no arguments: whatever
needs closing is already in the closure that registered it.
They run in reverse boot order, so a `cache` that needs `db` closes before the `db` it is holding.
A failing teardown is logged and the rest still run — one broken callback must not leave the
process up. Everything happens inside `close()`'s existing deadline; `createApp({ teardownTimeoutMs })`
reserves a slice of that budget when a connection must get its chance to close, and is rejected at
boot if it exceeds `shutdownTimeoutMs`.
Node, Deno and Bun behave identically — on Deno and Bun the teardown runs from the `close()` on the
server `serveDeno()`/`serveBun()` returned. **The edge cannot participate**: workerd has no
shutdown to intercept, so anything that must be released belongs in the request that acquired it.
Nothing changes for existing code. `Plugin`'s signature is unchanged, `Hooks` methods are optional,
and `dispose()` is called only if present.
- `limits.maxConnections` changes Node's previously unlimited concurrent socket count to a
default cap of `1000`; values `<= 0` leave Node unlimited. Deno and Bun have no equivalent
runtime setting and require a platform or reverse-proxy connection cap.
### Changed
- **`.` and `..` in a request path are now resolved rather than 404'd.** `GET /public/../admin` reaches
a route declared as `/admin`, and `%2e` counts as a dot, so the encoded spelling cannot reach a route
the plain one resolves away from. This is a **behaviour change on Node only**, and it exists to end a
divergence: Deno, Bun and Workers resolve dot segments inside the `Request` constructor before the
framework sees anything, so the same bytes on the wire already reached different routes depending on
where you deployed. Rejecting them — the stricter option, and what this module does for `//` — is not
implementable on three of the four runtimes. If a proxy or WAF in front of you matches on the literal
path, note that it sees `/public/...` where the application now routes `/admin`.
### Fixed
- **Buffered response bodies are narrowed to what the host runtime's `Response` accepts.** A Node
`Buffer` is a `Uint8Array` at runtime but its declared backing store admits `SharedArrayBuffer`, which
`BodyInit` does not — so Deno's types rejected it. This was a real typing hole on the `app.fetch`
path, which is the path Deno, Bun and the edge all use, rather than a JSR formality.
- **`close()`'s shutdown timer is armed before `finish()` is referenced.** The previous ordering relied
on `server.close(cb)` deferring, which is Node's behaviour rather than a guarantee to us, and left a
`ReferenceError` waiting in the shutdown path for whoever changed it.
## [26.8.0-beta.0] - 2026-08-02
### Added
+1 -1
View File
@@ -148,7 +148,7 @@ npm run build
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
- Keep runtime dependencies at zero beyond `reflect-metadata`.
- A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package.
- New public API needs a doc note in `README.md`.
- New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page.
- If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not.
On GitHub, workflows do not run on pull requests from forks until a maintainer approves them, so your first push may sit without any checks for a while. That is not a rejection.
+45 -7
View File
@@ -7,8 +7,13 @@
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
<p align="center">
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
<b>Declare intent. Derive execution.</b><br />
You declare what each step <b>needs</b> and <b>produces</b>; green-tea derives the order,<br />
validates the wiring before it serves traffic, and runs only the slice each route requires.
</p>
<p align="center">
<i>Less infrastructure in your application. Less infrastructure in your head.</i> 🍵
</p>
---
@@ -53,7 +58,33 @@ npm install busboy # multipart/form-data file uploads
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
## Who does the work?
Every backend has the same set of infrastructure decisions. The question is which side of the
`import` they live on.
| Decision | Owned by |
|---|---|
| Execution order | green-tea — derived from `needs`/`provides`, never maintained by hand |
| Dependency validation | green-tea — boot fails when nothing provides a key |
| Which steps a route runs | green-tea — the graph slice its handler actually depends on |
| Streaming mechanics — framing, backpressure, cleanup, disconnects | green-tea |
| OpenAPI projection | green-tea — from the same metadata that runs the app |
| Secure transport defaults | green-tea — headers, CORS, TLS |
| Runtime serving boundary | green-tea — `listen`, `fetch`, `upgrade` per runtime |
| Shutdown sequencing | green-tea — drain, then teardown, inside one deadline |
| **Business rules** | **you** |
That division is the whole design, and it is why `reflect-metadata` is the only runtime dependency:
the goal is not a small number for its own sake, it is **fewer moving parts your team has to
understand, upgrade, coordinate and debug**. A framework that owns less pushes the difference into
your application, where it becomes your maintenance instead of disappearing.
Automated does not mean invisible. `app.explain()` prints the ordered chain, `app.graph()` renders
the live graph, and `app.openapi()` projects the same metadata — the graph is not documentation drawn
after the fact, it is the structure green-tea validates and executes.
## Real-time is a primitive, not a second framework
@@ -98,9 +129,10 @@ class Live {
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
## Batteries included — still one dependency
## What the foundation already carries
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
The parts a real API needs, owned by the framework rather than assembled in your application — and
without growing the runtime dependency tree past `reflect-metadata`:
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
@@ -111,7 +143,8 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, 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.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. `app.close()` is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point, 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.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -252,11 +285,16 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
## Docs & development
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs); a change to public API here needs a matching change there, because nothing fails when the two disagree.
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs).
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
> **Changing public API? The docs are a separate repository now, and nothing tells you when you break them.**
> [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) imports nothing from here, so no build fails and no test turns red when a guide describes an API that no longer exists. **A pull request that changes public API updates the page documenting it, in the same pull request.** This is a rule rather than a check because no check exists yet — issue #18 is what a stale page looks like from a user's side, and that happened while both still lived in this repository.
```bash
npm install
npm test # vitest (Node only) — the fast loop, ~2s
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.8.0-beta.1",
"license": "MIT",
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
@@ -241,6 +241,21 @@ Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`.
The split trades CI coupling for drift risk: docs and code can now disagree without anything failing. #18 exists precisely because docs fell behind an API change. Decide what catches that — a link check against the published package, a docs job triggered from core releases, or an explicit accepted risk written down. Do not leave it unstated.
**Resolved 2026-08-17: accepted risk, stated where the rule is read rather than where it is published.** The first pass put it in both READMEs and stopped there, which satisfies the letter of "do not leave it unstated" and little else — the core README's copy sits in *Docs & development*, a section a user reads and a contributor changing an API does not.
What governs behaviour is `AGENTS.md:83` and the pre-PR checklist in `CONTRIBUTING.md`, both of which already carried *"New public API needs a note in `README.md`"* — written before the split and never updated for it, so the two documents that a contributor (or an assistant) actually reads mid-change said nothing about the new repository. Both now name it and say why the rule exists, since a rule without its reason is the first one dropped under time pressure.
**The link check was prototyped and then rejected, on measurement rather than taste.** It had been recommended here as the one worth building; building enough of it to decide showed otherwise.
- Every symbol the pages import is real: **24 distinct imports from `@green-tea/core` across 25 pages, all present** among the package's 101 exports. No bug for it to find today.
- More decisively, **an import check could not have caught #18**. That issue was *"docs still describe `close()` without the timeout"* — the method existed; the **option** was undocumented. Imports are the part that does not drift. Options, option shapes and method signatures are.
- Extending it to options and methods was tried and produced **17 findings, all 17 false** — a regex cannot tell a nested `tls: { key, cert }` from a top-level option, `app.example.com` in a CORS example from an `app.*` call, or prose describing Express's `app.use()` from a green-tea API. A check with that signal-to-noise trains people to ignore it, which is worse than not having one.
- What would genuinely catch #18's class is **type-checking the code blocks** (twoslash / Expressive Code). That requires the documentation repository to depend on `@green-tea/core` and its examples to be complete and compilable — many are deliberately fragments. It buys the guarantee back by spending exactly the independence this split was for.
So the accepted risk stands, now as an informed choice rather than a default. A **docs job triggered from core releases** was the other option and remains the weaker one: it fires after the API has already shipped.
One page is covered by more than a rule: `test/circuit-breaker-recipe.test.ts` executes the recipe published in `guides/circuit-breaker.md`. That is one page of twenty-five, and is not a substitute for the check above.
---
## Phase 4.5: Move the JSR gate off the tag — **run this before Task 2.5's code**
@@ -122,10 +122,12 @@ Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**:
`timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for.
- Drain runs first. Teardown runs after, within the same budget.
- `teardownTimeoutMs` is optional and defaults to `timeoutMs` — no separate cap, teardown may use whatever the drain left.
- Setting it lower **reserves**: the drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one.
- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
- `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped.
An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement.
Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run.
---
@@ -72,7 +72,7 @@ Tests: `dispose()` is called; a provider without one is skipped; `cache` needing
Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining.
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` defaults to `timeoutMs`; when set lower it **reserves**, so the drain is bounded to `timeoutMs − teardownTimeoutMs` and teardown is guaranteed its slice. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
`closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@green-tea/core",
"version": "26.8.0-beta.0",
"version": "26.8.0-beta.1",
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
"license": "MIT",
"author": "green-tea contributors <projects@expressive-tea.io>",
+142 -12
View File
@@ -12,6 +12,8 @@ import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocke
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle';
import type { Hooks } from './types';
import {
Ctor,
getModuleMeta,
@@ -48,6 +50,13 @@ interface Registry {
stepNodes: GraphNode[];
runners: Map<string, Runner>;
providerMeta: Map<string, { optional: boolean }>;
/**
* The `@Provider` instance behind each node, kept only so a `dispose()` can be reached.
*
* `collectProviders` used to build the instance and let it live on solely inside the runner's
* closure, which meant nothing could ever call a method on it again.
*/
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
routePlans: RoutePlan[];
exportedProviders: string[];
exportedSteps: string[];
@@ -86,6 +95,14 @@ interface PipelineDeps {
export function createApp(opts: {
modules: Ctor[];
plugins?: Plugin[];
/**
* Lifecycle participation without extending the graph.
*
* A plugin means "I want to add nodes"; someone who only needs to close a connection should not
* have to declare an extension they do not want. Methods are optional so later stages can join
* without a breaking change — only `onShutdown` exists today.
*/
hooks?: Hooks[];
mesh?: MeshConfig;
limits?: RequestLimits;
devGraph?: boolean;
@@ -111,6 +128,17 @@ export function createApp(opts: {
* where passing it per call is not an option.
*/
shutdownTimeoutMs?: number;
/**
* Milliseconds reserved out of the shutdown budget for teardown, in ms (default: none reserved).
*
* Teardown runs after the drain and inside the same `timeoutMs`, so `close()` never takes longer
* than the caller asked for. Left unset, the drain may use the whole budget and teardown gets
* whatever remains — possibly nothing. Set it when a connection *must* get its chance to close:
* the drain is then bounded to `timeoutMs - teardownTimeoutMs` and this slice is guaranteed.
*
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
*/
teardownTimeoutMs?: number;
/**
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
*
@@ -158,7 +186,8 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry);
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger);
// For each route, resolve which providers/steps feed it via topo order.
@@ -236,7 +265,7 @@ export function createApp(opts: {
registry,
opts.overrides,
() => orderedProviders,
{ runners, container, providerMeta, bus, logger },
{ runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
degradedProviders,
ready,
);
@@ -292,7 +321,7 @@ export function createApp(opts: {
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger);
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs);
return {
listen,
@@ -327,6 +356,7 @@ function emptyRegistry(): Registry {
stepNodes: [],
runners,
providerMeta: new Map(),
providerInstances: new Map(),
routePlans: [],
exportedProviders: [],
exportedSteps: [],
@@ -343,6 +373,7 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
registry.providerMeta.set(meta.provides, { optional: meta.optional });
if (meta.export) registry.exportedProviders.push(meta.provides);
const instance: any = new ProviderClass();
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
}
}
@@ -459,12 +490,40 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
return registry;
}
/**
* Builds the teardown registry, seeds it with the application's hooks, and validates the reservation.
*
* Hooks land before plugins, so the registry running in reverse tears plugins down before the hooks
* an application registered around them. Both go into the same list: one order, one failure policy.
*/
function buildTeardownRegistry(
hooks: Hooks[] | undefined,
teardownTimeoutMs: number | undefined,
shutdownTimeoutMs: number | undefined,
): TeardownRegistry {
const budget = shutdownTimeoutMs ?? 10_000;
// Rejected rather than clamped: a reservation larger than the budget it is carved from is a
// mistake in the caller's numbers, and quietly shrinking it would hide which of the two they got
// wrong — at boot, where there is time to fix it, rather than during a shutdown.
if (teardownTimeoutMs !== undefined && teardownTimeoutMs > budget) {
throw new Error(
`teardownTimeoutMs (${teardownTimeoutMs}) cannot exceed shutdownTimeoutMs (${budget}) — ` +
'it is reserved out of that budget, not added to it',
);
}
const teardown = new TeardownRegistry();
for (const hook of hooks ?? []) if (hook.onShutdown) teardown.add(hook.onShutdown);
return teardown;
}
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
const extraSteps: ScopeNode[] = [];
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
for (const scopeNode of extraSteps) {
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
@@ -667,11 +726,13 @@ async function bootProviders(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
): Promise<string[]> {
const { runners, container, providerMeta, bus, logger } = deps;
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
const degraded: string[] = [];
for (const node of orderedProviders) {
@@ -681,6 +742,15 @@ async function bootProviders(
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.
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 });
@@ -717,6 +787,8 @@ function makeAppBooter(
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
teardown: TeardownRegistry;
bus: Bus;
logger: Logger;
},
@@ -1006,6 +1078,46 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
}));
}
/**
* Runs registered teardown, bounded so it cannot push `close()` past the budget it was given.
*
* Bounding lives here rather than in {@link TeardownRegistry} because the registry has no business
* knowing about deadlines — `closeApp` and `closeWithDeadline` each already own one, and a third
* implementation is how the three drift into different meanings of the same `timeoutMs`.
*
* A teardown that overruns is left running rather than awaited: the callback is someone else's code
* and there is no way to interrupt it, so the choice is between returning on time and waiting
* indefinitely. It resolves on its own timer for the same reason `closeWithDeadline` does.
*/
function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: number): Promise<void> {
if (teardown.size === 0) return Promise.resolve();
return new Promise<void>((resolve) => {
let settled = false;
const finish = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
const timer = setTimeout(
() => {
if (settled) return;
logger.warn(`shutdown teardown exceeded its ${Math.max(0, budgetMs)}ms budget — returning without it`, {
budgetMs: Math.max(0, budgetMs),
});
finish();
},
Math.max(0, budgetMs),
);
timer.unref?.();
void teardown.run(logger).then(finish, finish);
});
}
function closeApp(
server: http.Server | undefined,
meshLinks: Link[],
@@ -1013,8 +1125,17 @@ function closeApp(
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
logger: Logger,
teardown: TeardownRegistry,
reservedMs: number | undefined,
): Promise<void> {
return new Promise((resolve) => {
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
const startedAt = Date.now();
// Unset reserves nothing: the drain may use the whole budget and teardown takes what is left.
// Set, it is carved out of the same budget rather than added to it, so `close()` still returns
// within `timeoutMs` — which is the whole reason the caller set that number.
const drainBudget = timeoutMs - (reservedMs ?? 0);
const drain = new Promise<void>((resolve) => {
// A mesh app booted through `app.fetch` has links but no server, and would leak every
// teapot connection otherwise — so links close before we even check for a server.
closeLinks(meshLinks);
@@ -1026,16 +1147,20 @@ function closeApp(
if (!server) {
if (options.timeoutMs !== undefined) {
logger.warn(
'close({ timeoutMs }) has no effect here — this app has no listen()ed server. On Deno ' +
'and Bun, call close() on the server serveDeno()/serveBun() returned; it takes the ' +
'same option. On the edge the platform owns the lifecycle.',
'close({ timeoutMs }) does not drain connections here — this app has no listen()ed ' +
'server, so it only bounds teardown. On Deno and Bun, call close() on the server ' +
'serveDeno()/serveBun() returned; it takes the same option and drains too. On the ' +
'edge the platform owns the lifecycle.',
);
}
// Falls through to teardown rather than returning from close(). An app served through
// `app.fetch` still booted its providers, so it still has connections that were opened and
// are owed a close — the transport being someone else's job does not make them not ours.
// Running teardown twice is safe: the registry drains once, whichever entry point is first.
return resolve();
}
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
let settled = false;
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
@@ -1056,7 +1181,7 @@ function closeApp(
// below — `engines` in package.json only guarantees >=18, so this matters.
server.closeAllConnections();
finish();
}, timeoutMs);
}, drainBudget);
timer.unref?.();
@@ -1072,6 +1197,11 @@ function closeApp(
for (const closeStream of streams) closeStream();
server.closeIdleConnections();
});
// Teardown runs after the drain and before close() resolves: an in-flight request may still be
// using the connection a teardown is about to close, so draining first is not an ordering
// preference. It gets whatever is left of the budget — at least the reservation, if one was made.
return drain.then(() => runTeardown(teardown, logger, timeoutMs - (Date.now() - startedAt)));
}
/** Best-effort close of every mesh link, ignoring individual failures. */
+12
View File
@@ -1,6 +1,7 @@
import type http from 'http';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { TeardownFn } from '../lifecycle';
import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata';
@@ -103,3 +104,14 @@ export interface MeshConfig {
*/
heartbeatMs?: number;
}
/**
* Lifecycle participation for an application that does not want to be a plugin.
*
* Every method is optional, and the shape is an object rather than a single callback so later
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
*/
export interface Hooks {
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
onShutdown?: TeardownFn;
}
+6 -1
View File
@@ -119,7 +119,12 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.stop(false),
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.stop(false).then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
+6 -1
View File
@@ -78,7 +78,12 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline(
() => server.shutdown(),
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.shutdown().then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
+7
View File
@@ -15,6 +15,13 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*/
export function edgeHandler(
app: App,
+70
View File
@@ -0,0 +1,70 @@
// src/lifecycle.ts — the teardown registry. Knows nothing about plugins, providers, apps or HTTP;
// the doors into it live where those things do.
import type { Logger } from './logger';
/**
* Something to run before the app goes away.
*
* Takes no arguments on purpose. State lives in the closure that registered it — a provider's
* `dispose()` already holds its own connection, and a plugin's callback already holds whatever the
* plugin built. Nothing has to cross a scope, which is what makes this a registry rather than an
* event bus: a bus solves "tell someone I do not know", and this is "run the thing I registered".
*/
export type TeardownFn = () => void | Promise<void>;
/**
* Await-aware teardown, deliberately not the {@link Bus}.
*
* `Bus.on` takes a synchronous listener and `emit` swallows failures, both so that an observer can
* never break the pipeline. A teardown needs the opposite of each: it must be awaited, and its
* failure must be visible. Same word, opposite guarantees — see D1 of the design.
*
* Bounding is deliberately *not* here. `closeApp` and `closeWithDeadline` already implement a
* deadline each, and a third implementation is how the three drift into different meanings of the
* same `timeoutMs`.
*/
export class TeardownRegistry {
private readonly callbacks: TeardownFn[] = [];
private drained = false;
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
add(fn: TeardownFn): void {
this.callbacks.push(fn);
}
/** How many callbacks are registered; lets a caller skip the whole path when nothing wants it. */
get size(): number {
return this.callbacks.length;
}
/**
* Run every callback, newest first, awaiting each.
*
* **Reverse registration order is load-bearing.** Providers register as they boot, and they boot
* in topological order, so reversing registration is what gives dependants teardown before their
* dependencies: a `cache` that needs `db` closes before the `db` it is still holding.
*
* Sequential rather than parallel, for the same reason — an order only means something if it is
* waited on.
*
* A failing callback is reported and the next one still runs. One broken teardown must not strand
* the rest or leave the process up. This mirrors `Bus`'s "a subscriber cannot break the system",
* but with the visibility `Bus` lacks: `Bus` swallows silently because no logger existed when it
* was written, and one exists now.
*
* Never throws, and never runs twice — `close()` is called twice by more real applications than
* anyone expects, and a second call must not re-close what the first one closed.
*/
async run(logger: Logger): Promise<void> {
if (this.drained) return;
this.drained = true;
for (let index = this.callbacks.length - 1; index >= 0; index--) {
try {
await this.callbacks[index]();
} catch (error) {
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
}
}
}
}
+21 -4
View File
@@ -1,4 +1,5 @@
import { Bus } from './bus';
import type { TeardownFn } from './lifecycle';
/** A step or provider a plugin contributes to the graph. */
export interface ScopeNode {
@@ -13,18 +14,34 @@ export interface ScopeNode {
export interface ScopeApi {
add(node: ScopeNode): void;
}
/** The capabilities handed to a plugin: event subscription and node registration only. */
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
/**
* Run something before the app closes — closing a pool, stopping a timer, flushing a buffer.
*
* Takes no arguments: whatever needs closing is already in the closure of the plugin that opened
* it. It is awaited, unlike a `bus.on` listener, and a failure is logged rather than swallowed.
*/
onShutdown(fn: TeardownFn): void;
}
/** A plugin: a function that wires itself up through the provided PluginApi. */
export type Plugin = (api: PluginApi) => void;
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void {
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
// Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
//
// "Isolation is structural" means this list and nothing else — it is a guarantee about the
// *registration surface*, not about the request context. A plugin's step receives the live
// context like any other step and can overwrite keys in it (`src/pipeline.ts`, `Object.assign`),
// which is a separate, pre-existing question this list has never covered.
//
// `onShutdown` is the first capability here the framework must *wait* for: nothing a plugin did
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
// caps the whole shutdown.
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
plugin(api);
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
}
+20
View File
@@ -49,3 +49,23 @@ test('serveBun close() drains an in-flight request rather than cutting it', asyn
expect(await inFlight).toEqual({ ok: true });
});
// D7 of the teardown design: proving the Node path works proves nothing here, because app.close()
// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses.
test('serveBun close() runs registered teardown', async () => {
const closed: string[] = [];
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await Bun.sleep(10);
closed.push('plugin');
})],
});
const server = serveBun(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
expect(closed).toEqual(['plugin', 'hook']);
});
+164
View File
@@ -0,0 +1,164 @@
// Executes the circuit-breaker recipe published at
// https://green-tea.expressive-tea.io/docs/guides/circuit-breaker/
//
// The recipe lives in the documentation repository, which imports nothing from here, so nothing
// fails when the two drift apart. This is the smallest thing that makes the page's load-bearing
// claims executable rather than merely written: that breaker state survives across requests (which
// is why it is a provider and not a step), that the window re-opens, and that a failed trial in
// half-open re-opens immediately instead of earning the threshold again.
//
// Keep the class below identical to the page. If you change one, change both.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import { Provider, Module, Route, Get } from '../src/metadata';
import { createApp } from '../src/app';
import { HttpError } from '../src/signals';
import { needs } from '../src/params';
// ---- the recipe, verbatim ---------------------------------------------------------------------
type BreakerState = 'closed' | 'open' | 'half-open';
class CircuitBreaker {
#state: BreakerState = 'closed';
#failures = 0;
#openedAt = 0;
constructor(
private readonly threshold: number,
private readonly resetMs: number,
private readonly now: () => number = Date.now,
) {}
get state(): BreakerState {
return this.#state;
}
async call<T>(operation: () => Promise<T>): Promise<T> {
if (this.#state === 'open') {
if (this.now() - this.#openedAt < this.resetMs) {
throw new HttpError(503, 'billing is unavailable');
}
this.#state = 'half-open';
}
try {
const result = await operation();
this.#state = 'closed';
this.#failures = 0;
return result;
} catch (error) {
this.#failures++;
if (this.#state === 'half-open' || this.#failures >= this.threshold) {
this.#state = 'open';
this.#openedAt = this.now();
}
throw error;
}
}
}
interface BillingApi {
charge(userId: string): Promise<{ ok: true }>;
}
@Provider({ provides: 'billing', needs: ['billingApi'] })
class GuardedBilling {
#breaker = new CircuitBreaker(3, 30_000);
provide({ billingApi }: { billingApi: BillingApi }) {
return {
billing: {
charge: (userId: string) => this.#breaker.call(() => billingApi.charge(userId)),
},
billingBreaker: this.#breaker,
};
}
}
// ---- the test ---------------------------------------------------------------------------------
describe('circuit-breaker recipe', () => {
it('opens after the threshold and short-circuits, sharing state across requests', async () => {
let calls = 0;
@Provider({ provides: 'billingApi' })
class FailingBilling {
provide() {
return {
billingApi: {
charge: async () => {
calls++;
throw new Error('upstream down');
},
} satisfies BillingApi,
};
}
}
@Route('/')
class Ctl {
@Get('/pay')
async pay(@needs('billing') billing: { charge(id: string): Promise<unknown> }) {
try {
await billing.charge('u1');
return { ok: true };
} catch (error) {
return { failed: (error as Error).message };
}
}
}
@Module({ mountpoint: '/', providers: [FailingBilling, GuardedBilling], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const hit = async () => (await (await app.fetch(new Request('http://x/pay'))).json()) as { failed: string };
// Three real attempts trip it; the fourth never reaches the upstream. The breaker survives
// across requests, which is the whole reason it is a provider and not a step.
expect((await hit()).failed).toBe('upstream down');
expect((await hit()).failed).toBe('upstream down');
expect((await hit()).failed).toBe('upstream down');
expect(calls).toBe(3);
expect((await hit()).failed).toBe('billing is unavailable');
expect(calls).toBe(3); // short-circuited — upstream was not called again
await app.close();
});
it('half-opens after the reset window and closes again on success', async () => {
let clock = 0;
let fail = true;
const breaker = new CircuitBreaker(2, 1000, () => clock);
const call = () =>
breaker.call(async () => {
if (fail) throw new Error('down');
return 'ok';
});
await expect(call()).rejects.toThrow('down');
await expect(call()).rejects.toThrow('down');
expect(breaker.state).toBe('open');
await expect(call()).rejects.toThrow('billing is unavailable'); // still inside the window
clock = 2000;
fail = false;
await expect(call()).resolves.toBe('ok');
expect(breaker.state).toBe('closed');
});
it('re-opens when the trial request in half-open fails', async () => {
let clock = 0;
const breaker = new CircuitBreaker(1, 1000, () => clock);
await expect(breaker.call(async () => Promise.reject(new Error('down')))).rejects.toThrow('down');
expect(breaker.state).toBe('open');
clock = 2000;
await expect(breaker.call(async () => Promise.reject(new Error('down')))).rejects.toThrow('down');
expect(breaker.state).toBe('open'); // one failed trial is enough, threshold not restarted
});
});
+21
View File
@@ -63,3 +63,24 @@ Deno.test('a caller-supplied signal still aborts the server', async () => {
ac.abort();
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
});
// D7 of the teardown design: a teardown must run on every runtime that has a shutdown, and it must
// run from the close() the runtime actually uses. app.close() returns at its no-server guard here,
// so proving the Node path works proves nothing about this one — hence a Deno assertion of its own.
Deno.test('serveDeno close() runs registered teardown', async () => {
const closed: string[] = [];
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void closed.push('hook') }],
plugins: [(api) => api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 10));
closed.push('plugin');
})],
});
const server = serveDeno(app, { port: 0 });
await server.close({ timeoutMs: 2000 });
// Reverse registration order: the plugin registered after the hook, so it tears down first.
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect, vi } from 'vitest';
import { TeardownRegistry, type TeardownFn } from '../src/lifecycle';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
describe('TeardownRegistry', () => {
it('runs callbacks newest first, so a dependant tears down before its dependency', async () => {
const order: string[] = [];
const registry = new TeardownRegistry();
// Providers register as they boot, and they boot in topological order — so `db` registering
// before `cache` is what a `cache` needing `db` actually looks like here.
registry.add(() => void order.push('db'));
registry.add(() => void order.push('cache'));
await registry.run(silentLogger());
expect(order).toEqual(['cache', 'db']);
});
it('awaits each callback before starting the next', async () => {
const order: string[] = [];
const registry = new TeardownRegistry();
registry.add(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
order.push('slow');
});
registry.add(() => void order.push('fast'));
await registry.run(silentLogger());
// 'fast' is registered last so it runs first; 'slow' must still have finished by return.
expect(order).toEqual(['fast', 'slow']);
});
it('logs a throwing callback and still runs the rest', async () => {
const logger = silentLogger();
const order: string[] = [];
const registry = new TeardownRegistry();
registry.add(() => void order.push('first'));
registry.add(() => {
throw new Error('boom');
});
registry.add(() => void order.push('third'));
await expect(registry.run(logger)).resolves.toBeUndefined();
expect(order).toEqual(['third', 'first']);
expect(logger.warn).toHaveBeenCalledOnce();
expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/boom/);
});
it('treats a rejecting async callback the same as a throwing one', async () => {
const logger = silentLogger();
const registry = new TeardownRegistry();
registry.add(() => Promise.reject(new Error('async boom')));
registry.add(() => Promise.resolve());
await expect(registry.run(logger)).resolves.toBeUndefined();
expect(vi.mocked(logger.warn).mock.calls[0][0]).toMatch(/async boom/);
});
it('does not re-run callbacks on a second close()', async () => {
let runs = 0;
const registry = new TeardownRegistry();
registry.add(() => void runs++);
await registry.run(silentLogger());
await registry.run(silentLogger());
expect(runs).toBe(1);
});
it('resolves when nothing is registered, and reports an empty size', async () => {
const registry = new TeardownRegistry();
expect(registry.size).toBe(0);
await expect(registry.run(silentLogger())).resolves.toBeUndefined();
});
it('reports how many callbacks are registered', () => {
const registry = new TeardownRegistry();
const noop: TeardownFn = () => {};
registry.add(noop);
registry.add(noop);
expect(registry.size).toBe(2);
});
});
+37 -2
View File
@@ -1,6 +1,9 @@
import { expect, test, vi } from 'vitest';
import { Bus } from '../src/bus';
import { mountPlugin, Plugin, ScopeApi } from '../src/plugin';
import type { TeardownFn } from '../src/lifecycle';
const noTeardown = (): ((fn: TeardownFn) => void) => () => {};
test('plugin can observe via bus.on and add to its own scope', () => {
const bus = new Bus();
@@ -14,7 +17,7 @@ test('plugin can observe via bus.on and add to its own scope', () => {
const mounted = vi.fn();
bus.on('plugin:mounted', mounted);
mountPlugin(logger, bus, scope);
mountPlugin(logger, bus, scope, noTeardown());
expect(added).toEqual(['log']);
expect(mounted).toHaveBeenCalled();
@@ -26,5 +29,37 @@ test('plugin api does NOT expose bus.emit', () => {
const plugin: Plugin = (api) => {
expect((api.bus as any).emit).toBeUndefined();
};
mountPlugin(plugin, bus, scope);
mountPlugin(plugin, bus, scope, noTeardown());
});
test('plugin can register a teardown, and it reaches the registry', () => {
const bus = new Bus();
const registered: TeardownFn[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {});
};
mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn));
expect(registered).toHaveLength(1);
});
// D3's no-break guarantee, asserted rather than assumed: `Plugin`'s signature did not change, so a
// plugin written before this capability existed must mount and behave exactly as it did.
test('a plugin that never calls onShutdown behaves exactly as before', () => {
const bus = new Bus();
const added: string[] = [];
const registered: TeardownFn[] = [];
const legacy: Plugin = (api) => {
api.bus.on('stream:open', () => {});
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) });
};
const mounted = vi.fn();
bus.on('plugin:mounted', mounted);
mountPlugin(legacy, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn));
expect(added).toEqual(['thing']);
expect(mounted).toHaveBeenCalled();
expect(registered).toHaveLength(0);
});
+215
View File
@@ -0,0 +1,215 @@
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { Provider, Module, Route, Get } from '../src/metadata';
import { createApp } from '../src/app';
import type { Plugin } from '../src/plugin';
import type { Logger } from '../src/logger';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
}
describe('shutdown teardown', () => {
it('awaits a plugin onShutdown before close() resolves', async () => {
const order: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('plugin torn down');
});
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
await app.close();
order.push('close returned');
expect(order).toEqual(['plugin torn down', 'close returned']);
});
it('runs a hook onShutdown without the app declaring a plugin', async () => {
const seen: string[] = [];
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({
modules: [M],
hooks: [{ onShutdown: () => void seen.push('hook') }],
logger: silentLogger(),
});
await app.listen(0);
await app.close();
expect(seen).toEqual(['hook']);
});
it('calls a provider dispose(), and skips a provider without one', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
async dispose() {
closed.push('db');
}
}
@Provider({ provides: 'plain' })
class Plain {
provide() {
return { plain: {} };
}
}
@Module({ mountpoint: '/', providers: [Db, Plain], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual(['db']);
});
// D5, and the reason dispose() is registered as a provider boots rather than as it is collected.
it('tears a dependant down before the dependency it needs', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
dispose() {
closed.push('db');
}
}
@Provider({ provides: 'cache', needs: ['db'] })
class Cache {
provide() {
return { cache: {} };
}
dispose() {
closed.push('cache');
}
}
// Declared dependency-last on purpose: the order must come from the graph, not the array.
@Module({ mountpoint: '/', providers: [Cache, Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual(['cache', 'db']);
});
it('does not dispose a provider that failed to boot', async () => {
const closed: string[] = [];
@Provider({ provides: 'broken', optional: true })
class Broken {
provide(): unknown {
throw new Error('cannot connect');
}
dispose() {
closed.push('broken');
}
}
@Module({ mountpoint: '/', providers: [Broken], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.listen(0);
await app.close();
expect(closed).toEqual([]);
});
it('logs a failing teardown, runs the rest, and still resolves', async () => {
const logger = silentLogger();
const closed: string[] = [];
const plugin: Plugin = (api) => {
api.onShutdown(() => {
throw new Error('teardown boom');
});
api.onShutdown(() => void closed.push('survivor'));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger });
await app.listen(0);
await expect(app.close()).resolves.toBeUndefined();
expect(closed).toEqual(['survivor']);
expect(vi.mocked(logger.warn).mock.calls.some((c) => /teardown boom/.test(c[0]))).toBe(true);
});
it('does not let a hanging teardown push close() past its deadline', async () => {
const plugin: Plugin = (api) => {
api.onShutdown(() => new Promise<void>(() => {})); // never settles
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
const startedAt = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - startedAt).toBeLessThan(1500);
});
it('rejects a reservation larger than the budget it comes out of', () => {
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M], shutdownTimeoutMs: 1000, teardownTimeoutMs: 2000 })).toThrow(
/cannot exceed shutdownTimeoutMs/,
);
});
it('tears down an app that was never listen()ed, since its providers still booted', async () => {
const closed: string[] = [];
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: {} };
}
dispose() {
closed.push('db');
}
}
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], logger: silentLogger() });
await app.fetch(new Request('http://x/ping')); // boots providers, no server
await app.close();
expect(closed).toEqual(['db']);
});
it('drains only once when close() is called twice', async () => {
let runs = 0;
const plugin: Plugin = (api) => {
api.onShutdown(() => void runs++);
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
await app.listen(0);
await app.close();
await app.close();
expect(runs).toBe(1);
});
});