Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0218508a96 | ||
|
|
41c1f4308b | ||
|
|
bb75cabeea | ||
|
|
bead3c1569 | ||
|
|
0414aff665 | ||
|
|
21765c2a47 | ||
|
|
cd6e2f073f | ||
|
|
38b73cebce | ||
|
|
62d0b7aa3a | ||
|
|
24feca481c |
No files matched your search
@@ -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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
@@ -8,12 +8,75 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [26.8.0-beta.1] - 2026-08-17
|
||||||
|
|
||||||
### Added
|
### 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
|
- `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
|
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.
|
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
|
## [26.8.0-beta.0] - 2026-08-02
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+1
-1
@@ -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.
|
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
|
||||||
- Keep runtime dependencies at zero beyond `reflect-metadata`.
|
- Keep runtime dependencies at zero beyond `reflect-metadata`.
|
||||||
- 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.
|
- 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.
|
- 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.
|
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.
|
||||||
|
|||||||
@@ -7,8 +7,13 @@
|
|||||||
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
|
<b>Declare intent. Derive execution.</b><br />
|
||||||
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
|
You declare what each step <b>needs</b> and <b>produces</b>; green-tea derives the order,<br />
|
||||||
|
validates the wiring before it serves traffic, and runs only the slice each route requires.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<i>Less infrastructure in your application. Less infrastructure in your head.</i> 🍵
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -53,7 +58,33 @@ npm install busboy # multipart/form-data file uploads
|
|||||||
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||||
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||||
|
|
||||||
|
## Who does the work?
|
||||||
|
|
||||||
|
Every backend has the same set of infrastructure decisions. The question is which side of the
|
||||||
|
`import` they live on.
|
||||||
|
|
||||||
|
| Decision | Owned by |
|
||||||
|
|---|---|
|
||||||
|
| Execution order | green-tea — derived from `needs`/`provides`, never maintained by hand |
|
||||||
|
| Dependency validation | green-tea — boot fails when nothing provides a key |
|
||||||
|
| Which steps a route runs | green-tea — the graph slice its handler actually depends on |
|
||||||
|
| Streaming mechanics — framing, backpressure, cleanup, disconnects | green-tea |
|
||||||
|
| OpenAPI projection | green-tea — from the same metadata that runs the app |
|
||||||
|
| Secure transport defaults | green-tea — headers, CORS, TLS |
|
||||||
|
| Runtime serving boundary | green-tea — `listen`, `fetch`, `upgrade` per runtime |
|
||||||
|
| Shutdown sequencing | green-tea — drain, then teardown, inside one deadline |
|
||||||
|
| **Business rules** | **you** |
|
||||||
|
|
||||||
|
That division is the whole design, and it is why `reflect-metadata` is the only runtime dependency:
|
||||||
|
the goal is not a small number for its own sake, it is **fewer moving parts your team has to
|
||||||
|
understand, upgrade, coordinate and debug**. A framework that owns less pushes the difference into
|
||||||
|
your application, where it becomes your maintenance instead of disappearing.
|
||||||
|
|
||||||
|
Automated does not mean invisible. `app.explain()` prints the ordered chain, `app.graph()` renders
|
||||||
|
the live graph, and `app.openapi()` projects the same metadata — the graph is not documentation drawn
|
||||||
|
after the fact, it is the structure green-tea validates and executes.
|
||||||
|
|
||||||
## Real-time is a primitive, not a second framework
|
## Real-time is a primitive, not a second framework
|
||||||
|
|
||||||
@@ -98,9 +129,10 @@ class Live {
|
|||||||
|
|
||||||
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
||||||
|
|
||||||
## Batteries included — still one dependency
|
## What the foundation already carries
|
||||||
|
|
||||||
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
|
The parts a real API needs, owned by the framework rather than assembled in your application — and
|
||||||
|
without growing the runtime dependency tree past `reflect-metadata`:
|
||||||
|
|
||||||
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
|
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
|
||||||
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
|
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
|
||||||
@@ -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.
|
- **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.
|
- **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.
|
- **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.
|
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||||
|
|
||||||
@@ -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.
|
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||||
|
|
||||||
|
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
|
||||||
|
|
||||||
## Docs & development
|
## Docs & development
|
||||||
|
|
||||||
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing. 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.
|
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
|
||||||
|
|
||||||
|
> **Changing public API? The docs are a separate repository now, and nothing tells you when you break them.**
|
||||||
|
> [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) imports nothing from here, so no build fails and no test turns red when a guide describes an API that no longer exists. **A pull request that changes public API updates the page documenting it, in the same pull request.** This is a rule rather than a check because no check exists yet — issue #18 is what a stale page looks like from a user's side, and that happened while both still lived in this repository.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm test # vitest (Node only) — the fast loop, ~2s
|
npm test # vitest (Node only) — the fast loop, ~2s
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "26.8.0-beta.0",
|
"version": "26.8.0-beta.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
|
// 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
|
// `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.
|
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**
|
## 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.
|
`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.
|
- 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.
|
- **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.
|
||||||
- Setting it lower **reserves**: the drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
|
- **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.
|
- `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.
|
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.
|
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.
|
`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
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"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.",
|
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "green-tea contributors <projects@expressive-tea.io>",
|
"author": "green-tea contributors <projects@expressive-tea.io>",
|
||||||
|
|||||||
+142
-12
@@ -12,6 +12,8 @@ import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocke
|
|||||||
import { isAsyncIterable } from '../channel';
|
import { isAsyncIterable } from '../channel';
|
||||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||||
|
import { TeardownRegistry } from '../lifecycle';
|
||||||
|
import type { Hooks } from './types';
|
||||||
import {
|
import {
|
||||||
Ctor,
|
Ctor,
|
||||||
getModuleMeta,
|
getModuleMeta,
|
||||||
@@ -48,6 +50,13 @@ interface Registry {
|
|||||||
stepNodes: GraphNode[];
|
stepNodes: GraphNode[];
|
||||||
runners: Map<string, Runner>;
|
runners: Map<string, Runner>;
|
||||||
providerMeta: Map<string, { optional: boolean }>;
|
providerMeta: Map<string, { optional: boolean }>;
|
||||||
|
/**
|
||||||
|
* The `@Provider` instance behind each node, kept only so a `dispose()` can be reached.
|
||||||
|
*
|
||||||
|
* `collectProviders` used to build the instance and let it live on solely inside the runner's
|
||||||
|
* closure, which meant nothing could ever call a method on it again.
|
||||||
|
*/
|
||||||
|
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
|
||||||
routePlans: RoutePlan[];
|
routePlans: RoutePlan[];
|
||||||
exportedProviders: string[];
|
exportedProviders: string[];
|
||||||
exportedSteps: string[];
|
exportedSteps: string[];
|
||||||
@@ -86,6 +95,14 @@ interface PipelineDeps {
|
|||||||
export function createApp(opts: {
|
export function createApp(opts: {
|
||||||
modules: Ctor[];
|
modules: Ctor[];
|
||||||
plugins?: Plugin[];
|
plugins?: Plugin[];
|
||||||
|
/**
|
||||||
|
* Lifecycle participation without extending the graph.
|
||||||
|
*
|
||||||
|
* A plugin means "I want to add nodes"; someone who only needs to close a connection should not
|
||||||
|
* have to declare an extension they do not want. Methods are optional so later stages can join
|
||||||
|
* without a breaking change — only `onShutdown` exists today.
|
||||||
|
*/
|
||||||
|
hooks?: Hooks[];
|
||||||
mesh?: MeshConfig;
|
mesh?: MeshConfig;
|
||||||
limits?: RequestLimits;
|
limits?: RequestLimits;
|
||||||
devGraph?: boolean;
|
devGraph?: boolean;
|
||||||
@@ -111,6 +128,17 @@ export function createApp(opts: {
|
|||||||
* where passing it per call is not an option.
|
* where passing it per call is not an option.
|
||||||
*/
|
*/
|
||||||
shutdownTimeoutMs?: number;
|
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).
|
* 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 viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
|
||||||
const registry = collectModules(opts.modules, viewsCtx);
|
const registry = collectModules(opts.modules, viewsCtx);
|
||||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||||
mountPlugins(opts.plugins, bus, registry);
|
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
|
||||||
|
mountPlugins(opts.plugins, bus, registry, teardown);
|
||||||
provideBuiltins(registry, logger);
|
provideBuiltins(registry, logger);
|
||||||
|
|
||||||
// For each route, resolve which providers/steps feed it via topo order.
|
// For each route, resolve which providers/steps feed it via topo order.
|
||||||
@@ -236,7 +265,7 @@ export function createApp(opts: {
|
|||||||
registry,
|
registry,
|
||||||
opts.overrides,
|
opts.overrides,
|
||||||
() => orderedProviders,
|
() => orderedProviders,
|
||||||
{ runners, container, providerMeta, bus, logger },
|
{ runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
|
||||||
degradedProviders,
|
degradedProviders,
|
||||||
ready,
|
ready,
|
||||||
);
|
);
|
||||||
@@ -292,7 +321,7 @@ export function createApp(opts: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
|
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 {
|
return {
|
||||||
listen,
|
listen,
|
||||||
@@ -327,6 +356,7 @@ function emptyRegistry(): Registry {
|
|||||||
stepNodes: [],
|
stepNodes: [],
|
||||||
runners,
|
runners,
|
||||||
providerMeta: new Map(),
|
providerMeta: new Map(),
|
||||||
|
providerInstances: new Map(),
|
||||||
routePlans: [],
|
routePlans: [],
|
||||||
exportedProviders: [],
|
exportedProviders: [],
|
||||||
exportedSteps: [],
|
exportedSteps: [],
|
||||||
@@ -343,6 +373,7 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
|
|||||||
registry.providerMeta.set(meta.provides, { optional: meta.optional });
|
registry.providerMeta.set(meta.provides, { optional: meta.optional });
|
||||||
if (meta.export) registry.exportedProviders.push(meta.provides);
|
if (meta.export) registry.exportedProviders.push(meta.provides);
|
||||||
const instance: any = new ProviderClass();
|
const instance: any = new ProviderClass();
|
||||||
|
registry.providerInstances.set(meta.provides, instance);
|
||||||
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
|
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -459,12 +490,40 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
|
|||||||
return registry;
|
return registry;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the teardown registry, seeds it with the application's hooks, and validates the reservation.
|
||||||
|
*
|
||||||
|
* Hooks land before plugins, so the registry running in reverse tears plugins down before the hooks
|
||||||
|
* an application registered around them. Both go into the same list: one order, one failure policy.
|
||||||
|
*/
|
||||||
|
function buildTeardownRegistry(
|
||||||
|
hooks: Hooks[] | undefined,
|
||||||
|
teardownTimeoutMs: number | undefined,
|
||||||
|
shutdownTimeoutMs: number | undefined,
|
||||||
|
): TeardownRegistry {
|
||||||
|
const budget = shutdownTimeoutMs ?? 10_000;
|
||||||
|
|
||||||
|
// Rejected rather than clamped: a reservation larger than the budget it is carved from is a
|
||||||
|
// mistake in the caller's numbers, and quietly shrinking it would hide which of the two they got
|
||||||
|
// wrong — at boot, where there is time to fix it, rather than during a shutdown.
|
||||||
|
if (teardownTimeoutMs !== undefined && teardownTimeoutMs > budget) {
|
||||||
|
throw new Error(
|
||||||
|
`teardownTimeoutMs (${teardownTimeoutMs}) cannot exceed shutdownTimeoutMs (${budget}) — ` +
|
||||||
|
'it is reserved out of that budget, not added to it',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const teardown = new TeardownRegistry();
|
||||||
|
for (const hook of hooks ?? []) if (hook.onShutdown) teardown.add(hook.onShutdown);
|
||||||
|
return teardown;
|
||||||
|
}
|
||||||
|
|
||||||
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
|
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
|
||||||
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
|
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry, teardown: TeardownRegistry): void {
|
||||||
const extraSteps: ScopeNode[] = [];
|
const extraSteps: ScopeNode[] = [];
|
||||||
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
|
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
|
||||||
|
|
||||||
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
|
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope, (fn) => teardown.add(fn));
|
||||||
|
|
||||||
for (const scopeNode of extraSteps) {
|
for (const scopeNode of extraSteps) {
|
||||||
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
||||||
@@ -667,11 +726,13 @@ async function bootProviders(
|
|||||||
runners: Map<string, Runner>;
|
runners: Map<string, Runner>;
|
||||||
container: Container;
|
container: Container;
|
||||||
providerMeta: Map<string, { optional: boolean }>;
|
providerMeta: Map<string, { optional: boolean }>;
|
||||||
|
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
|
||||||
|
teardown: TeardownRegistry;
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
logger: Logger;
|
logger: Logger;
|
||||||
},
|
},
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const { runners, container, providerMeta, bus, logger } = deps;
|
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
|
||||||
const degraded: string[] = [];
|
const degraded: string[] = [];
|
||||||
|
|
||||||
for (const node of orderedProviders) {
|
for (const node of orderedProviders) {
|
||||||
@@ -681,6 +742,15 @@ async function bootProviders(
|
|||||||
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
||||||
container.register(node.name, 'app', () => value);
|
container.register(node.name, 'app', () => value);
|
||||||
await container.resolve(node.name); // warm the cache
|
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 });
|
bus.emit('boot:provider:ok', { name: node.name });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
bus.emit('boot:provider:fail', { name: node.name, error });
|
bus.emit('boot:provider:fail', { name: node.name, error });
|
||||||
@@ -717,6 +787,8 @@ function makeAppBooter(
|
|||||||
runners: Map<string, Runner>;
|
runners: Map<string, Runner>;
|
||||||
container: Container;
|
container: Container;
|
||||||
providerMeta: Map<string, { optional: boolean }>;
|
providerMeta: Map<string, { optional: boolean }>;
|
||||||
|
providerInstances: Map<string, { dispose?: () => void | Promise<void> }>;
|
||||||
|
teardown: TeardownRegistry;
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
logger: Logger;
|
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(
|
function closeApp(
|
||||||
server: http.Server | undefined,
|
server: http.Server | undefined,
|
||||||
meshLinks: Link[],
|
meshLinks: Link[],
|
||||||
@@ -1013,8 +1125,17 @@ function closeApp(
|
|||||||
options: { timeoutMs?: number },
|
options: { timeoutMs?: number },
|
||||||
defaultTimeoutMs: number | undefined,
|
defaultTimeoutMs: number | undefined,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
|
teardown: TeardownRegistry,
|
||||||
|
reservedMs: number | undefined,
|
||||||
): Promise<void> {
|
): 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
|
// 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.
|
// teapot connection otherwise — so links close before we even check for a server.
|
||||||
closeLinks(meshLinks);
|
closeLinks(meshLinks);
|
||||||
@@ -1026,16 +1147,20 @@ function closeApp(
|
|||||||
if (!server) {
|
if (!server) {
|
||||||
if (options.timeoutMs !== undefined) {
|
if (options.timeoutMs !== undefined) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'close({ timeoutMs }) has no effect here — this app has no listen()ed server. On Deno ' +
|
'close({ timeoutMs }) does not drain connections here — this app has no listen()ed ' +
|
||||||
'and Bun, call close() on the server serveDeno()/serveBun() returned; it takes the ' +
|
'server, so it only bounds teardown. On Deno and Bun, call close() on the server ' +
|
||||||
'same option. On the edge the platform owns the lifecycle.',
|
'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();
|
return resolve();
|
||||||
}
|
}
|
||||||
|
|
||||||
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
|
|
||||||
let settled = false;
|
let settled = false;
|
||||||
|
|
||||||
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
|
// 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.
|
// below — `engines` in package.json only guarantees >=18, so this matters.
|
||||||
server.closeAllConnections();
|
server.closeAllConnections();
|
||||||
finish();
|
finish();
|
||||||
}, timeoutMs);
|
}, drainBudget);
|
||||||
|
|
||||||
timer.unref?.();
|
timer.unref?.();
|
||||||
|
|
||||||
@@ -1072,6 +1197,11 @@ function closeApp(
|
|||||||
for (const closeStream of streams) closeStream();
|
for (const closeStream of streams) closeStream();
|
||||||
server.closeIdleConnections();
|
server.closeIdleConnections();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Teardown runs after the drain and before close() resolves: an in-flight request may still be
|
||||||
|
// using the connection a teardown is about to close, so draining first is not an ordering
|
||||||
|
// preference. It gets whatever is left of the budget — at least the reservation, if one was made.
|
||||||
|
return drain.then(() => runTeardown(teardown, logger, timeoutMs - (Date.now() - startedAt)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Best-effort close of every mesh link, ignoring individual failures. */
|
/** Best-effort close of every mesh link, ignoring individual failures. */
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import type { Logger } from '../logger';
|
import type { Logger } from '../logger';
|
||||||
|
import type { TeardownFn } from '../lifecycle';
|
||||||
import type { GraphNode } from '../graph';
|
import type { GraphNode } from '../graph';
|
||||||
import type { GraphView } from '../graph-viz';
|
import type { GraphView } from '../graph-viz';
|
||||||
import type { HttpMethod, Transport } from '../metadata';
|
import type { HttpMethod, Transport } from '../metadata';
|
||||||
@@ -103,3 +104,14 @@ export interface MeshConfig {
|
|||||||
*/
|
*/
|
||||||
heartbeatMs?: number;
|
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
@@ -119,7 +119,12 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
|
|||||||
return Object.assign(server, {
|
return Object.assign(server, {
|
||||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||||
closeWithDeadline(
|
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),
|
() => void server.stop(true),
|
||||||
closeOptions.timeoutMs ?? 10_000,
|
closeOptions.timeoutMs ?? 10_000,
|
||||||
(ms) =>
|
(ms) =>
|
||||||
|
|||||||
+6
-1
@@ -78,7 +78,12 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
|
|||||||
return Object.assign(server, {
|
return Object.assign(server, {
|
||||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||||
closeWithDeadline(
|
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
|
// 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
|
// 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
|
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
||||||
|
|||||||
@@ -15,6 +15,13 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
|
|||||||
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
|
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
|
||||||
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
|
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
|
||||||
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
|
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
|
||||||
|
*
|
||||||
|
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
|
||||||
|
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
|
||||||
|
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
|
||||||
|
* to release something is therefore *silently* inert on the edge, which is why this says so rather
|
||||||
|
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
|
||||||
|
* the request that acquired it, or in a platform binding that manages its own lifetime.
|
||||||
*/
|
*/
|
||||||
export function edgeHandler(
|
export function edgeHandler(
|
||||||
app: App,
|
app: App,
|
||||||
|
|||||||
@@ -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
@@ -1,4 +1,5 @@
|
|||||||
import { Bus } from './bus';
|
import { Bus } from './bus';
|
||||||
|
import type { TeardownFn } from './lifecycle';
|
||||||
|
|
||||||
/** A step or provider a plugin contributes to the graph. */
|
/** A step or provider a plugin contributes to the graph. */
|
||||||
export interface ScopeNode {
|
export interface ScopeNode {
|
||||||
@@ -13,18 +14,34 @@ export interface ScopeNode {
|
|||||||
export interface ScopeApi {
|
export interface ScopeApi {
|
||||||
add(node: ScopeNode): void;
|
add(node: ScopeNode): void;
|
||||||
}
|
}
|
||||||
/** The capabilities handed to a plugin: event subscription and node registration only. */
|
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
|
||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
bus: { on: Bus['on'] };
|
bus: { on: Bus['on'] };
|
||||||
scope: ScopeApi;
|
scope: ScopeApi;
|
||||||
|
/**
|
||||||
|
* Run something before the app closes — closing a pool, stopping a timer, flushing a buffer.
|
||||||
|
*
|
||||||
|
* Takes no arguments: whatever needs closing is already in the closure of the plugin that opened
|
||||||
|
* it. It is awaited, unlike a `bus.on` listener, and a failure is logged rather than swallowed.
|
||||||
|
*/
|
||||||
|
onShutdown(fn: TeardownFn): void;
|
||||||
}
|
}
|
||||||
/** A plugin: a function that wires itself up through the provided PluginApi. */
|
/** A plugin: a function that wires itself up through the provided PluginApi. */
|
||||||
export type Plugin = (api: PluginApi) => void;
|
export type Plugin = (api: PluginApi) => void;
|
||||||
|
|
||||||
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
|
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
|
||||||
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void {
|
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
|
||||||
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural.
|
// Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
|
||||||
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
|
//
|
||||||
|
// "Isolation is structural" means this list and nothing else — it is a guarantee about the
|
||||||
|
// *registration surface*, not about the request context. A plugin's step receives the live
|
||||||
|
// context like any other step and can overwrite keys in it (`src/pipeline.ts`, `Object.assign`),
|
||||||
|
// which is a separate, pre-existing question this list has never covered.
|
||||||
|
//
|
||||||
|
// `onShutdown` is the first capability here the framework must *wait* for: nothing a plugin did
|
||||||
|
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
|
||||||
|
// caps the whole shutdown.
|
||||||
|
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
|
||||||
plugin(api);
|
plugin(api);
|
||||||
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
|
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
|
||||||
}
|
}
|
||||||
@@ -49,3 +49,23 @@ test('serveBun close() drains an in-flight request rather than cutting it', asyn
|
|||||||
|
|
||||||
expect(await inFlight).toEqual({ ok: true });
|
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']);
|
||||||
|
});
|
||||||
@@ -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
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -63,3 +63,24 @@ Deno.test('a caller-supplied signal still aborts the server', async () => {
|
|||||||
ac.abort();
|
ac.abort();
|
||||||
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
|
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(',')}`);
|
||||||
|
});
|
||||||
@@ -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
@@ -1,6 +1,9 @@
|
|||||||
import { expect, test, vi } from 'vitest';
|
import { expect, test, vi } from 'vitest';
|
||||||
import { Bus } from '../src/bus';
|
import { Bus } from '../src/bus';
|
||||||
import { mountPlugin, Plugin, ScopeApi } from '../src/plugin';
|
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', () => {
|
test('plugin can observe via bus.on and add to its own scope', () => {
|
||||||
const bus = new Bus();
|
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();
|
const mounted = vi.fn();
|
||||||
bus.on('plugin:mounted', mounted);
|
bus.on('plugin:mounted', mounted);
|
||||||
mountPlugin(logger, bus, scope);
|
mountPlugin(logger, bus, scope, noTeardown());
|
||||||
|
|
||||||
expect(added).toEqual(['log']);
|
expect(added).toEqual(['log']);
|
||||||
expect(mounted).toHaveBeenCalled();
|
expect(mounted).toHaveBeenCalled();
|
||||||
@@ -26,5 +29,37 @@ test('plugin api does NOT expose bus.emit', () => {
|
|||||||
const plugin: Plugin = (api) => {
|
const plugin: Plugin = (api) => {
|
||||||
expect((api.bus as any).emit).toBeUndefined();
|
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);
|
||||||
});
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user