Compare commits
106
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f9e6b19d6 | ||
|
|
7be26fda5c | ||
|
|
e540752f1e | ||
|
|
e86051382d | ||
|
|
b8cb684a6b | ||
|
|
2c838c8753 | ||
|
|
cd4f47486f | ||
|
|
ffb5139cae | ||
|
|
46342a0aa2 | ||
|
|
1975a7c03f | ||
|
|
f2cb411eac | ||
|
|
1ccbf6cadf | ||
|
|
6ffbad9825 | ||
|
|
6672185ba2 | ||
|
|
198e62944f | ||
|
|
7d04b2d736 | ||
|
|
51608b0631 | ||
|
|
bbcc90eb4d | ||
|
|
9b5347aa75 | ||
|
|
0218508a96 | ||
|
|
41c1f4308b | ||
|
|
bb75cabeea | ||
|
|
bead3c1569 | ||
|
|
0414aff665 | ||
|
|
21765c2a47 | ||
|
|
cd6e2f073f | ||
|
|
38b73cebce | ||
|
|
62d0b7aa3a | ||
|
|
24feca481c | ||
|
|
bfe8b66127 | ||
|
|
78b5034936 | ||
|
|
a5c1fda886 | ||
|
|
e778f62902 | ||
|
|
9f72604cbb | ||
|
|
101c4fe65a | ||
|
|
a4bb3c02d6 | ||
|
|
0c9f8a545e | ||
|
|
e625d5c881 | ||
|
|
5fafe97bc5 | ||
|
|
8d8ef7ed09 | ||
|
|
0c5decbeae | ||
|
|
86dd3fe9b6 | ||
|
|
523e3184b0 | ||
|
|
92987d0a24 | ||
|
|
e052d5ba8f | ||
|
|
df460f01dd | ||
|
|
7b0a3d4e24 | ||
|
|
dabab1812b | ||
|
|
633ef58032 | ||
|
|
2c47ee8896 | ||
|
|
7bd11bff27 | ||
|
|
d324ecfcb4 | ||
|
|
8c3844e577 | ||
|
|
f97ac8098b | ||
|
|
e4a2047a1e | ||
|
|
586e14da72 | ||
|
|
085eb9a67d | ||
|
|
91f349bef7 | ||
|
|
f96c2ad401 | ||
|
|
a0fd74da34 | ||
|
|
1c5a908fb9 | ||
|
|
30f33b6383 | ||
|
|
70bb9902dc | ||
|
|
9c3bc9574b | ||
|
|
08310ac252 | ||
|
|
31cafcc3fa | ||
|
|
4aae9c3e71 | ||
|
|
2e4712788b | ||
|
|
9d95260706 | ||
|
|
3dcf784159 | ||
|
|
7518a5a785 | ||
|
|
da6099b0e6 | ||
|
|
f200045fd7 | ||
|
|
18d441b3ec | ||
|
|
3714f7befc | ||
|
|
ab58c064d5 | ||
|
|
6fa40672c6 | ||
|
|
1bb82491bd | ||
|
|
b08ecb66cc | ||
|
|
9bff2a52c9 | ||
|
|
551e79a86c | ||
|
|
61bef36d60 | ||
|
|
024b0a79fd | ||
|
|
8c781c1258 | ||
|
|
84a2a29ed6 | ||
|
|
9d8e970c85 | ||
|
|
9e5e5cffe9 | ||
|
|
beec350fcd | ||
|
|
37693246d7 | ||
|
|
1b8f2f3140 | ||
|
|
e820954ea8 | ||
|
|
324ddf0d61 | ||
|
|
f2db461187 | ||
|
|
55263f2d97 | ||
|
|
506dedb624 | ||
|
|
1030109efa | ||
|
|
08d92f5de7 | ||
|
|
8babcb9554 | ||
|
|
6dd23ed874 | ||
|
|
05e59383f1 | ||
|
|
97a146a758 | ||
|
|
aa3402bd84 | ||
|
|
813a29001b | ||
|
|
8d923e053c | ||
|
|
523e302012 | ||
|
|
e068426582 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something behaves differently from what the docs or the types promise
|
||||
labels: bug
|
||||
---
|
||||
|
||||
## What happened
|
||||
|
||||
## What you expected
|
||||
|
||||
## Minimal reproduction
|
||||
|
||||
The smallest module and route that shows it:
|
||||
|
||||
```ts
|
||||
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
- green-tea version:
|
||||
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
|
||||
- OS:
|
||||
|
||||
<!--
|
||||
If it works on one runtime and not another, say which. That difference is
|
||||
usually the bug rather than a detail of it.
|
||||
-->
|
||||
@@ -0,0 +1,14 @@
|
||||
# Design questions, scope decisions and "should this live in core?" threads don't fit a
|
||||
# bug form, and they are most of what gets filed here. Keep the blank option available.
|
||||
blank_issues_enabled: true
|
||||
|
||||
contact_links:
|
||||
- name: Security vulnerability
|
||||
url: https://github.com/Expressive-Tea/green-tea/security/advisories/new
|
||||
about: Report it privately instead. Never in a public issue — see SECURITY.md.
|
||||
- name: Documentation
|
||||
url: https://green-tea.expressive-tea.io/docs/
|
||||
about: How to wire a route, a module, a plugin or a runtime adapter.
|
||||
- name: Help with your own app
|
||||
url: mailto:support@expressive-tea.io
|
||||
about: Implementation questions about your code rather than a bug in green-tea.
|
||||
@@ -0,0 +1,16 @@
|
||||
> **Base branch:** on GitHub this must target `contrib`, not `main`. You can still change it above, before you submit — and [here is why](https://github.com/Expressive-Tea/green-tea/blob/main/CONTRIBUTING.md#where-to-send-your-changes). Delete this line once the base is right.
|
||||
|
||||
## What this changes
|
||||
|
||||
<!-- A sentence or two, on the why rather than the what. -->
|
||||
|
||||
Closes #
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] The base branch above is `contrib`
|
||||
- [ ] Commits are signed off (`git commit -s`)
|
||||
- [ ] `npm run lint`, `npm run format:check`, `npm run typecheck`, `npm test`, `npm run complexity:check` and `npm run build` pass locally
|
||||
- [ ] New behavior has a test
|
||||
- [ ] A new public option or method is also declared in `src/app/types.ts`, and noted in `README.md`
|
||||
- [ ] Behavior is the same on Node, Deno and Bun — or the difference is deliberate, and said out loud here
|
||||
@@ -1,10 +1,40 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [develop, main]
|
||||
branches: [develop, main, contrib]
|
||||
pull_request:
|
||||
branches: [develop, main]
|
||||
branches: [develop, main, contrib]
|
||||
jobs:
|
||||
# Separate job so a missing sign-off reports on its own and doesn't hide behind the code
|
||||
# gates, and so it costs nothing on push. Checks that the trailer is present, not that it
|
||||
# matches the author — a mismatch is a judgement call for a reviewer, an absent trailer
|
||||
# is not, and telling a contributor on their first push beats telling them on review.
|
||||
dco:
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Every commit needs a Signed-off-by
|
||||
env:
|
||||
RANGE: ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
missing=0
|
||||
for sha in $(git rev-list --no-merges "$RANGE"); do
|
||||
if ! git show -s --format='%(trailers:key=Signed-off-by,valueonly)' "$sha" | grep -q '[^[:space:]]'; then
|
||||
echo "::error::no Signed-off-by: $(git show -s --format='%h %s' "$sha")"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
if [ "$missing" = 1 ]; then
|
||||
echo "We use the DCO instead of a CLA. See CONTRIBUTING.md."
|
||||
echo "Fix the whole branch with: git rebase --signoff ${{ github.event.pull_request.base.sha }}"
|
||||
echo "Then: git push --force-with-lease"
|
||||
exit 1
|
||||
fi
|
||||
echo "All commits signed off."
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -13,16 +43,63 @@ jobs:
|
||||
with:
|
||||
node-version: '18'
|
||||
- run: npm ci
|
||||
- run: npm audit
|
||||
- run: npm run lint
|
||||
- run: npm run format:check
|
||||
- run: npm run complexity:check
|
||||
- run: npm run typecheck
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
# Supply chain, deliberately after the code gates: an advisory published by a third party
|
||||
# must never decide whether a contributor gets to see their own lint and typecheck output.
|
||||
# Only what we ship blocks — with `reflect-metadata` as the sole runtime dependency, a
|
||||
# production advisory is rare and genuinely reaches users. Build tooling only reports.
|
||||
- run: npm audit --omit=dev
|
||||
- run: npm audit
|
||||
continue-on-error: true
|
||||
|
||||
# Runs everywhere is the headline claim, so it gets tested rather than asserted. `npm test` is
|
||||
# Node only: a change to shared code can pass it and still be broken on Deno or Bun, which is
|
||||
# exactly why these suites exist separately. Leaving them out of CI meant the claim rested on
|
||||
# whoever remembered to run them locally.
|
||||
#
|
||||
# Its own job, not more steps on `build`, for the reason the audit sits where it does: a Bun
|
||||
# failure should read as a Bun failure instead of burying the Node lint output.
|
||||
runtimes:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
# One runtime breaking must not cancel the others — which one else broke is the useful part
|
||||
# of the answer, and a cancelled job reports as if it had never been asked.
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runtime: [deno, bun, edge]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22.12'
|
||||
- run: npm ci --prefix website
|
||||
- run: npm audit --prefix website
|
||||
- run: npm run docs:build
|
||||
node-version: '22'
|
||||
# All three need the dependency tree: the edge suite drives workerd from a Node process, and
|
||||
# Deno and Bun resolve `reflect-metadata` out of node_modules like any other import.
|
||||
- run: npm ci
|
||||
- if: matrix.runtime == 'deno'
|
||||
uses: denoland/setup-deno@v2
|
||||
with:
|
||||
deno-version: v2.x
|
||||
- if: matrix.runtime == 'bun'
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- run: npm run test:${{ matrix.runtime }}
|
||||
# JSR's gate, moved off the release tag. `release.yml` runs this too and keeps doing so —
|
||||
# that copy protects an immutable JSR version and is the last thing standing between a tag
|
||||
# and a version number that can never be replaced. This copy exists because that one runs
|
||||
# too late to be useful as feedback: a slow type or a Deno type error would otherwise land
|
||||
# on `main` in silence and surface while cutting a release, which is the same "least time
|
||||
# to judge a fix" the audit steps above are ordered to avoid.
|
||||
#
|
||||
# It is a second compiler over the same source, not a formality. `npm run typecheck` is tsc
|
||||
# with this repo's tsconfig; this is Deno's checker with Deno's lib, and it is what found
|
||||
# the `BodyInit` hole on the fetch path that tsc accepted. JSR serves `src/` directly, so
|
||||
# anything it rejects is something a JSR consumer would have received.
|
||||
#
|
||||
# 0.68s against 2.0s for the whole vitest suite. No `--allow-dirty`: a checkout is clean,
|
||||
# and if it somehow is not, that is worth failing on.
|
||||
- if: matrix.runtime == 'deno'
|
||||
run: deno publish --dry-run
|
||||
@@ -12,6 +12,8 @@ jobs:
|
||||
publish-prod:
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PKG: '@green-tea/core'
|
||||
permissions:
|
||||
id-token: write # OIDC for Trusted Publishing (also enables provenance)
|
||||
contents: read
|
||||
@@ -23,13 +25,83 @@ jobs:
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
||||
- run: npm ci
|
||||
# Same scoped gate as ci.yml: only what we ship blocks a publish. With `reflect-metadata`
|
||||
# as the sole runtime dependency, a blocking advisory here is rare and genuinely reaches
|
||||
# users; a build-tooling one never does. The full audit still reports.
|
||||
- run: npm audit --omit=dev
|
||||
- run: npm audit
|
||||
continue-on-error: true
|
||||
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
||||
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
|
||||
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
|
||||
# never points at a beta; a stable version publishes under `latest`.
|
||||
- name: Publish
|
||||
- uses: denoland/setup-deno@v2
|
||||
with:
|
||||
deno-version: v2.x
|
||||
# Gate both registries before either one ships. JSR checks things npm never looks at — slow
|
||||
# types, module analysis — and learning about them after npm has published leaves the tag
|
||||
# half-shipped. Seconds, against a failure mode with no clean recovery.
|
||||
- run: deno publish --dry-run
|
||||
- name: Publish to npmjs
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
|
||||
echo "dist-tag: $TAG"
|
||||
npm publish --access public --tag "$TAG"
|
||||
echo "$VERSION under dist-tag: $TAG"
|
||||
# Skip rather than fail when the version is already up. A step after this one can fail —
|
||||
# the dist-tag move below does — and a re-run of the job has to be able to finish the
|
||||
# remaining work instead of dying on a duplicate npm rejects anyway.
|
||||
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
|
||||
echo "npm already has $VERSION"
|
||||
else
|
||||
npm publish --access public --tag "$TAG"
|
||||
fi
|
||||
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
|
||||
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
|
||||
# failure *after* it would cost a version number permanently. Version and entry points come
|
||||
# from deno.json, which `test/package-metadata.test.ts` pins to package.json — JSR has no
|
||||
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
|
||||
# id-token npm just used; the package is linked to this repository on jsr.io.
|
||||
- name: Publish to JSR
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
PKG=${PKG#@}
|
||||
# 404 until the version exists — and it stays 404 for a package with no versions yet, which
|
||||
# is the state this repository is actually in, so the guard must not read that as an error.
|
||||
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
|
||||
echo "JSR already has $VERSION"
|
||||
else
|
||||
deno publish
|
||||
fi
|
||||
# `latest` is what a bare `npm install @green-tea/core` resolves to, and while there is no
|
||||
# stable release the docs promise it is the newest beta. `npm publish --tag beta` sets exactly
|
||||
# one tag, so `latest` has to be moved separately — and `npm dist-tag` cannot use Trusted
|
||||
# Publishing, whose OIDC exchange lives only inside `npm publish`. So we run that same exchange
|
||||
# by hand (id-token → short-lived npm token) rather than keep a long-lived token in a secret for
|
||||
# one command. Last on purpose: both registries already have the version, and a dist-tag is the
|
||||
# only thing here that can be redone. If this step fails, the release is out but `latest` is
|
||||
# stale — recover with `npm dist-tag add @green-tea/core@<version> latest`.
|
||||
- name: Point `latest` at this release while no stable exists
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
case "$VERSION" in
|
||||
*-*) ;;
|
||||
*) echo "$VERSION is stable — npm publish already put it on latest"; exit 0 ;;
|
||||
esac
|
||||
# A stable release owns `latest` for good; a beta published afterwards must never drag it
|
||||
# backwards, so the newest-beta rule applies only until the first stable exists.
|
||||
# Read the list first so a failed lookup fails the step, rather than reading as "no stable
|
||||
# exists" and moving `latest` backwards on the strength of a network error.
|
||||
VERSIONS=$(npm view "$PKG" versions --json)
|
||||
if node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
|
||||
echo "a stable version exists — leaving latest where it is"; exit 0
|
||||
fi
|
||||
URL=$(node -p "const u=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);u.searchParams.set('audience','npm:registry.npmjs.org');u.href")
|
||||
ID_TOKEN=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$URL" \
|
||||
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).value")
|
||||
echo "::add-mask::$ID_TOKEN"
|
||||
NODE_AUTH_TOKEN=$(curl -fsS -X POST -H "Authorization: Bearer $ID_TOKEN" \
|
||||
"https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/$(node -p "encodeURIComponent(process.env.PKG)")" \
|
||||
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).token")
|
||||
echo "::add-mask::$NODE_AUTH_TOKEN"
|
||||
export NODE_AUTH_TOKEN
|
||||
npm dist-tag add "$PKG@$VERSION" latest
|
||||
@@ -18,7 +18,12 @@ jobs:
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
# Same scoped gate as ci.yml: only what we ship blocks a publish. A `tsup` advisory
|
||||
# reaches nobody, and holding a release candidate for one is how staging stalls on work
|
||||
# that has nothing to do with the package. The full audit still reports.
|
||||
- run: npm audit --omit=dev
|
||||
- run: npm audit
|
||||
continue-on-error: true
|
||||
- name: Validate release candidate
|
||||
run: npm run prepublishOnly
|
||||
- name: Publish prerelease to Verdaccio
|
||||
|
||||
+7
-3
@@ -11,9 +11,13 @@ coverage/
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# Astro (docs site)
|
||||
.astro/
|
||||
website/dist/
|
||||
|
||||
# Edge (Miniflare) test bundle artifact
|
||||
test/edge/_worker.mjs
|
||||
|
||||
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
|
||||
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
|
||||
# deno.lock IS tracked, and that asymmetry is deliberate — the Deno tests import `npm:` and
|
||||
# `jsr:` specifiers that Deno resolves against registries, so only a lockfile makes them
|
||||
# reproducible. Bun resolves the same package.json npm does.
|
||||
bun.lock
|
||||
@@ -0,0 +1,102 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for AI coding assistants working in this repository. Claude Code, Codex, Cursor and anything else that reads this file.
|
||||
|
||||
If you are an assistant: a person reads every line of what you produce before it lands, and the person submitting it signs off on it. Make that reading worth their time — leave the reasoning visible, don't quietly widen the scope you were asked for, and say what you were unsure about instead of smoothing over it. The "Working with AI assistance" section of `CONTRIBUTING.md` applies to your output.
|
||||
|
||||
## What this is
|
||||
|
||||
`@green-tea/core` — a type-safe HTTP framework where the API is a dependency graph rather than a middleware chain. You declare what each step needs and provides; the framework computes execution order, fails at boot if something is missing, and can print the whole pipeline. Runs on Node, Deno, Bun and the edge from one codebase.
|
||||
|
||||
**Hard constraint: one runtime dependency.** `reflect-metadata`, and nothing else. `busboy` and `ws` are peer dependencies. Anything that would add a third belongs in a plugin, not in core.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
npm run lint # eslint
|
||||
npm run format:check # prettier, src/**/*.ts only
|
||||
npm run typecheck # must be clean; includes the compile-time-guarantee type test
|
||||
npm test # vitest
|
||||
npm run build # tsup
|
||||
npm run complexity:check
|
||||
|
||||
npm run test:deno # the other runtimes are NOT covered by `npm test`
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Run the first four before proposing anything as finished. The runtime suites stay separate commands on purpose — a change to shared code that passes `npm test` may still be broken on Deno or Bun — but they are no longer optional: CI runs all three on every push and each one gates a merge. Run them yourself for anything touching `src/http/`, the adapters, or `src/mesh/`, rather than finding out from CI.
|
||||
|
||||
## Two forges
|
||||
|
||||
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and release tags, nothing else.
|
||||
|
||||
```
|
||||
feature/* → develop → main → [promote.yml] → GitHub main
|
||||
↑ ↓
|
||||
lead dev GitHub contrib ← external PRs
|
||||
```
|
||||
|
||||
- **Gitea `develop`** — active development.
|
||||
- **Gitea `main`** — staging. Merging here publishes nothing; only a `v*` tag publishes.
|
||||
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
|
||||
- **`contrib`** — exists on *both* forges. Where outside contributions land.
|
||||
|
||||
`develop` and `main` on Gitea have direct push disabled with an empty whitelist, so nobody can push to them, admins included. Advance them by opening a PR and merging it.
|
||||
|
||||
## Procedure
|
||||
|
||||
**Promotions are fast-forward-only.** `develop → main` merges with Gitea's fast-forward-only style, so `main` becomes an exact copy of `develop` and no commit is ever born on `main`. This is not a preference: merge-style promotions created seven of the ten commits of drift that had to be cleaned up in August 2026, because each one lived on `main` and never travelled back. Release boundaries are marked by `v*` tags, not by promotion commits.
|
||||
|
||||
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
|
||||
|
||||
**Diagnosing "this branch is ahead of main".** Usually it is pre-rebase duplication, not unmerged work: the same content under different SHAs, because contributions are rebased on their way into `develop`. Confirm before acting:
|
||||
|
||||
```bash
|
||||
git diff <branch> <main> -- <suspect file> # empty means the content is already in main
|
||||
```
|
||||
|
||||
Merging such a branch to "recover" the commits duplicates the work and drags stale history along.
|
||||
|
||||
**External contributions.** They arrive on GitHub `contrib`. Merge the pull request there, mirror that branch to Gitea, then open a `contrib → develop` pull request and merge it. Merge rather than rebase: because promotions are fast-forward-only, `develop` and `main` are the same commit, so there is no main-only history for a merge to drag in. Rebasing would rewrite the contributor's SHAs for no gain and push `contrib` out of `main`'s ancestry, which then costs a force-push at reset time. Merging keeps their commits reaching `main` under their own name and hash.
|
||||
|
||||
The exception is a `hotfix/*`, which lands on `main` without passing through `develop` and leaves the two out of step. Back-merge before taking a contribution through, or rebase that one and accept the force-push. If you do rebase, take the commit range from the pull request itself and never "everything since main": if a second contributor branched from `contrib` after the first one merged, the broad range sweeps up work that isn't theirs.
|
||||
|
||||
**After every promotion, reset *both* `contrib` branches to `main`.** GitHub's is where external work lands; Gitea's is its mirror, and the easy one to forget because nothing there refuses the push. Normally this is an ordinary fast-forward, since `contrib` is already inside `main`'s history. It only needs a force-push when SHAs were rewritten on the way in — and GitHub then refuses it even for admins, so that branch's protection has to be lifted and restored around the reset.
|
||||
|
||||
A conflict against unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve.
|
||||
|
||||
## Releasing
|
||||
|
||||
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
|
||||
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
|
||||
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
|
||||
nowhere is worse than no heading at all, because the next reader believes it.
|
||||
|
||||
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
|
||||
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
|
||||
two contradictory things — that beta.1 was released, and that everything in it was not.
|
||||
|
||||
So the order is: everything merged and promoted → **close the section with the release date** → tag →
|
||||
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
|
||||
number feels.
|
||||
|
||||
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
|
||||
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
||||
A version number is a plan; a changelog heading is a receipt.
|
||||
|
||||
## CI
|
||||
|
||||
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
|
||||
|
||||
**The forges disagree about where workflows come from.** GitHub reads `pull_request` workflows from the base branch, so a workflow fix cannot validate itself and must reach the base before it gates anything. Gitea reads from the head. Likewise, `continue-on-error` steps report as `success` on GitHub, hiding the advisory in the log, but as `failure` with the job still green on Gitea.
|
||||
|
||||
GitHub does not run workflows on fork pull requests until a maintainer approves them. A contributor's first push may sit with no checks at all.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Conventional Commits, focused on the *why*. Every commit signed off (`git commit -s`) — the project uses a DCO, and unsigned commits are rejected. No AI co-authoring attribution.
|
||||
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
|
||||
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
|
||||
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
|
||||
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
|
||||
+161
-4
@@ -8,9 +8,162 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [26.8.0-beta.1] - 2026-08-19
|
||||
|
||||
### Added
|
||||
|
||||
- **Observability: a correlated lifecycle event stream and an injectable logger.** Every request is
|
||||
given an id — an incoming `x-request-id` is adopted rather than replaced — and every event of that
|
||||
request carries it, alongside the matched route _pattern_ (never the concrete URL, which would give
|
||||
a metrics backend one label per distinct path). Each step reports its own duration. `createApp({
|
||||
logger })` accepts any object with `debug`/`info`/`warn`/`error`; the default writes structured JSON,
|
||||
or a readable line on a TTY, decided once at boot. Nothing in core writes to `console`, enforced by a
|
||||
lint rule rather than by intention. `createApp({ logRequests: true })` logs one line per request, off
|
||||
by default. New exports: `Logger`, `LogLevel`, `LogFields`, `createDefaultLogger`,
|
||||
`withConsoleFallback`, `logRequests`, `LifecycleEvent`, `EventPayload`, `Correlation`.
|
||||
|
||||
No metrics registry and no OpenTelemetry exporter in core — those live outside it, because core
|
||||
keeps one runtime dependency. A `traceparent` header is carried through untouched for an exporter to
|
||||
interpret; core implements no propagation spec. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
|
||||
|
||||
- **A bounded `close()` on the Deno and Bun adapters**, and `createApp({ shutdownTimeoutMs })` for the
|
||||
Node one. `app.close()` returns at its no-server guard on Deno and Bun, so the deadline lives on the
|
||||
server `serveDeno()`/`serveBun()` returns. One difference the deadline cannot hide: Node and Bun
|
||||
force the remainder shut, while Deno cannot — aborting a server that is already draining throws from
|
||||
Deno's own listener, so there the deadline bounds how long `close()` waits, not when connections die.
|
||||
|
||||
- Shutdown is now an extension point. A `@Provider` may declare `dispose()`, a plugin may call
|
||||
`api.onShutdown(fn)`, and an application may pass `createApp({ hooks: [{ onShutdown }] })` — three
|
||||
doors into one registry, so an app closing a connection no longer writes `process.on('SIGTERM')`
|
||||
by hand. Callbacks are **awaited**, unlike `bus.on` listeners, and take no arguments: whatever
|
||||
needs closing is already in the closure that registered it.
|
||||
|
||||
They run in reverse boot order, so a `cache` that needs `db` closes before the `db` it is holding.
|
||||
A failing teardown is logged and the rest still run — one broken callback must not leave the
|
||||
process up. Everything happens inside `close()`'s existing deadline; `createApp({ teardownTimeoutMs })`
|
||||
reserves a slice of that budget when a connection must get its chance to close, and is rejected at
|
||||
boot if it exceeds `shutdownTimeoutMs`.
|
||||
|
||||
Node, Deno and Bun behave identically — on Deno and Bun the teardown runs from the `close()` on the
|
||||
server `serveDeno()`/`serveBun()` returned. **The edge cannot participate**: workerd has no
|
||||
shutdown to intercept, so anything that must be released belongs in the request that acquired it.
|
||||
|
||||
Nothing changes for existing code. `Plugin`'s signature is unchanged, `Hooks` methods are optional,
|
||||
and `dispose()` is called only if present.
|
||||
|
||||
- `limits.maxConnections` changes Node's previously unlimited concurrent socket count to a
|
||||
default cap of `1000`; values `<= 0` leave Node unlimited. Deno and Bun have no equivalent
|
||||
runtime setting and require a platform or reverse-proxy connection cap.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A request that crosses the mesh keeps its identity.** The RPC envelope now carries the caller's
|
||||
`requestId` and `traceId`, and a teapot adopts them rather than opening a new investigation — the
|
||||
same rule an incoming `x-request-id` already got, applied at the process boundary where a trace
|
||||
matters most. It also carries `url`, so a proxied handler sees the path its caller asked for.
|
||||
|
||||
Both fields are **optional on the wire and the protocol version does not move**: `decode` validates
|
||||
only what a frame type requires and passes extras through, so a teapot on an older green-tea
|
||||
ignores them and keeps answering. That is degraded, not broken. The rule for when the version
|
||||
_does_ move is now written next to the constant, because "bump on any breaking change" never said
|
||||
what counts as breaking.
|
||||
|
||||
The remote-route envelope is also built explicitly instead of cast from the internal request
|
||||
object, which had been putting `ip` and `protocol` on the wire — fields the protocol never
|
||||
declared and a teapot could have come to depend on.
|
||||
|
||||
- **Boot waits for a teapot that is merely slow, and still fails for one that is absent.**
|
||||
`createApp({ mesh: { bootTimeoutMs } })` gives a teacup a grace period — default `timeoutMs`, so
|
||||
30s — in which a teapot that has not finished starting is retried with backoff. When it passes,
|
||||
the boot still fails, because a provider the graph depends on is not optional: booting without it
|
||||
would only move the failure to the first request, where it becomes a caller's 503 instead of the
|
||||
deploy's error. `bootTimeoutMs: 0` restores a single attempt.
|
||||
|
||||
**A refusal is not retried.** A wrong secret or a protocol-version mismatch is the teapot's
|
||||
decision and will be the same decision in thirty seconds, so it fails immediately rather than
|
||||
spending the whole budget to reach an identical error. The two are told apart by whether the
|
||||
socket ever opened — a peer that accepted the connection and then hung up rejected us on purpose;
|
||||
one that never accepted it may simply not be listening yet.
|
||||
|
||||
Every retry is logged _and_ emitted as the new `mesh:boot:retry` lifecycle event, so a slow boot
|
||||
is visible to whatever collects events and not only to whoever is watching a terminal.
|
||||
|
||||
- **`.` and `..` in a request path are now resolved rather than 404'd.** `GET /public/../admin` reaches
|
||||
a route declared as `/admin`, and `%2e` counts as a dot, so the encoded spelling cannot reach a route
|
||||
the plain one resolves away from. This is a **behaviour change on Node only**, and it exists to end a
|
||||
divergence: Deno, Bun and Workers resolve dot segments inside the `Request` constructor before the
|
||||
framework sees anything, so the same bytes on the wire already reached different routes depending on
|
||||
where you deployed. Rejecting them — the stricter option, and what this module does for `//` — is not
|
||||
implementable on three of the four runtimes. If a proxy or WAF in front of you matches on the literal
|
||||
path, note that it sees `/public/...` where the application now routes `/admin`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A mesh export that carried behaviour arrived as `{}`, with HTTP 200 and no warning.** The wire is
|
||||
JSON, so a value with methods — a connection pool, a client, a `Map` — lost everything but its
|
||||
shape in transit. What reached the caller was an object: truthy, passing any `if (db)` check, and
|
||||
missing every method, so the failure surfaced as `db.query is not a function` at a call site
|
||||
arbitrarily far from the export that caused it.
|
||||
|
||||
A teapot now refuses to send one, on the side that still holds the real value, with a message
|
||||
naming the token and what sat where: `mesh cannot transport 'db': result.db is a Pool instance`.
|
||||
The check is an allowlist — primitives, plain objects, arrays — so `Date` is refused too, since it
|
||||
would arrive as a string rather than the type the caller declared, which is the same silent
|
||||
difference in a smaller costume. It is bounded by a scan budget, so a large legitimate payload is
|
||||
never turned into an error by the cost of checking it.
|
||||
|
||||
**This is a constraint the documentation never stated:** a mesh export carries _data_, never
|
||||
behaviour. Export what a handle produces, not the handle.
|
||||
|
||||
- **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for
|
||||
the life of the process: every RPC answered 503 until the teacup was restarted, so deploying a
|
||||
teapot forced a restart of every teacup that depended on it, and boot order became load-bearing.
|
||||
Links now reconnect with exponential backoff and jitter (500ms doubling to 30s), tunable through
|
||||
`mesh: { reconnect: { initialDelayMs, maxDelayMs } }` and disabled with `reconnect: false`.
|
||||
`close()` is terminal — a link the application hung up on never reconnects, so `app.close()` cannot
|
||||
leave a process that refuses to exit.
|
||||
|
||||
A returning teapot whose manifest no longer exports something the graph was validated against at
|
||||
boot is **refused** rather than adopted, named by `mesh: { onManifestChange: 'refuse' }`, which is
|
||||
the default and currently the only policy. The link keeps retrying, since a partial deploy may
|
||||
still restore it, and logs the refusal once per distinct manifest rather than once per attempt.
|
||||
Serving against a manifest that no longer backs the graph would surface as a 500 that looks like
|
||||
application code. Extra exports in a returning manifest are ignored: the graph is fixed at boot.
|
||||
|
||||
This also closes the documented gap where **an app-scope export outlived its teapot with a stale
|
||||
value** — a successful reconnect re-registers those bindings, so the next resolve re-runs the RPC.
|
||||
|
||||
Mesh remains **alpha** and behind `experimental: true`.
|
||||
|
||||
- **`mesh:rpc:error` reported the wire id where every other emitter reports a name.** A failing
|
||||
remote call emitted `name: "0"` — the per-link request counter — so the teacup's event could not be
|
||||
lined up with the teapot's event for the same failure. It now names the token or route.
|
||||
|
||||
- **A teapot now bounds its own handshake and caps the size of a control frame.** The teacup has
|
||||
always timed out its side; the teapot had no equivalent, so an unauthenticated peer could hold a
|
||||
socket open forever by simply never sending `hello`. And `decode` runs `JSON.parse` on
|
||||
peer-controlled input _before_ authentication, with no ceiling below whatever the WebSocket layer
|
||||
allowed — 100 MiB under the `ws` package's defaults. Frames above 4,000,000 characters are now
|
||||
refused with close code 1009, sized above the 1 MB default body limit a legitimate RPC can carry.
|
||||
|
||||
- **A `ws://` teapot on a non-loopback host now warns at boot.** The shared secret travels verbatim
|
||||
in the `hello` frame, so an unencrypted link puts it in front of anyone on the path. A warning
|
||||
rather than a refusal, since a private network doing its own mutual TLS is a real deployment and
|
||||
green-tea cannot tell the two apart.
|
||||
|
||||
- **Buffered response bodies are narrowed to what the host runtime's `Response` accepts.** A Node
|
||||
`Buffer` is a `Uint8Array` at runtime but its declared backing store admits `SharedArrayBuffer`, which
|
||||
`BodyInit` does not — so Deno's types rejected it. This was a real typing hole on the `app.fetch`
|
||||
path, which is the path Deno, Bun and the edge all use, rather than a JSR formality.
|
||||
|
||||
- **`close()`'s shutdown timer is armed before `finish()` is referenced.** The previous ordering relied
|
||||
on `server.close(cb)` deferring, which is Node's behaviour rather than a guarantee to us, and left a
|
||||
`ReferenceError` waiting in the shutdown path for whoever changed it.
|
||||
|
||||
## [26.8.0-beta.0] - 2026-08-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
|
||||
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
|
||||
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
|
||||
@@ -30,14 +183,14 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
|
||||
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
|
||||
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
||||
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination
|
||||
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot _and_ teacup, in any combination
|
||||
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
|
||||
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
|
||||
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
|
||||
`nodejs_compat` does not provide.
|
||||
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
|
||||
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
|
||||
The teapot checks the version *before* the secret — a skewed peer is not an auth failure.
|
||||
The teapot checks the version _before_ the secret — a skewed peer is not an auth failure.
|
||||
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
|
||||
(`retry-after`, `etag`, …) without a special case in the error renderer.
|
||||
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
|
||||
@@ -53,6 +206,7 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
|
||||
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
|
||||
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
|
||||
@@ -88,6 +242,7 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
`request:step:leave`.
|
||||
|
||||
### Changed
|
||||
|
||||
- Root, runtime-only, and website dependency audits are clean after supported package updates and
|
||||
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
|
||||
GitHub OIDC release workflow audits immediately before its publish gate.
|
||||
@@ -112,6 +267,7 @@ First public beta, published under the npm `beta` dist-tag. The API may still
|
||||
change before the stable release.
|
||||
|
||||
### Added
|
||||
|
||||
- **Transport security** — native TLS termination (https/wss), CORS with a
|
||||
guarded preflight and credentials-safe origins, secure-by-default response
|
||||
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
|
||||
@@ -131,7 +287,7 @@ change before the stable release.
|
||||
`405 Method Not Allowed` with an `Allow` header when a path exists under a
|
||||
different method.
|
||||
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
|
||||
@abort`, plus `@header('name')` as a singular alias of `@headers`.
|
||||
@abort`, plus `@header('name')` as a singular alias of `@headers`.
|
||||
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
|
||||
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
|
||||
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
|
||||
@@ -153,6 +309,7 @@ change before the stable release.
|
||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||
|
||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
|
||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...main
|
||||
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||
@@ -0,0 +1,3 @@
|
||||
# CLAUDE.md
|
||||
|
||||
See [AGENTS.md](./AGENTS.md). It is the same guidance, kept in one place so the two files cannot drift apart.
|
||||
@@ -0,0 +1,89 @@
|
||||
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **compliance@expressive-tea.io**. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
If you would rather write to a named person than to an address, the project lead reads
|
||||
diego.resendez@expressive-tea.io. Reports about a maintainer, including the project lead,
|
||||
should go to compliance@expressive-tea.io, which is not maintained by the project team.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
|
||||
+112
-4
@@ -2,6 +2,36 @@
|
||||
|
||||
Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**.
|
||||
|
||||
## Where to send your changes
|
||||
|
||||
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main` and release tags, and nothing else. Which branch you target depends on where you are.
|
||||
|
||||
**From GitHub, if you are an outside contributor:** open your pull request against **`contrib`**. Not `main`. `main` on GitHub is a mirror of released code, and merging into it puts the two forges out of sync and breaks the next release push. A maintainer reviews on `contrib` and then carries your commits upstream into Gitea's `develop`, with your authorship and your sign-off intact.
|
||||
|
||||
**From Gitea, if you have access:** follow the branch model below.
|
||||
|
||||
### Worked example
|
||||
|
||||
```bash
|
||||
# fork Expressive-Tea/green-tea on GitHub, then
|
||||
git clone git@github.com:<you>/green-tea.git
|
||||
cd green-tea
|
||||
git remote add upstream https://github.com/Expressive-Tea/green-tea.git
|
||||
git fetch upstream
|
||||
|
||||
# branch from contrib, not from main
|
||||
git checkout -b fix/close-timeout upstream/contrib
|
||||
|
||||
# ... make the change, add a test ...
|
||||
|
||||
git commit -s -m "fix: add a timeout to app.close()"
|
||||
git push origin fix/close-timeout
|
||||
```
|
||||
|
||||
Then open the pull request with **`contrib`** as the base branch.
|
||||
|
||||
`contrib` tracks released code, so it is reset to `main` after each release. If your branch has been open across one, rebase onto the new `contrib` before pushing again.
|
||||
|
||||
## Developer Certificate of Origin (DCO)
|
||||
|
||||
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork.
|
||||
@@ -26,6 +56,34 @@ To sign off a range you forgot to sign:
|
||||
git rebase --signoff <base>
|
||||
```
|
||||
|
||||
Or, for the commit you just made:
|
||||
|
||||
```bash
|
||||
git commit --amend -s
|
||||
git push --force-with-lease
|
||||
```
|
||||
|
||||
## Working with AI assistance
|
||||
|
||||
Use one if it helps. There is no permission to ask for and nothing to declare.
|
||||
|
||||
What we do ask is that you read what it hands you before it becomes a pull request. Every line that lands here is reviewed by a person, by hand, and usually that person is one person. A diff its own author hasn't read moves that work onto them, and turns review into proofreading — which is the thing review is worst at.
|
||||
|
||||
So go through the diff the way you would go through a stranger's, because that is what it is. If you can't say why a line is there, it isn't ready to send. That's the whole of it.
|
||||
|
||||
**What assistants tend to get wrong here in particular** — worth checking before you push:
|
||||
|
||||
- They add dependencies. Core has one runtime dependency, and that is a design constraint rather than an oversight.
|
||||
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` does not cover them.
|
||||
- They delete comments they read as redundant. In this codebase a comment usually carries reasoning the code can't show on its own.
|
||||
- They skip the test.
|
||||
|
||||
**Where you're unsure, say so** — not as a disclosure, as a pointer. "I'm not confident about the Deno path here" tells a reviewer where to spend their attention, and that is worth more to them than a pull request that merely looks clean.
|
||||
|
||||
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the work under this project's license, and that stays true however the text was produced.
|
||||
|
||||
If your assistant reads repository instructions, `AGENTS.md` has the conventions and the architecture notes.
|
||||
|
||||
## Branch model (GitFlow)
|
||||
|
||||
- `main` — production-ready, protected. No direct pushes.
|
||||
@@ -33,6 +91,7 @@ git rebase --signoff <base>
|
||||
- `feature/<name>` — branch from `develop`.
|
||||
- `hotfix/<name>` — branch from `main`.
|
||||
- `release/<version>` — release stabilization.
|
||||
- `contrib` — GitHub only. Where outside contributions land before a maintainer moves them to `develop`.
|
||||
|
||||
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
|
||||
|
||||
@@ -40,17 +99,66 @@ git rebase --signoff <base>
|
||||
|
||||
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
|
||||
|
||||
## Before you open an MR
|
||||
## Local setup
|
||||
|
||||
Node 18 or newer, which is what `engines` requires and what CI runs.
|
||||
|
||||
```bash
|
||||
npm test # all tests must pass
|
||||
npm install
|
||||
```
|
||||
|
||||
That does one thing worth knowing about: the `prepare` script points `core.hooksPath` at
|
||||
`.githooks/`, which installs a pre-commit gate. The gate formats and lint-fixes your staged
|
||||
sources automatically, then refuses the commit if `npm run lint` or `npm run complexity:check`
|
||||
fails. It is there so CI tells you nothing you couldn't have heard locally. Confirm it took:
|
||||
|
||||
```bash
|
||||
git config core.hooksPath # should print .githooks
|
||||
```
|
||||
|
||||
If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you install with
|
||||
something other than npm, check this before your first commit rather than after.
|
||||
|
||||
`npm test` runs the Node suite under Vitest. The other three runtimes have their own commands
|
||||
and their own toolchains, and none of them run in CI:
|
||||
|
||||
```bash
|
||||
npm run test:deno # needs deno
|
||||
npm run test:bun # needs bun
|
||||
npm run test:edge # Miniflare
|
||||
```
|
||||
|
||||
You are not expected to install all three to fix a typo. You are expected to run the one your
|
||||
change touches, and to say in the pull request which ones you ran.
|
||||
|
||||
## Before you open a pull request
|
||||
|
||||
Run what CI runs:
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format:check
|
||||
npm run typecheck # must be clean — this includes the compile-time-guarantee type test
|
||||
npm test # all tests must pass
|
||||
npm run complexity:check
|
||||
npm run build
|
||||
```
|
||||
|
||||
- Write tests for new behavior (TDD welcome). We use Vitest.
|
||||
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
|
||||
- Keep runtime dependencies at zero beyond `reflect-metadata`.
|
||||
- New public API needs a doc note in `README.md`.
|
||||
- A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package.
|
||||
- New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page.
|
||||
- If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not.
|
||||
|
||||
On GitHub, workflows do not run on pull requests from forks until a maintainer approves them, so your first push may sit without any checks for a while. That is not a rejection.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
Open an issue with a minimal reproduction: green-tea version, Node version, and the smallest module/route that shows the problem.
|
||||
Open an issue with a minimal reproduction: green-tea version, runtime and version, and the smallest module/route that shows the problem.
|
||||
|
||||
**Except for security.** If what you found is exploitable, do not open an issue — an issue is world-readable the moment you press the button. Email security@expressive-tea.io or use the [private advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new). [`SECURITY.md`](./SECURITY.md) has the scope and what to expect back.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
By taking part here you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md), which is the Contributor Covenant 2.1. Reports go to compliance@expressive-tea.io.
|
||||
@@ -7,8 +7,13 @@
|
||||
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
||||
|
||||
<p align="center">
|
||||
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
|
||||
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
|
||||
<b>Declare intent. Derive execution.</b><br />
|
||||
You declare what each step <b>needs</b> and <b>produces</b>; green-tea derives the order,<br />
|
||||
validates the wiring before it serves traffic, and runs only the slice each route requires.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<i>Less infrastructure in your application. Less infrastructure in your head.</i> 🍵
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -53,7 +58,33 @@ npm install busboy # multipart/form-data file uploads
|
||||
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
|
||||
## Who does the work?
|
||||
|
||||
Every backend has the same set of infrastructure decisions. The question is which side of the
|
||||
`import` they live on.
|
||||
|
||||
| Decision | Owned by |
|
||||
|---|---|
|
||||
| Execution order | green-tea — derived from `needs`/`provides`, never maintained by hand |
|
||||
| Dependency validation | green-tea — boot fails when nothing provides a key |
|
||||
| Which steps a route runs | green-tea — the graph slice its handler actually depends on |
|
||||
| Streaming mechanics — framing, backpressure, cleanup, disconnects | green-tea |
|
||||
| OpenAPI projection | green-tea — from the same metadata that runs the app |
|
||||
| Secure transport defaults | green-tea — headers, CORS, TLS |
|
||||
| Runtime serving boundary | green-tea — `listen`, `fetch`, `upgrade` per runtime |
|
||||
| Shutdown sequencing | green-tea — drain, then teardown, inside one deadline |
|
||||
| **Business rules** | **you** |
|
||||
|
||||
That division is the whole design, and it is why `reflect-metadata` is the only runtime dependency:
|
||||
the goal is not a small number for its own sake, it is **fewer moving parts your team has to
|
||||
understand, upgrade, coordinate and debug**. A framework that owns less pushes the difference into
|
||||
your application, where it becomes your maintenance instead of disappearing.
|
||||
|
||||
Automated does not mean invisible. `app.explain()` prints the ordered chain, `app.graph()` renders
|
||||
the live graph, and `app.openapi()` projects the same metadata — the graph is not documentation drawn
|
||||
after the fact, it is the structure green-tea validates and executes.
|
||||
|
||||
## Real-time is a primitive, not a second framework
|
||||
|
||||
@@ -98,9 +129,10 @@ class Live {
|
||||
|
||||
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
||||
|
||||
## Batteries included — still one dependency
|
||||
## What the foundation already carries
|
||||
|
||||
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
|
||||
The parts a real API needs, owned by the framework rather than assembled in your application — and
|
||||
without growing the runtime dependency tree past `reflect-metadata`:
|
||||
|
||||
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
|
||||
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
|
||||
@@ -109,8 +141,10 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything.
|
||||
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
|
||||
- **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 })`. 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.
|
||||
|
||||
@@ -243,26 +277,46 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
|
||||
|
||||
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
|
||||
|
||||
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
|
||||
**Observability is a contract, not an integration.** Core emits a correlated lifecycle event stream — every request gets an id (an incoming `x-request-id` is adopted, not replaced), every event carries it, and each step reports its own duration. `createApp({ logger })` takes any logger; the default writes structured JSON, or a readable line on a TTY. Nothing in core writes to `console`, which is enforced by a lint rule rather than a promise. `createApp({ logRequests: true })` logs a line per request, off by default.
|
||||
|
||||
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
|
||||
|
||||
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||
|
||||
**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.
|
||||
- **[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); test:deno / test:bun / test:edge for the other runtimes
|
||||
npm test # vitest (Node only) — the fast loop, ~2s
|
||||
npm run test:all # everything below, plus the JSR gate — the pre-push check
|
||||
npm run test:deno # deno test } a change to shared code can pass `npm test`
|
||||
npm run test:bun # bun test } and still be broken on one of these
|
||||
npm run test:edge # workerd via miniflare
|
||||
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
||||
npm run build # emit dist/ (tsup: dual ESM + CJS)
|
||||
npm run bench # regenerate BENCHMARKS.md
|
||||
npm run docs:dev # the documentation site (website/)
|
||||
```
|
||||
|
||||
`npm test` stays Node-only on purpose: it is the loop you run constantly, and booting Deno, Bun and
|
||||
workerd into it would tax every run to catch what CI already catches on every push. Nothing here is
|
||||
unguarded — the `runtimes` job runs all three, and `deno publish --dry-run` gates JSR. `test:all` is
|
||||
for the moment before you push, when you would rather find out locally.
|
||||
|
||||
That last one is a second type-checker, not a packaging formality: `npm run typecheck` is `tsc` with
|
||||
this repository's config, while `deno publish --dry-run` is Deno's checker with Deno's lib plus JSR's
|
||||
slow-types rules over the public API. JSR serves `src/` directly, so what it rejects is what a JSR
|
||||
consumer would have received.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
|
||||
@@ -270,9 +324,10 @@ npm run docs:dev # the documentation site (website/)
|
||||
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
|
||||
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
|
||||
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
||||
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
|
||||
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. Every CI run exercises all four; the Deno, Bun, and workerd suites gate a merge exactly as the Node one does.
|
||||
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
|
||||
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
|
||||
- ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
|
||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
|
||||
|
||||
## Versioning
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Email **security@expressive-tea.io**. Please do not open a public issue for something
|
||||
exploitable — an issue is world-readable from the moment you press the button, and that is
|
||||
the one thing a security report cannot be.
|
||||
|
||||
Include whatever you have: the version, the runtime, and the smallest app that shows it.
|
||||
A route, a module and a request is usually enough. If you have a working exploit, send it;
|
||||
if you only have a suspicion, send that instead of sitting on it.
|
||||
|
||||
You can also report privately through GitHub's
|
||||
[security advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new),
|
||||
which reaches the same people.
|
||||
|
||||
## What happens next
|
||||
|
||||
Acknowledgement within **5 working days**. A verdict on whether we agree it is a vulnerability
|
||||
within **15**. If we agree, you get the fix timeline and a heads-up before the advisory goes
|
||||
public. If we don't, you get the reasoning rather than silence.
|
||||
|
||||
Those numbers are deliberately slower than the 24 to 48 hours you will see quoted elsewhere.
|
||||
That figure comes from the CERT Guide to Coordinated Vulnerability Disclosure and describes
|
||||
vendors and coordinators — organizations with someone on rotation. This project is one person.
|
||||
A number that only holds in a good week is worse than an honest one.
|
||||
|
||||
Which is why there is an escape hatch, and you should use it. **If you have no acknowledgement
|
||||
after 10 working days**, write directly to diego.resendez@expressive-tea.io. If that is also
|
||||
met with silence, consider yourself released from any embargo and disclose as you see fit. You
|
||||
will not have done anything wrong: a project that goes quiet on a security report has spent
|
||||
whatever claim it had on your patience.
|
||||
|
||||
## Disclosure window
|
||||
|
||||
We ask for **90 days** from your report before public disclosure, or until the fix ships,
|
||||
whichever comes first. That is the industry default and we are not asking you for more than
|
||||
anyone else does. If the fix is out in a week, so is the advisory.
|
||||
|
||||
If a vulnerability is being actively exploited, the window is however long it takes us to ship,
|
||||
and we will say so rather than hold you to 90 days while users are being attacked.
|
||||
|
||||
We publish a GitHub advisory for anything that affects a released version, and credit you by
|
||||
the name you ask for. Say so if you would rather not be named.
|
||||
|
||||
There is no bug bounty and no money, which we would rather state here than leave you to find
|
||||
out after the work.
|
||||
|
||||
## Supported versions
|
||||
|
||||
While the package is in beta, only the most recent `26.x.y-beta.N` receives fixes. There is no
|
||||
backport channel yet; when the first stable ships, this section gets the real table.
|
||||
|
||||
## Scope
|
||||
|
||||
In scope: anything in `src/` that ships in the published package — route matching, the request
|
||||
pipeline, body parsing and its limits, the security headers and CORS handling, TLS setup, the
|
||||
WebSocket upgrade path, the mesh wire protocol, static file serving and view rendering.
|
||||
|
||||
Out of scope: the benchmarks in `bench/`, the documentation site (now its own repository,
|
||||
[green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)), dev-only tooling, and
|
||||
anything that requires an attacker to already control your application code. Advisories in
|
||||
build-time dependencies are worth telling us about, but they are not vulnerabilities in
|
||||
green-tea and we handle them as ordinary dependency updates.
|
||||
|
||||
A denial of service that needs no authentication is in scope. Reports that amount to "this
|
||||
endpoint is slow under load" generally are not — but if you are unsure which one you have,
|
||||
send it and let us decide.
|
||||
@@ -1,4 +1,19 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"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
|
||||
// `@green-tea/core/bun` has to work whichever registry the reader installed from.
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./deno": "./src/deno.ts",
|
||||
"./bun": "./src/bun.ts",
|
||||
"./edge": "./src/edge.ts"
|
||||
},
|
||||
"publish": {
|
||||
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
|
||||
},
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# Observability — Design
|
||||
|
||||
**Issue:** [#10](https://github.com/Expressive-Tea/green-tea/issues/10) · **Status:** reviewed, all decisions settled · **Constraint:** no new runtime dependency
|
||||
|
||||
---
|
||||
|
||||
## The diagnosis is not the one in the issue
|
||||
|
||||
#10 says green-tea "ships no logging, metrics or tracing contract today", and asks for an injectable logger, structured output, tracing hooks and metrics as one design. The framing is right; the starting point is wrong, and it changes what the work is.
|
||||
|
||||
**The mechanism already exists.** `Bus` (`src/bus.ts`) is an in-process event emitter with 19 emission points already wired through boot, the pipeline, streams, WebSockets, mesh and plugins. Plugins already receive `bus.on` — and only `on`, so isolation is structural (`src/plugin.ts:27`).
|
||||
|
||||
What is actually missing is narrower and more serious than "there is no logger":
|
||||
|
||||
| # | Finding | Where |
|
||||
|---|---|---|
|
||||
| 1 | **No event carries request identity.** Under any concurrency, interleaved `request:step:enter` events cannot be attributed to a request. | `src/pipeline.ts:53,56` |
|
||||
| 2 | **`durationMs` is declared and never set by anything.** There is no timing in the system at all. | `src/bus.ts:22`, zero writers |
|
||||
| 3 | **No request-level events exist.** No `started`/`completed`/`failed`, so there is no span for step events to hang from. | — |
|
||||
| 4 | **A failing step is reported as `name: 'pipeline'`**, losing which step broke. | `src/pipeline.ts:98` |
|
||||
| 5 | **8 `console.warn` calls in core**, unredirectable. | `src/app/index.ts` ×6, `src/deno.ts`, `src/bun.ts` |
|
||||
|
||||
So the real statement of the problem is:
|
||||
|
||||
> The event stream exists but is **not correlatable and not measured**, which makes it unusable for production observability regardless of what consumes it.
|
||||
|
||||
That is *why* #10 is one design and not six — a sharper reason than the issue had. A logger, a metrics exporter and an OpenTelemetry bridge are not three features; they are three **consumers of one corrected event stream**. Fix correlation and timing once, and all three become adapters outside core. Ship them separately and each grows its own private notion of "which request was that", which is the three-mechanisms failure #10 warned about.
|
||||
|
||||
**Consequence for sequencing:** most of this work is in `src/bus.ts` and `src/pipeline.ts`, not in new files.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1 — The logger is a distinct registration, not an ordinary provider
|
||||
|
||||
`createApp({ logger })`, not `@Provider({ provides: 'logger' })`.
|
||||
|
||||
The deciding constraint is ordering. `boot:provider:start`/`fail` fire *while* the graph is booting (`src/app/index.ts:639-647`), and the optional-provider failure warning at `src/app/index.ts` logs during that same phase. A provider cannot log its own boot failure, and a logger that only exists after the graph resolves cannot report the graph failing to resolve. Shutdown has the same shape: `closeApp` warns after the graph is gone.
|
||||
|
||||
The logger is therefore framework infrastructure with a lifetime wider than the graph.
|
||||
|
||||
It is *additionally* exposed as an injectable key so steps and handlers reach it with `@needs('logger')` like anything else. One object, two access paths, no second implementation.
|
||||
|
||||
**Default:** structured JSON. Human-readable when the process is interactive, decided once at boot rather than per call. **Never a dependency** — the default writes to `console` behind the same interface everyone else implements, which is what lets the 8 direct `console.warn` calls become logger calls without core gaining a logging library.
|
||||
|
||||
### D2 — One emitter. Extend `Bus`; do not add a parallel hook system
|
||||
|
||||
Per-category hooks would be a second mechanism competing with an emitter that already has 19 call sites and a plugin contract built on it. `LifecycleEvent` grows; nothing new is introduced.
|
||||
|
||||
This also keeps the existing guarantee intact: `emit` swallows listener failures (`src/bus.ts:41`) precisely so observers can never break the pipeline. Observability must not acquire the power to take down a request.
|
||||
|
||||
**This is exactly why shutdown teardown does not belong here** — see Task 2.5 in the trust-release plan. A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
|
||||
|
||||
### D3 — A step failure emits both `request:step:error` and `request:failed`
|
||||
|
||||
They answer different questions — *which step broke* and *did this request fail* — and a tracing exporter needs both: one marks the span, the other marks the trace. Emitting only the outer event is what produces a trace that says a request failed with no indication where.
|
||||
|
||||
`request:step:error` must also carry the real step name. Emitting `name: 'pipeline'` (`src/pipeline.ts:98`) is a bug, not a design choice, and it is fixed as part of this.
|
||||
|
||||
### D4 — Streams and WebSockets emit lifecycle events only, never per-message
|
||||
|
||||
`stream:open`/`close`/`error` already exist and are the right granularity. A per-message event on a high-rate SSE or WebSocket stream is a firehose that costs more than it reports, and the cost lands on the workload least able to absorb it.
|
||||
|
||||
Anyone who needs per-message visibility instruments their own handler, where they know the message semantics. Same reasoning that keeps WebSocket upgrades outside the concurrency gate in #21.
|
||||
|
||||
### D5 — Request identity is generated with `crypto.randomUUID()`, and inherited when offered
|
||||
|
||||
No new dependency is available, so no UUID library. `globalThis.crypto.randomUUID` is present on Node, Deno and Bun (verified locally) and is Web Crypto on workerd.
|
||||
|
||||
**To validate during implementation:** Node 18 is the floor in `package.json` and CI's `build` job pins `node-version: '18'`, so a gap there fails CI rather than reaching a user. `test:edge` covers workerd the same way.
|
||||
|
||||
An incoming `x-request-id` is adopted rather than replaced — a green-tea service behind a gateway must not start a second identity for the same request. A `traceparent` header, if present, is carried as `traceId` untouched; core parses nothing and implements no propagation spec. That belongs in the OpenTelemetry adapter, which owns W3C Trace Context.
|
||||
|
||||
---
|
||||
|
||||
## The contract
|
||||
|
||||
### Events
|
||||
|
||||
Existing, unchanged in name: `boot:provider:start|ok|fail`, `request:step:enter|leave|error`, `stream:open|close|error`, `mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||
|
||||
Added:
|
||||
|
||||
```
|
||||
request:start request:end request:failed
|
||||
route:matched route:unmatched
|
||||
graph:resolved graph:failed
|
||||
```
|
||||
|
||||
`route:unmatched` rather than the report's `route.not_found`: a 405 is also an unmatched route and is not a 404, and naming the event after one outcome would misreport the other.
|
||||
|
||||
### Payload
|
||||
|
||||
`EventPayload` gains the correlation and measurement fields it lacks. Every field stays optional — mesh and boot events have no request to name, and forcing a shape on them would mean inventing values.
|
||||
|
||||
```ts
|
||||
interface EventPayload {
|
||||
name: string;
|
||||
scope?: string;
|
||||
error?: unknown;
|
||||
durationMs?: number; // declared today, written by nothing — this design makes it real
|
||||
requestId?: string; // the correlation fix
|
||||
traceId?: string; // inherited from traceparent when present; never synthesized
|
||||
route?: string; // the matched pattern, not the raw URL — bounded cardinality for metrics
|
||||
method?: string;
|
||||
transport?: Transport;
|
||||
status?: number;
|
||||
runtime?: 'node' | 'deno' | 'bun' | 'edge';
|
||||
}
|
||||
```
|
||||
|
||||
`route` is the **pattern** (`/users/:id`), never the concrete path. A metrics consumer that labels a counter with the raw URL produces unbounded cardinality and takes down the metrics backend rather than the app — the framework should not hand a user that shape by default.
|
||||
|
||||
### Metrics
|
||||
|
||||
No metrics registry in core, and no new event type for them. Per-step timings come from `durationMs` on the events already defined; a metrics adapter subscribes and aggregates. The graph already knows every node, which is what makes this close to free — but the timing instrumentation is measured before it is declared free, per Trust Release §6, and stays opt-in if the measurement says otherwise.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope, deliberately
|
||||
|
||||
- **OpenTelemetry itself.** A separate `@green-tea/opentelemetry` package. Core exposes the stream; it never imports an exporter, and never depends on one.
|
||||
- **Log shipping, sampling, redaction.** Consumer concerns. Core hands over structured records.
|
||||
- **Trace context propagation.** Carried, not parsed. The adapter owns W3C Trace Context.
|
||||
- **Shutdown teardown for plugins/providers.** Task 2.5, a different guarantee — see D2.
|
||||
|
||||
---
|
||||
|
||||
### D6 — A request span ends when the handler returns, and stream events carry its `requestId`
|
||||
|
||||
A streaming route returns from `handle()` in milliseconds while the connection lives for minutes or hours. `request:end` fires at the handler's return, so latency histograms measure time-to-first-byte and stay meaningful instead of mixing 2 ms buffered requests with hour-long SSE connections in one distribution. Connection duration is already available from `stream:open`/`stream:close`, which now carry the same `requestId` so a consumer can join the two.
|
||||
|
||||
This is the same boundary #21 chose for its concurrency gate — release when `handle()` returns, treat long-lived streams like upgrades. Answering it differently in the two places would mean the framework disagreed with itself about when a request is over.
|
||||
|
||||
### D7 — Per-step timing is always on, measured at step boundaries
|
||||
|
||||
Measured before deciding, on the box `BENCHMARKS.md` was produced on:
|
||||
|
||||
| Approach | Cost per step | Share of one request |
|
||||
|---|---:|---:|
|
||||
| `performance.now()` ×2 per step | 45.3 ns | 0.44% |
|
||||
| **`performance.now()` at step boundaries (N+1 calls for N steps)** | **25.2 ns** | **0.25%** |
|
||||
| `Date.now()` ×1 | 28.6 ns | — |
|
||||
|
||||
Baseline: 98,093 req/s ≈ 10.19 µs per request.
|
||||
|
||||
Two things follow. `Date.now()` loses on both axes — slower *and* coarser — so `performance.now()` is unambiguous. And a step's end is the next step's start, so a pipeline of N steps needs N+1 timestamps rather than 2N, halving the cost.
|
||||
|
||||
At 0.25% per step the overhead sits **below the 0.3% run-to-run CV of the project's own benchmark**, so it is not measurable in the harness that would have to justify a flag. Making it opt-in would buy two code paths and a configuration surface in exchange for something nobody can observe. Always on.
|
||||
|
||||
> **Correction, after implementation.** This decision survived; its reasoning did not. The measured cost is **+7.0% of the framework's own per-request work** (~0.29 µs, ~2% over a real socket), and it is *fixed per request* rather than per step — per-step work is skipped entirely when nothing subscribes. "Always on" is still right, and for a better reason: there is nothing per-step left to make optional.
|
||||
>
|
||||
> Three earlier figures for this were published before that one and all three were wrong, each from a comparison with more than one variable moving. See Task 7 in the implementation plan for what went wrong and why interleaving is not optional here.
|
||||
|
||||
### D8 — Request logging is a `Bus` subscriber, wrapped so a failing logger cannot go silent
|
||||
|
||||
The logger is a callable sink either way — the 8 direct diagnostics (shutdown timeout, degraded provider) are not events and need one regardless. The decision is only about request logging, and it goes through the event stream: one path, and it is composable and removable exactly as #10 asks for ("a composable step, not a global middleware").
|
||||
|
||||
The cost this closes: `emit` swallows listener failures by design (`src/bus.ts:41`), so a user-supplied logger that throws would stop writing with nobody informed. The built-in subscriber is therefore wrapped to fall back to `console` on failure. The Bus keeps its guarantee — an observer still cannot break a request — without buying it with silence.
|
||||
|
||||
---
|
||||
|
||||
## Verification this design must survive
|
||||
|
||||
`npm run lint && npm run format:check && npm run typecheck && npm test`, plus `test:deno`, `test:bun` and `test:edge` — all four now gate a merge. Per-request instrumentation is on the hot path, so `npm run bench` before and after, with the numbers in the implementation plan.
|
||||
@@ -0,0 +1,166 @@
|
||||
# Observability — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Design:** [2026-08-16-observability-design.md](./2026-08-16-observability-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
|
||||
|
||||
**Goal:** Make the existing event stream correlatable and measured, then build the logger on top of it as its first consumer. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
|
||||
|
||||
**Architecture:** Most of this lands in `src/bus.ts` and `src/pipeline.ts`. The `Bus` already has 19 emission points; this adds identity, timing and the request-level events those points had nothing to hang from. No new runtime dependency — `reflect-metadata` stays the only one, and the OpenTelemetry bridge lives outside core.
|
||||
|
||||
**Tech Stack:** TypeScript, Vitest, Deno/Bun/workerd suites, `performance.now()`, `crypto.randomUUID()`.
|
||||
|
||||
---
|
||||
|
||||
## Order
|
||||
|
||||
Tasks 1–3 are the correction; 4–6 are what consumes it. Do not start 4 before 3 — a logger built on uncorrelated events would need its own notion of request identity, which is the failure the design exists to prevent.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Give every request an identity, and carry it
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/core.ts` (`NeutralRequest`, `handle`)
|
||||
- Modify: `src/http/server.ts` (~line 120, the Node call into `handle`)
|
||||
- Modify: `src/http/web.ts` (~line 178, the Fetch call into `handle`)
|
||||
- Modify: `src/bus.ts`
|
||||
- Test: `test/observability.test.ts` (new)
|
||||
|
||||
**Step 1:** Extend `EventPayload` with the optional fields from the design: `requestId`, `traceId`, `route`, `method`, `transport`, `status`, `runtime`. All optional — boot and mesh events have no request to name.
|
||||
|
||||
**Step 2:** Add `requestId` to `NeutralRequest` (`src/http/core.ts`). Generate it in the **adapters**, not in `handle()`, and here is why that placement matters: both adapters read and size-check the body before they reach `handle()` (`server.ts:107`, `web.ts:143` per the #21 analysis), so a 413 is rejected before `handle()` ever sees the request. Generating inside `handle()` would leave exactly the failures an operator most wants to correlate without an id.
|
||||
|
||||
**Step 3:** One shared helper for generation, so the two adapters cannot diverge on the rule: adopt an incoming `x-request-id`, otherwise `crypto.randomUUID()`. Carry `traceparent` through as `traceId` **without parsing it** (D5).
|
||||
|
||||
**Step 4:** Write the test that fails first: fire two concurrent requests through `app.fetch`, collect `request:step:enter` from the bus, and assert every event carries a `requestId` and that the two requests' events never share one. This is the defect the whole design exists to fix, so it is the first test.
|
||||
|
||||
**Verify:** `crypto.randomUUID` on Node 18 — CI's `build` job pins `node-version: '18'`, and `test:edge` covers workerd. Do not assume; let both run.
|
||||
|
||||
### Task 2: Measure steps at their boundaries
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pipeline.ts` (`runSteps`, ~line 48)
|
||||
- Test: `test/observability.test.ts`
|
||||
|
||||
**Step 1:** Take `performance.now()` once before the loop, then once per iteration — **N+1 timestamps for N steps**, because a step's end is the next step's start. Not two per step. The design measured the difference: 25.2 ns vs 45.3 ns per step (D7).
|
||||
|
||||
**Step 2:** Attach `durationMs` to `request:step:leave`. The field has been declared in `EventPayload` since the beginning and written by nothing; this is what makes it real.
|
||||
|
||||
**Step 3:** Always on, no flag (D7 — 0.25% of a request, below the benchmark's own 0.3% CV).
|
||||
|
||||
**Verify:** a step that sleeps a known interval reports a `durationMs` in that neighbourhood. Assert a range, never an exact value.
|
||||
|
||||
### Task 3: Stop losing which step failed
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pipeline.ts` (`runSteps`, and the catch at ~line 98)
|
||||
- Test: `test/observability.test.ts`
|
||||
|
||||
`request:step:error` currently emits `{ name: 'pipeline' }`, which throws away the one fact it exists to report.
|
||||
|
||||
**Step 1:** Wrap each `step.run` inside `runSteps`, emit `request:step:error` with the real step name and `scope`, and rethrow unchanged. Do not swallow.
|
||||
|
||||
**Step 2:** `runPipeline`'s existing catch now emits `request:failed` instead of a second `step:error` (D3). Both fire for a failing step, deliberately: one marks the span, the other the trace.
|
||||
|
||||
**Verify:** a three-step pipeline whose middle step throws emits `request:step:error` naming *that* step, plus exactly one `request:failed`.
|
||||
|
||||
### Task 4: The logger contract
|
||||
|
||||
**Files:**
|
||||
- Create: `src/logger.ts`
|
||||
- Modify: `src/app/index.ts` (`createApp` options; the 6 `console.warn` calls)
|
||||
- Modify: `src/deno.ts`, `src/bun.ts` (1 `console.warn` each)
|
||||
- Modify: `src/index.ts` (export the type)
|
||||
- Test: `test/logger.test.ts` (new)
|
||||
|
||||
**Step 1:** Define the interface. Keep it to the levels core actually uses — resist inventing a hierarchy nobody calls.
|
||||
|
||||
**Step 2:** Default implementation: structured JSON, human-readable when the process is interactive, decided **once at boot** rather than per call. It writes through `console`; core gains no logging dependency (D1).
|
||||
|
||||
**Step 3:** `createApp({ logger })`. A distinct registration, not a provider — it has to outlive the graph to report the graph failing to boot (D1). Per `AGENTS.md`, a new public option means `src/app/types.ts` too if it appears on `App`.
|
||||
|
||||
**Step 4:** Replace all 8 `console.warn` calls. `grep -rn "console\." src/` must return nothing afterwards, which is the check #10 actually asks for.
|
||||
|
||||
**Step 5:** Expose the logger under an injectable key so steps and handlers reach it with `@needs('logger')`. One object, two access paths, no second implementation.
|
||||
|
||||
### Task 5: Request logging as a subscriber
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/logger.ts`
|
||||
- Test: `test/logger.test.ts`
|
||||
|
||||
**Step 1:** Build request logging as `bus.on(...)` over the corrected stream (D8). Composable and removable, which is what #10 means by "a composable step, not a global middleware".
|
||||
|
||||
**Step 2:** Wrap the subscriber so a throwing logger falls back to `console`. `Bus.emit` swallows listener failures by design (`src/bus.ts:41`); without the wrapper a broken user logger stops writing and tells nobody. The Bus keeps its guarantee; it just stops paying for it with silence.
|
||||
|
||||
**Verify:** a logger that throws on every call still produces output, and the request still succeeds.
|
||||
|
||||
### Task 6: The remaining events
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/bus.ts`, `src/http/core.ts`, `src/app/index.ts`
|
||||
|
||||
**Step 1:** Add `request:start|end|failed`, `route:matched|unmatched`, `graph:resolved|failed` to `LifecycleEvent`.
|
||||
|
||||
**Step 2:** `request:end` fires **when the handler returns**, not when a stream closes (D6). `stream:open`/`close` carry the same `requestId` so a consumer joins them itself.
|
||||
|
||||
**Step 3:** `route:unmatched` covers 404 and 405 both — naming it after one outcome would misreport the other.
|
||||
|
||||
**Step 4:** `route` on every payload is the **matched pattern**, never the concrete path. A metrics consumer labelling on raw URLs produces unbounded cardinality and takes down the metrics backend; the framework must not hand anyone that shape by default.
|
||||
|
||||
### Task 7: Benchmark, and publish the number — **DONE; D7 was wrong in shape**
|
||||
|
||||
**Files:**
|
||||
- Modify: `BENCHMARKS.md`
|
||||
|
||||
D7 predicted ~0.25% **per step**, invisible against the harness's own 0.3% CV.
|
||||
|
||||
**Measured: +7.0% of the framework's own per-request work** — 4.074 µs → 4.361 µs, medians of five interleaved rounds, ranges not overlapping. About 0.29 µs, or ~2% of a request over a real socket.
|
||||
|
||||
The prediction was wrong in **shape**, not only magnitude. Per-step work is skipped entirely when nothing subscribes (`Bus.hasListeners`), so a deep pipeline pays no more than a shallow one; what remains is a **fixed per-request** cost — generating the request id, reading two headers, and the guard checks. "Always on" survives, for a better reason than it was made with: there is nothing per-step left to make optional.
|
||||
|
||||
**Three earlier numbers for this were published and all three were wrong**, which is the more useful lesson: −3.9%, then 0.8%, then −6.8%. Each came from a comparison with more than one variable moving.
|
||||
|
||||
- The first two were sequential rather than interleaved. The same code measured at the start and end of one session differed by **12%** as the machine warmed, so run order was indistinguishable from effect — one of them even reported the wrong sign.
|
||||
- The third compared `7bd11bf` against `HEAD`, which differ by observability **and** three performance fixes pulling the other way. It reported their net as if it were one of them.
|
||||
|
||||
The number above compares `7bd11bf` against `523e318`, the last commit before those fixes, alternating round by round.
|
||||
|
||||
Two regressions were found and fixed by measuring rather than reasoning, both larger than anything the design anticipated:
|
||||
|
||||
- **A second `async` frame in `handle()` cost 0.43 µs/request** — a promise and two microtask ticks, an order of magnitude more than the four `Map` lookups it existed to arrange. `handle()` is no longer `async`.
|
||||
- **A closure allocated per request inside `correlateRequest`** cost 0.16 µs, 45% of the then-remaining overhead, for a helper capturing nothing.
|
||||
|
||||
Recorded here because the lesson generalises: on this path, an extra promise costs more than any amount of bookkeeping, and a hot-path prediction reasoned from primitive costs was off by more than 10×.
|
||||
|
||||
### Task 8: Documentation
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md` (the *Honest scope* paragraph at ~line 246)
|
||||
- Modify: `website/src/content/docs/` — a new observability guide, plus the `createapp` reference table
|
||||
|
||||
`README.md:246` currently opens "**No observability layer, either.**" and links to #10. It is the single most load-bearing sentence in the CTO assessment, and rewriting it is part of this work rather than follow-up. Say what now exists and what still does not — the OpenTelemetry adapter is not in core and should not be implied to be.
|
||||
|
||||
Per `AGENTS.md`, new public API needs a note in `README.md`.
|
||||
|
||||
> If Phase 4 has already moved the site, the guide lands in the docs repository instead.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope
|
||||
|
||||
`@green-tea/opentelemetry`, log shipping, sampling, redaction, W3C Trace Context parsing, and plugin/provider teardown (Task 2.5 in the trust-release plan — an awaited teardown and a non-blocking observer are opposite guarantees).
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run complexity:check && npm run typecheck && npm test
|
||||
npm run test:deno && npm run test:bun && npm run test:edge # all three gate a merge now
|
||||
npm run bench # hot-path change
|
||||
grep -rn "console\." src/ # must be empty
|
||||
```
|
||||
@@ -0,0 +1,350 @@
|
||||
# Trust Release Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Close the gaps that four independent evaluations agree on, in the order that makes each one cheap. Prove portability in CI, make derived execution explainable, ship an observability contract, and move the documentation site out of the core repository so it gets its own lifecycle.
|
||||
|
||||
**Architecture:** Nothing here adds a runtime dependency. The observability work is a contract plus emission points, with exporters living outside core. The explain work is a resolver over data `explainRoute` already returns. The runtime matrix runs suites that already exist. The docs split moves a directory that is already self-contained.
|
||||
|
||||
**Tech Stack:** TypeScript, legacy decorators, Vitest, Deno/Bun/Workers runtimes, JSR, Astro/Starlight, GitHub/Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
## Why this order
|
||||
|
||||
The four reports in `.specs/reports/` were written independently and converge on one gap. Observability is the only dimension the CTO due diligence marks as risk **Alto** on its own (§5.3, risk register), it is P0 twice in the Trust Release report (§4, §5), and it is a listed con in the lead-dev report (§4). That is GH #10, and it is the largest item here — which is exactly why it is not first. The three phases before it are cheap, unblock evidence, and produce the material that #10's design needs.
|
||||
|
||||
Two things the reports demand that had **no issue filed**, both verified against the code rather than taken on the report's word:
|
||||
|
||||
- **Runtime matrix in CI.** `package.json:91-93` defines `test:deno`, `test:bun` and `test:edge`. `.github/workflows/ci.yml` runs none of them. `AGENTS.md:23` already warns that `npm test` does not cover the other runtimes — and CI does not close that. The framework's headline claim has no CI evidence. Trust Release §7 (P0), CTO §8.2 and P0-6.
|
||||
- **`explain()` does not explain causality.** `src/app/introspect.ts:62` returns a flat `chain` with `needs`/`provides` per node, but never the edge from a need to the node that produced it. Trust Release §2 (P0).
|
||||
|
||||
One thing that **has** an issue but appears in no report: **#13 circuit breaker**. Neither the CTO report nor the Trust Release report raises it; the nearest item is "rate limiter" under the CTO's security pack (P0-3), which is a different mechanism. The issue itself already says a worked example in the docs might close it outright. It is scheduled last, as documentation.
|
||||
|
||||
**API freeze is deliberately not a phase.** `README.md:276` already declares it under `**next**`. It needs the RC boundary, and freezing a public surface before #10 lands would freeze an API that is still missing its observability contract. What this plan adds instead is a stability *contract* — a statement of which areas are volatile today, which promises nothing and commits to no date (Task 6.1).
|
||||
|
||||
**Out of scope: #21 and #17.** Both are claimed by `hgshreyas` with the design already settled in the issue threads. Do not touch them.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0: Unblock releases
|
||||
|
||||
### Task 0.1: Scope the audit gate in stage and release
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/stage.yml`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
`AGENTS.md:71` states the policy: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. `ci.yml:56-59` implements it. `stage.yml:21` and `release.yml:26` run bare `npm audit`, so a dev-only advisory blocks a publish. This is drift, not a second policy.
|
||||
|
||||
That drift is what stopped work twice. The `nanoid` advisory reached the tree through `tsup → postcss → nanoid` — a build-tooling path that ships to nobody.
|
||||
|
||||
**Step 1:** In both files, change `npm audit` to `npm audit --omit=dev`, and add a non-blocking full `npm audit` with `continue-on-error: true` after it so the advisory is still visible in the log.
|
||||
|
||||
**Step 2:** Carry a comment on the blocking step pointing at the rule, in the voice `ci.yml` already uses — the next person to read it should see a decision, not an omission.
|
||||
|
||||
**Verify:** `grep -n "npm audit" .github/workflows/*.yml` — every blocking occurrence carries `--omit=dev`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Prove portability, and publish to JSR
|
||||
|
||||
These are one phase because they are one subject. The type error JSR found is on the `app.fetch` path, which is the path Deno, Bun and edge all use; a runtime matrix would have caught it first. Fixing them together means the matrix has a green baseline to protect.
|
||||
|
||||
### Task 1.1: Fix the `BodyInit` hole on the Fetch path
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/web.ts`
|
||||
- Test: `test/` (the Fetch adapter suite)
|
||||
|
||||
Gitea #19 reports, from a real `deno publish --dry-run`:
|
||||
|
||||
```
|
||||
TS2345: Argument of type 'string | Buffer<ArrayBufferLike> | null' is not
|
||||
assignable to parameter of type 'BodyInit | null | undefined'.
|
||||
--> src/http/web.ts:112:23
|
||||
```
|
||||
|
||||
`Buffer` is not a valid `BodyInit` under Deno's lib. It works at runtime because implementations are forgiving, which is what makes it worth fixing before a user reports it as a bug: it is a genuine typing hole on the runtime-agnostic path, not a JSR formality.
|
||||
|
||||
**Step 1:** Write a failing test that drives a `Buffer` body through the Fetch adapter and asserts the response body round-trips byte-for-byte.
|
||||
|
||||
**Step 2:** Narrow the body to a real `BodyInit` at the boundary — convert the `Buffer` to a view its type declares, rather than casting the error away. A cast would keep the hole and hide it.
|
||||
|
||||
**Step 3:** Confirm the test passes and `npm run typecheck` is clean.
|
||||
|
||||
### Task 1.2: Give the slow-type sites explicit return types
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/metadata.ts` (11 sites)
|
||||
- Modify: `src/params.ts` (6 sites)
|
||||
|
||||
Two shapes, both mechanical: `missing-explicit-return-type` on factory functions (`routeDecorator` at `src/metadata.ts:103`, `envelope` at `src/params.ts:35`) and `missing-explicit-type` on the exported constants built from them (`export const Get = routeDecorator('GET', 'buffer')` at `src/metadata.ts:126`).
|
||||
|
||||
**Do not pass `--allow-slow-types`.** That flag degrades generated declarations and makes type checking 1.5–2× slower for consumers, in the framework whose central claim is type safety. Shipping it would contradict the pitch on its own install page.
|
||||
|
||||
**Step 1:** Annotate the factories first — several of the constant errors resolve on their own once the factory's return type is written down.
|
||||
|
||||
**Step 2:** Annotate whatever constants remain.
|
||||
|
||||
**Step 3:** `deno publish --dry-run` reports zero slow types, with no flags.
|
||||
|
||||
**Verify:** `npm run typecheck` and `npm test` still clean; the public types in `dist/` are unchanged or strictly more precise.
|
||||
|
||||
### Task 1.3: Runtime matrix in CI
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
|
||||
The suites exist and CI ignores them. Add a matrix job that runs `test:deno`, `test:bun` and `test:edge` alongside the Node build.
|
||||
|
||||
**Step 1:** Add a job with the three runtimes, each installing its own toolchain. Keep it a separate job from `build` so a Bun failure reports as a Bun failure and does not bury the Node lint output — the same reasoning `ci.yml:53` already applies to the audit step.
|
||||
|
||||
**Step 2:** Confirm the forge difference documented at `AGENTS.md:73` does not bite: GitHub reads `pull_request` workflows from the base branch, so this workflow change cannot validate itself and must reach the base before it gates anything.
|
||||
|
||||
**Step 3:** Publish the resulting capability matrix. `README.md:273` already claims all four runtimes; the matrix is what turns that claim into evidence.
|
||||
|
||||
**Verify:** A deliberate break in shared code fails the Deno job and not only the Node one.
|
||||
|
||||
### Task 1.4: Claim the JSR scope and publish
|
||||
|
||||
**Files:**
|
||||
- Modify: `deno.json`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
**Blocked on Diego and not delegable:** `@green-tea` on jsr.io must be claimed with a GitHub account.
|
||||
|
||||
**Step 1:** Add `name`, `version` and `exports` to `deno.json`. Decide whether all four entry points (`.`, `./deno`, `./bun`, `./edge`) are exported or only the Deno one.
|
||||
|
||||
**Step 2:** Publish from the same `v*` tag that publishes to npm, using GitHub Actions OIDC. `release.yml` already holds `id-token: write` for npm Trusted Publishing, so JSR needs no new secret.
|
||||
|
||||
**Step 3:** Nothing here justifies cutting a release on its own — it rides along with the next version cut that has a reason.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: The shutdown cluster
|
||||
|
||||
Four open issues, all consequences of the `close({ timeoutMs })` contribution that just merged (`3dcf784`). Treated as one deliverable because they are one subject: Trust Release §14 (P1, lifecycle guarantees) and CTO P0-4 (production checklist, shutdown).
|
||||
|
||||
Order matters — the bug first, then the API, then the docs that describe the finished API.
|
||||
|
||||
### Task 2.1: #20 — `finish()` reads its timer before declaration
|
||||
|
||||
A use-before-declare bug. Smallest item in this plan and it is already shipped. Fix it, and leave a test that fails if the ordering regresses.
|
||||
|
||||
### Task 2.2: #19 — shutdown deadline settable at `createApp` level
|
||||
|
||||
The 10s deadline is hardcoded. Make it configurable at app level, with `close({ timeoutMs })` still overriding per call.
|
||||
|
||||
Per `AGENTS.md:81`, a new option on a public interface **must** also change `src/app/types.ts`. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
|
||||
|
||||
### Task 2.3: #15 — graceful shutdown is Node-only — **DECIDED, DONE**
|
||||
|
||||
**Decision: `app.close()` stays Node-only; each adapter that owns a server offers the same `close({ timeoutMs })`.** The framework's line is *it handles architecture, you handle business*, and draining is owned by whoever holds the handle.
|
||||
|
||||
What the runtimes turned out to allow, measured rather than assumed:
|
||||
|
||||
| Runtime | Drain | After the deadline |
|
||||
|---|---|---|
|
||||
| Node | `server.close()` | `closeAllConnections()` — remainder cut |
|
||||
| Bun | `stop(false)` | `stop(true)` — remainder cut |
|
||||
| Deno | `shutdown()` | **returns anyway** — remainder ends with the process |
|
||||
|
||||
Deno cannot escalate. Aborting the serve signal while `shutdown()` is pending throws `BadResource: Bad resource ID` from Deno's own listener — uncaught, and fatal under `deno test`. Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long `close()` waits, not when connections die, and `runtimes.md` says so in a table rather than averaging the three.
|
||||
|
||||
`closeWithDeadline` (`src/http/shutdown.ts`) is shared so the two adapters cannot drift into different meanings of the same `timeoutMs`, and it resolves on its own timer rather than awaiting the force call — Bun's `stop(true)` was measured waiting out a handler with a pending timer, which is the unbounded wait the deadline exists to prevent.
|
||||
|
||||
### Task 2.5: Shutdown as an extension point — **OPEN, needs its own design**
|
||||
|
||||
Raised while deciding #15: shutdown should emit signals so plugins and providers register their own teardown, instead of every consumer writing `process.on('SIGTERM', …)` by hand. Same principle as the decision above — the framework owns the plumbing.
|
||||
|
||||
It does **not** fit the existing `Bus`, and that is the finding worth carrying forward. `Bus.on` takes a synchronous listener (`src/bus.ts:29`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:38`, `catch {}`). That is deliberate — observers must never break the pipeline — but a plugin closing a database connection needs shutdown to *wait for it*. Registering a teardown is not observing an event, and bending `Bus` to do both would cost the guarantee that makes it safe.
|
||||
|
||||
So it needs: an await-aware teardown registry, a new surface on `PluginApi` (public API — `src/plugin.ts:19`), and a decision about provider cleanup. That is Trust Release §14 "Graceful lifecycle guarantees" and CTO P0-4, and it belongs in a design document rather than inside a bug-fix cluster. Sequence it with Phase 3, whose observability contract shares the same lifecycle vocabulary.
|
||||
|
||||
### Task 2.4: #18 — docs still describe `close()` without the timeout
|
||||
|
||||
Last, so it documents the finished API rather than being rewritten twice. If Phase 4 has already run, this lands in the docs repository instead.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Observability (#10)
|
||||
|
||||
The one every report puts first, and the only one that needs a design document before code.
|
||||
|
||||
### Task 3.1: Design document
|
||||
|
||||
**Files:**
|
||||
- Create: `.specs/2026-XX-XX-green-tea-observability-design.md`
|
||||
|
||||
Write the design before any implementation, following the design/plan pairing already in `.specs/`.
|
||||
|
||||
The issue is explicit that this is **one design, not six**: an injectable logger, structured output and tracing hooks are the same API decision, and solving them separately leaves three mechanisms that do not fit together.
|
||||
|
||||
Inputs to reconcile:
|
||||
|
||||
- The scope in GH #10 — injectable logger contract, JSON default with human-readable dev output, request/response logging as a composable step rather than global middleware, hooks an exporter can attach to, metrics export.
|
||||
- The Trust Release event vocabulary (§4) — `request.*`, `route.*`, `step.*`, `provider.*`, `graph.*`, `websocket.*`, `stream.*` — and its context fields (`requestId`, `traceId`, `route`, `transport`, `step`, `duration`, `status`, `scope`, `runtime`).
|
||||
- Trust Release §6, graph timing. Per-step timings are close to free because the graph already knows every node, but the instrumentation stays opt-in if overhead is measurable. Measure before deciding.
|
||||
|
||||
Hard constraint, restated from `AGENTS.md:11`: **no new runtime dependency.** Core stays on `reflect-metadata` alone. An OpenTelemetry exporter is a separate package (`@green-tea/opentelemetry`), never a core dependency.
|
||||
|
||||
Decisions the design must settle rather than leave open:
|
||||
|
||||
1. Is the logger a provider like any other, or a distinct registration?
|
||||
2. Do events go through one emitter or through per-category hooks?
|
||||
3. Does a step failure emit `step.failed` and `request.failed`, or only the outer one?
|
||||
4. Do long-lived streams and WebSockets emit per-message events, or only lifecycle ones? (The same reasoning that keeps upgrades out of the #21 gate applies.)
|
||||
|
||||
### Task 3.2: Implement to the approved design
|
||||
|
||||
Do not start before the design is reviewed. Write the implementation plan from the approved design, as `.specs/` already does for every other subsystem.
|
||||
|
||||
### Task 3.3: Rewrite the observability paragraph in `README.md`
|
||||
|
||||
`README.md:246` currently reads "**No observability layer, either.**" and points at issue #10. When #10 lands, that paragraph is wrong and it is the single most load-bearing sentence in the CTO's assessment. Rewriting it is part of the work, not follow-up.
|
||||
|
||||
`AGENTS.md:83`: new public API needs a note in `README.md`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Split the documentation site
|
||||
|
||||
Verified before scheduling: `website/` is self-contained. 26 source files, no path escaping the directory, and the `@green-tea/core` mentions inside the `.md` files are example code, not build-time imports.
|
||||
|
||||
The coupling to core is five lines:
|
||||
|
||||
| Location | What |
|
||||
|---|---|
|
||||
| `.github/workflows/ci.yml:62-65` | `npm ci --prefix website`, `npm audit --prefix website`, `npm run docs:build` |
|
||||
| `package.json:100-101` | `docs:dev`, `docs:build` |
|
||||
|
||||
Plus two README references to update: `README.md:254` (the docs link) and `README.md:263` (`npm run docs:dev`).
|
||||
|
||||
**The real work is not the move.** No workflow anywhere in `.github/workflows/` deploys the site. `website/astro.config.mjs:6` points at `green-tea.expressive-tea.io` and the deploy happens by hand today. The new repository is where that pipeline gets built for the first time.
|
||||
|
||||
### Task 4.1: Create the repository and move `website/` with its history
|
||||
|
||||
Preserve commit history for the moved directory rather than landing it as one squashed import.
|
||||
|
||||
### Task 4.2: Build the deploy pipeline
|
||||
|
||||
The thing the docs never had. Build on push to the default branch, deploy to `green-tea.expressive-tea.io`.
|
||||
|
||||
### Task 4.3: Remove the website from core
|
||||
|
||||
Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`. Update `README.md:254` and `README.md:263`.
|
||||
|
||||
### Task 4.4: Guard the seam the split opens
|
||||
|
||||
The split trades CI coupling for drift risk: docs and code can now disagree without anything failing. #18 exists precisely because docs fell behind an API change. Decide what catches that — a link check against the published package, a docs job triggered from core releases, or an explicit accepted risk written down. Do not leave it unstated.
|
||||
|
||||
**Resolved 2026-08-17: accepted risk, stated where the rule is read rather than where it is published.** The first pass put it in both READMEs and stopped there, which satisfies the letter of "do not leave it unstated" and little else — the core README's copy sits in *Docs & development*, a section a user reads and a contributor changing an API does not.
|
||||
|
||||
What governs behaviour is `AGENTS.md:83` and the pre-PR checklist in `CONTRIBUTING.md`, both of which already carried *"New public API needs a note in `README.md`"* — written before the split and never updated for it, so the two documents that a contributor (or an assistant) actually reads mid-change said nothing about the new repository. Both now name it and say why the rule exists, since a rule without its reason is the first one dropped under time pressure.
|
||||
|
||||
**The link check was prototyped and then rejected, on measurement rather than taste.** It had been recommended here as the one worth building; building enough of it to decide showed otherwise.
|
||||
|
||||
- Every symbol the pages import is real: **24 distinct imports from `@green-tea/core` across 25 pages, all present** among the package's 101 exports. No bug for it to find today.
|
||||
- More decisively, **an import check could not have caught #18**. That issue was *"docs still describe `close()` without the timeout"* — the method existed; the **option** was undocumented. Imports are the part that does not drift. Options, option shapes and method signatures are.
|
||||
- Extending it to options and methods was tried and produced **17 findings, all 17 false** — a regex cannot tell a nested `tls: { key, cert }` from a top-level option, `app.example.com` in a CORS example from an `app.*` call, or prose describing Express's `app.use()` from a green-tea API. A check with that signal-to-noise trains people to ignore it, which is worse than not having one.
|
||||
- What would genuinely catch #18's class is **type-checking the code blocks** (twoslash / Expressive Code). That requires the documentation repository to depend on `@green-tea/core` and its examples to be complete and compilable — many are deliberately fragments. It buys the guarantee back by spending exactly the independence this split was for.
|
||||
|
||||
So the accepted risk stands, now as an informed choice rather than a default. A **docs job triggered from core releases** was the other option and remains the weaker one: it fires after the API has already shipped.
|
||||
|
||||
One page is covered by more than a rule: `test/circuit-breaker-recipe.test.ts` executes the recipe published in `guides/circuit-breaker.md`. That is one page of twenty-five, and is not a substitute for the check above.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4.5: Move the JSR gate off the tag — **run this before Task 2.5's code**
|
||||
|
||||
Numbered as an insertion because that is what it is, the same way Task 2.5 was. It is small, and its position is the whole point: **Task 2.5 adds public API** — `Hooks`, `TeardownFn`, `PluginApi.onShutdown` — and exported types are exactly what JSR's slow-types check polices. Writing that surface with no JSR gate on pull requests means learning at release time whether the shape is publishable.
|
||||
|
||||
Verified before writing this, because the first reading was wrong: `release.yml:42` **already** runs `deno publish --dry-run`, before publishing to either registry, and its comment already makes the argument — *"JSR checks things npm never looks at — slow types, module analysis — and learning about them after npm has published leaves the tag half-shipped."* Phase 1 already published to JSR, and a dry run passes today, slow-types check included.
|
||||
|
||||
The gap is not that the gate is missing. It is **when it runs**: only on a version tag. A change that breaks Deno's type-checker or introduces a slow type lands on `main` in silence and surfaces while cutting a release — the moment `release.yml`'s own npm-audit comment identifies as having the least time to judge a fix. The workflow makes that argument for advisories and not for JSR.
|
||||
|
||||
Worth stating plainly: `deno publish --dry-run` type-checks the four entry points with **Deno's** checker and lib, which is not the same pass as `tsc --noEmit -p tsconfig.json`. A second compiler over the same source is a real gate, not a formality — Task 1.1 exists because that second compiler found a hole the first one did not. And JSR serves `src/` directly, so anything it would reject is something a JSR user gets.
|
||||
|
||||
### Task 4.5.1: Run the JSR gate on every push and pull request
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
|
||||
Add `deno publish --dry-run` to the `runtimes` job's Deno leg, which already installs Deno. Measured at **0.68s** against 2.0s for the whole vitest suite — cheap enough that placing it anywhere else is over-thinking.
|
||||
|
||||
Leave `release.yml` alone. The tag-time gate stays: it is the one that protects an immutable JSR version, and a gate that runs twice is not a duplication worth removing.
|
||||
|
||||
### Task 4.5.2: One command for the whole matrix
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Modify: `README.md`
|
||||
|
||||
`npm test` is Node-only, deliberately — it is the fast local loop, 2s, and booting Deno, Bun and workerd into it would tax every run to catch what CI already catches on every push. The `runtimes` job means these suites are not unguarded; what is missing is a way for a contributor to run everything with one command before pushing.
|
||||
|
||||
Add `test:all` — `npm test` plus `test:deno`, `test:bun`, `test:edge`, and the JSR dry run. Say in `README.md` which one is the fast loop and which one is the pre-push check, so the split reads as a decision rather than an oversight.
|
||||
|
||||
### The decorator warning is expected — no task, and no new documentation
|
||||
|
||||
Every `deno publish --dry-run` prints:
|
||||
|
||||
```
|
||||
Warning experimentalDecorators compiler option is deprecated and may be removed at any time
|
||||
```
|
||||
|
||||
Whoever adds this gate to CI will see that warning arrive with it and should not treat it as something the gate found. It is **already documented, and better than a new note would manage**: `README.md:233` (*Why legacy decorators*) and `concepts/the-graph.md:43` in the docs repository both carry the reasoning — parameter decorators are deliberately absent from the TC39 Stage 3 proposal, so `handler(@param('id') id: string)` is only expressible with legacy decorators, and Stage 3 means the replacement is not finalized either.
|
||||
|
||||
An earlier draft of this phase claimed the framework "depends on `emitDecoratorMetadata`". That is **wrong**, and both documents already say so: argument positions are recorded explicitly, and `grep -rn 'design:type\|design:paramtypes' src/` returns nothing — the flag is set in `tsconfig.json` and `deno.json`, but no `design:*` reflection is read anywhere. Legacy parameter decorators are the only legacy surface this project actually depends on.
|
||||
|
||||
Do not turn the warning into an error to force the issue: that breaks releases on someone else's schedule.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Close #13 as documentation
|
||||
|
||||
### Task 5.1: Write the circuit-breaker recipe
|
||||
|
||||
**Files:**
|
||||
- Create: a guide page in the docs repository
|
||||
|
||||
The issue was opened to decide placement, not to commit to a core implementation, and it answers itself: core adding resilience policy would contradict the one-runtime-dependency rule. A circuit breaker fits a step — it needs whatever provides the client, it produces a guarded caller, and the graph already sequences it correctly.
|
||||
|
||||
Write it as a worked example, then close #13 pointing at the page. First real content in the new repository, which is also a live test of the deploy pipeline from Task 4.2.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: The stability contract
|
||||
|
||||
### Task 6.1: A stability paragraph in `Honest scope`
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
|
||||
Not a roadmap, and not the API freeze. A statement of which areas are volatile *today* — present state, no dates, no delivery commitment. This is spare-time work by one person and a roadmap it cannot keep would cost more trust than it earns.
|
||||
|
||||
`## Honest scope` (`README.md:240`) already carries exactly this voice: mesh is alpha, there is no observability layer, runtimes differ in what they can offer. The stability tiers belong in that section, in that register, as one paragraph.
|
||||
|
||||
Roughly the split the Trust Release report proposes in §8 — graph semantics, providers, steps and controllers as the stable candidates; decorator syntax, CLI and plugin APIs as beta; mesh and distributed capabilities as experimental. Verify each claim against the code before writing it down; a stability tier asserted and then broken is worse than none.
|
||||
|
||||
`README.md:266-276` keeps its `**next**` line unchanged. API freeze stays declared there and gets planned separately, near the RC.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
Per `AGENTS.md:28`, run before proposing any task as finished:
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run typecheck && npm test
|
||||
```
|
||||
|
||||
And from Phase 1 onward the runtime suites are no longer optional, because CI runs them:
|
||||
|
||||
```bash
|
||||
npm run test:deno && npm run test:bun && npm run test:edge
|
||||
```
|
||||
|
||||
Conventional Commits focused on the *why*, every commit signed off (`git commit -s`), no AI co-authoring attribution.
|
||||
@@ -0,0 +1,211 @@
|
||||
# Shutdown teardown — Design
|
||||
|
||||
**Task:** 2.5 in the [trust-release plan](./2026-08-16-trust-release-plan.md) · Trust Release §14, CTO P0-4 · **Status:** reviewed, D1–D8 settled · **Constraint:** no new runtime dependency
|
||||
|
||||
---
|
||||
|
||||
## The diagnosis
|
||||
|
||||
An application closing a database connection today writes `process.on('SIGTERM', …)` by hand, because the framework offers nowhere to put that. `closeApp` (`src/app/index.ts:1009`) closes mesh links, streams and the HTTP server, and knows nothing about plugins or providers. `LifecycleEvent` (`src/bus.ts:2`) has no shutdown event at all — a plugin cannot even *observe* that the app is closing, let alone act on it.
|
||||
|
||||
The framework owns the plumbing everywhere else. This is the hole.
|
||||
|
||||
### Why the existing `Bus` cannot carry it
|
||||
|
||||
`Bus.on` takes a synchronous listener (`src/bus.ts:62`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:85`). Both are deliberate: observers must never break the pipeline. A plugin closing a database connection needs shutdown to *wait for it*, and needs its failure to be visible.
|
||||
|
||||
The observability design already settled this rather than leaving it open — `D2` of [2026-08-16-observability-design.md](./2026-08-16-observability-design.md):
|
||||
|
||||
> **This is exactly why shutdown teardown does not belong here.** A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
|
||||
|
||||
Conceptually this is still an event — *"the app is closing, do you have anything to do first?"* — and callers may reasonably think of registering as subscribing. Mechanically it is a separate await-aware registry, because bending `Bus` to do both would cost the guarantee that makes `Bus` safe.
|
||||
|
||||
### What "isolation is structural" actually protects
|
||||
|
||||
`src/plugin.ts:26` reads *"Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural."* That sentence is load-bearing and it is easy to over-read, so this design states what it does and does not cover — verified against the code, because the answer surprised both people in the conversation that produced this document.
|
||||
|
||||
**Enforced today:**
|
||||
|
||||
- A plugin receives only `bus.on` and `scope.add` — no `emit`, so it cannot fabricate lifecycle events, and no reach into the registry.
|
||||
- `setRunner` (`src/app/index.ts:320`) throws on duplicate names, so a plugin cannot silently replace an existing provider or step.
|
||||
- Plugin nodes carry `origin: 'plugin'` and stay attributable in the graph.
|
||||
|
||||
**Not enforced today:**
|
||||
|
||||
- `runSteps` passes the live context object to every step and merges its output with `Object.assign(context, output)` (`src/pipeline.ts:73-74`). No collision check. A plugin's step can mutate the context directly and can overwrite any key another step provided.
|
||||
- `mountPlugins` (`src/app/index.ts:161`) runs *before* `provideBuiltins` (`:162`), and `provideBuiltins` skips anything already registered — so a plugin registering a node named `logger` or `rooms` replaces the builtin.
|
||||
|
||||
So the guarantee is about the **registration surface**, not about the **runtime context**. Teardown touches neither: it adds a third thing a plugin may register, and never sees a request context. The context-integrity question is real but pre-existing and out of scope here — it is recorded at the end so it is not lost.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1 — A teardown registry, not a `Bus` event
|
||||
|
||||
One list of callbacks, owned by the app, awaited on close. Not a `LifecycleEvent`, for the reason `D2` of the observability design already gives.
|
||||
|
||||
The registry is the entire mechanism. Everything below is a door into it.
|
||||
|
||||
### D2 — Three doors, one registry: one order, one failure policy
|
||||
|
||||
| Door | Who uses it | Shape |
|
||||
|---|---|---|
|
||||
| `hooks: [...]` in `createApp` | an application that wants lifecycle participation and nothing else | `onShutdown()` |
|
||||
| `PluginApi.onShutdown` | a plugin that also extends the graph | `onShutdown()` |
|
||||
| `dispose()` on a `@Provider` class | the provider that opened the resource | optional method |
|
||||
|
||||
Three entry points, **one** registry, **one** order, **one** failure policy. If they ever acquire separate ordering relative to each other, this design has failed and two mechanisms exist again.
|
||||
|
||||
The doors differ by intent, not by semantics. Today the only way into the lifecycle is to write a plugin, and a plugin means *"I want to extend the graph"* — someone who only wants to close a connection is forced to declare an extension they do not want.
|
||||
|
||||
### D3 — `PluginApi` gains a property; the `Plugin` signature does not change
|
||||
|
||||
`Plugin = (api: PluginApi) => void` is untouched. `onShutdown` joins `bus` and `scope` on the object a plugin already receives. Every existing plugin ignores it and behaves identically.
|
||||
|
||||
This is why the hooks framing is better than widening the plugin contract directly: it removes the only break the earlier sketch had. See "What breaks" below — the answer is now *nothing at runtime*.
|
||||
|
||||
### D4 — Teardown callbacks receive no arguments
|
||||
|
||||
```ts
|
||||
type TeardownFn = () => void | Promise<void>;
|
||||
```
|
||||
|
||||
State lives where the resource was created, and the closure already holds it:
|
||||
|
||||
```ts
|
||||
class MyPlugin {
|
||||
#db = new Pool();
|
||||
mount(api: PluginApi) {
|
||||
api.onShutdown(() => this.#db.end()); // the closure already has it
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A provider's `dispose()` is the same picture — the instance holds its own connection.
|
||||
|
||||
**Nothing needs to cross scopes**, which is what makes a container reference, an app reference, or any transport mechanism unnecessary here. A bus solves *"tell someone I do not know"*. Teardown is *"run this thing I registered"*. Handing a hook a resolver would make the container reachable from a hook and would be a genuine widening — declined.
|
||||
|
||||
If an argument is ever needed, adding one to a callback that receives none is additive. The reverse is not.
|
||||
|
||||
### D5 — Order is the reverse of boot
|
||||
|
||||
Providers boot in topological order (`bootProviders`, `src/app/index.ts:664`), so they tear down in reverse: if `cache` needs `db`, `cache` closes first. Registration order within the same tier is preserved.
|
||||
|
||||
Sequential, not parallel. Reverse-topological order only means something if it is respected, and parallel teardown discards it.
|
||||
|
||||
### D6 — A failing teardown is logged and shutdown continues
|
||||
|
||||
The failure goes to the injectable `Logger` and `close()` still resolves. One plugin's broken teardown must not strand the remaining ones or hang the process.
|
||||
|
||||
This mirrors `Bus`'s philosophy — a subscriber cannot break the system — but with the visibility `Bus` lacks. `Bus` swallows silently because no logger existed when it was written; one exists now.
|
||||
|
||||
The counter-argument was weighed and rejected: a `close()` that reports success after losing data is arguably worse than one that fails loudly. It loses because the alternative is worse in the common case — a process that will not exit is a worse operational failure than one that exited with a warning in the log, and the warning is not silent.
|
||||
|
||||
### D7 — Triggered from each runtime's real close
|
||||
|
||||
`app.close()` returns at its `if (!server)` guard on Deno, Bun and the edge (`src/app/index.ts:1026`). Hanging teardown off `app.close()` would make behaviour differ per runtime, which the multi-runtime constraint forbids.
|
||||
|
||||
| Runtime | Entry point |
|
||||
|---|---|
|
||||
| Node | `app.close()` → `closeApp` |
|
||||
| Deno | `serveDeno(app).close()` → `closeWithDeadline` |
|
||||
| Bun | `serveBun(app).close()` → `closeWithDeadline` |
|
||||
| edge (workerd) | **none — no shutdown exists** |
|
||||
|
||||
`serveDeno` and `serveBun` already receive the app, so their `close()` can run its teardown without the user calling two things. `closeWithDeadline` (`src/http/shutdown.ts`) is already shared by both *"so the two adapters cannot drift into different meanings of the same `timeoutMs`"* — the same argument applies here, and it is why teardown belongs in that shared function rather than in each adapter.
|
||||
|
||||
Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**: workerd never closes, so there is nothing to intercept. A plugin that depends on teardown for correctness is broken there. This is a runtime capability difference and belongs in the `runtimes.md` table beside `@Html` file mode and mesh, not in a footnote.
|
||||
|
||||
### D8 — Teardown shares the close budget, and `close()` never exceeds `timeoutMs`
|
||||
|
||||
`timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for.
|
||||
|
||||
- Drain runs first. Teardown runs after, within the same budget.
|
||||
- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one.
|
||||
- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
|
||||
- `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped.
|
||||
|
||||
An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement.
|
||||
|
||||
Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run.
|
||||
|
||||
---
|
||||
|
||||
## The contract
|
||||
|
||||
```ts
|
||||
/** A teardown callback. Receives nothing: state lives in the closure that registered it. */
|
||||
export type TeardownFn = () => void | Promise<void>;
|
||||
|
||||
/** Lifecycle participation without extending the graph. Methods are optional so later
|
||||
* stages (onBoot, onReady) can join without a breaking change. */
|
||||
export interface Hooks {
|
||||
onShutdown?: TeardownFn;
|
||||
}
|
||||
|
||||
/** Unchanged except for the third capability. `Plugin` keeps its signature. */
|
||||
export interface PluginApi {
|
||||
bus: { on: Bus['on'] };
|
||||
scope: ScopeApi;
|
||||
onShutdown(fn: TeardownFn): void;
|
||||
}
|
||||
|
||||
createApp({
|
||||
modules: [...],
|
||||
plugins: [...],
|
||||
hooks: [...], // new
|
||||
shutdownTimeoutMs: 10_000, // existing
|
||||
teardownTimeoutMs: 2_000, // new, optional; <= shutdownTimeoutMs
|
||||
});
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() { /* ... */ }
|
||||
async dispose() { /* optional; called if present */ }
|
||||
}
|
||||
```
|
||||
|
||||
### What this costs internally
|
||||
|
||||
`collectProviders` (`src/app/index.ts:345`) constructs each provider with `new ProviderClass()` and captures the instance in a closure. **The instance is never stored anywhere reachable**, and `Container.bindings` is private with no iteration, so there is no handle to call `dispose()` on today.
|
||||
|
||||
Keeping provider instances requires a new field on `Registry`. That is internal, not public API, and it is the part nobody sees coming from reading "add `onShutdown` to `PluginApi`".
|
||||
|
||||
### What breaks
|
||||
|
||||
**At runtime: nothing.** `Plugin`'s signature is unchanged, `Hooks` methods are optional, and `dispose()` is called only if present.
|
||||
|
||||
**At compile time: nothing either**, given D3. Widening `PluginApi` would have broken anyone constructing one as a literal — typically a test mock — but `onShutdown` is a required property on an object the framework builds and hands out, never one a user implements. Should that turn out to be wrong for some consumer, it goes in the CHANGELOG with the reason: making it optional would force every plugin to check for it and would turn a capability into a conditional forever.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope, deliberately
|
||||
|
||||
- **`onBoot` / `onReady`.** `Hooks` is shaped as an object of optional methods so they can be added without a breaking change, but only `onShutdown` ships. The shape accommodates them; this design does not build them.
|
||||
- **Request-scope cleanup.** Request values are recomputed per resolve (`src/container.ts`) and are garbage, not resources. Only app-scope teardown is in scope.
|
||||
- **Edge teardown.** Not possible. Documented, not worked around.
|
||||
- **A context argument for teardown callbacks.** D4. Additive later if a real case appears.
|
||||
- **Context integrity.** A plugin's step can overwrite context keys and can replace the `logger` and `rooms` builtins. Real, pre-existing, unrelated to teardown, and recorded here only so the finding is not lost with this conversation.
|
||||
|
||||
---
|
||||
|
||||
## Verification this design must survive
|
||||
|
||||
1. A plugin registering `onShutdown` has it awaited before `close()` resolves — on Node, Deno and Bun, asserted per runtime rather than once.
|
||||
2. A provider with `dispose()` has it called; one without is skipped.
|
||||
3. Reverse-topological order: `cache` needing `db` tears down first.
|
||||
4. A throwing teardown is logged and the remaining ones still run; `close()` resolves.
|
||||
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
|
||||
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
|
||||
8. `close()` on an app with no teardown registered costs nothing measurable — this is not a request path, but it is still on the shutdown path of every app that uses none of it.
|
||||
|
||||
## Documentation this design changes
|
||||
|
||||
All of these now live in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs):
|
||||
|
||||
- `guides/plugins.md:7` — states plugins have exactly two capabilities. Becomes three, and the isolation wording needs the precision from the diagnosis above rather than a restatement.
|
||||
- `guides/runtimes.md:44` — the shutdown table gains teardown, and edge gains its exception.
|
||||
- `guides/dependency-injection.md:56` — describes what `close()` does; it now does one more thing.
|
||||
- `README.md` — new public API, per `AGENTS.md:83`.
|
||||
@@ -0,0 +1,141 @@
|
||||
# Shutdown teardown — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Design:** [2026-08-17-shutdown-teardown-design.md](./2026-08-17-shutdown-teardown-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
|
||||
|
||||
**Goal:** Give plugins, providers and applications somewhere to put teardown, so closing a database connection stops meaning `process.on('SIGTERM', …)` by hand. Closes Task 2.5 of the [trust-release plan](./2026-08-16-trust-release-plan.md); Trust Release §14, CTO P0-4.
|
||||
|
||||
**Architecture:** A new `src/lifecycle.ts` holds the registry and nothing else. `src/plugin.ts` and `src/app/index.ts` gain doors into it; `src/app/index.ts` (`closeApp`) and `src/http/shutdown.ts` (`closeWithDeadline`) gain the call that drains it. No new runtime dependency — `reflect-metadata` stays the only one.
|
||||
|
||||
**The thing to keep hold of:** three doors, one registry, one order, one failure policy. Any task that gives a door its own ordering or its own error handling has broken D2, whatever the tests say.
|
||||
|
||||
---
|
||||
|
||||
## Order
|
||||
|
||||
Tasks 1–3 build the mechanism and the doors; nothing observable changes until Task 4 wires it into `close()`. Task 5 is the runtime parity that D7 demands and is the one most likely to surface a surprise, so it does not go last. Documentation is Task 7 because it should describe the finished API rather than be rewritten twice.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: The registry
|
||||
|
||||
**Files:**
|
||||
- Create: `src/lifecycle.ts`
|
||||
- Create: `test/lifecycle.test.ts`
|
||||
|
||||
The whole mechanism, with no knowledge of plugins, providers, apps or HTTP.
|
||||
|
||||
```ts
|
||||
export type TeardownFn = () => void | Promise<void>;
|
||||
```
|
||||
|
||||
It needs: register a callback, and run everything registered — sequentially, in reverse registration order (D5), awaiting each, catching each (D6), never throwing. A failing callback is reported through the injectable `Logger` and the next one still runs.
|
||||
|
||||
Keep the timeout **out** of here. Bounding is the caller's job, and it is already solved twice over by `closeApp` and `closeWithDeadline`; a third implementation is how the three drift into different meanings of the same number.
|
||||
|
||||
Tests: order is reverse of registration; a throwing callback is logged and does not stop the rest; a rejecting async callback is treated the same; an empty registry resolves; running twice does not re-run callbacks (`close()` is called twice by more real applications than anyone expects).
|
||||
|
||||
### Task 2: The plugin and hook doors
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugin.ts`
|
||||
- Modify: `src/app/index.ts` — `mountPlugins`, `createApp` options
|
||||
- Modify: `src/app/types.ts` — `Hooks` on the public options
|
||||
- Modify: `test/plugin.test.ts`
|
||||
|
||||
`PluginApi` gains `onShutdown(fn: TeardownFn): void`, bound to the app's registry. `mountPlugin`'s comment at `src/plugin.ts:26` currently says a plugin gets `on()` and `add()` and nothing else; it now gets three things, and the comment says which and why — the isolation wording in the design's diagnosis is the precise version, not "isolation is gone".
|
||||
|
||||
`createApp({ hooks })` takes `Hooks[]`, an object of optional methods so `onBoot`/`onReady` can join later without a breaking change. Only `onShutdown` exists now.
|
||||
|
||||
Tests: a plugin registering `onShutdown` lands in the registry; a plugin that never calls it behaves exactly as before (D3 — this is the no-break guarantee, so it gets an explicit test rather than an assumption); hooks and plugins interleave in one order rather than running as two groups.
|
||||
|
||||
### Task 3: Provider `dispose()`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/index.ts` — `collectProviders`, `Registry`
|
||||
- Modify: `test/app.test.ts`
|
||||
|
||||
`collectProviders` (`src/app/index.ts:345`) builds each provider with `new ProviderClass()` and captures the instance in a closure where nothing can reach it. Keep the instances on `Registry` so a `dispose()` can be called.
|
||||
|
||||
Registration order must follow boot order, not declaration order, so that D5's reverse-topological teardown falls out of the registry's reverse-registration rule rather than needing a second sort. That means registering a provider's `dispose()` as it boots in `bootProviders` (`:664`), not when it is collected.
|
||||
|
||||
A provider that failed to boot must not have `dispose()` called — it never provided anything. Optional providers that degraded (`degradedProviders`) are exactly this case and already tracked.
|
||||
|
||||
Tests: `dispose()` is called; a provider without one is skipped; `cache` needing `db` tears down first; a provider that failed to boot is not disposed.
|
||||
|
||||
### Task 4: Drain the registry on close — Node
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/index.ts` — `closeApp`
|
||||
- Modify: `test/app.test.ts`
|
||||
|
||||
Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining.
|
||||
|
||||
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
|
||||
|
||||
`closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering.
|
||||
|
||||
Tests: a registered teardown is awaited before `close()` resolves; a hanging teardown does not let `close()` exceed `timeoutMs`; a slow drain plus a set `teardownTimeoutMs` still leaves teardown its reserved slice; `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
|
||||
### Task 5: Runtime parity — Deno and Bun
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/shutdown.ts` — `closeWithDeadline`
|
||||
- Modify: `src/deno.ts`, `src/bun.ts`
|
||||
- Modify: `test/deno/*`, `test/bun/*`
|
||||
|
||||
`app.close()` returns at its `if (!server)` guard on Deno and Bun (`src/app/index.ts:1026`), so teardown cannot hang off it without behaviour differing per runtime — which the multi-runtime constraint forbids (D7).
|
||||
|
||||
`serveDeno(app)` and `serveBun(app)` already hold the app, so their `close()` runs the teardown and the user calls one thing, not two. It goes in `closeWithDeadline` rather than in each adapter, for the reason that function already exists: so the two cannot drift into different meanings of the same `timeoutMs`.
|
||||
|
||||
Deno cannot escalate from graceful to forced — its deadline bounds how long `close()` waits, not when connections die. That asymmetry already exists and this must not make it worse.
|
||||
|
||||
These suites are **not** in `npm test`. Run `npm run test:deno` and `npm run test:bun` explicitly, and do not report this task done on the strength of vitest passing.
|
||||
|
||||
Tests, per runtime rather than once: a teardown registered on a Deno/Bun app is awaited by that server's `close()`.
|
||||
|
||||
### Task 6: Edge — document the hole, do not paper over it
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/edge.ts` — doc comment only
|
||||
|
||||
workerd never closes, so there is nothing to intercept and no design fixes it. A plugin depending on teardown for correctness is broken there.
|
||||
|
||||
No shim, no fake `close()`, no best-effort call on an unload event that does not exist. The only change is a doc comment stating it, so someone reading `edgeHandler` learns it there rather than in production. The user-facing half is Task 7.
|
||||
|
||||
### Task 7: Documentation
|
||||
|
||||
**Files:** all in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)
|
||||
- Modify: `src/content/docs/guides/plugins.md` — line 7 says plugins have exactly two capabilities; it is three now, and the isolation sentence needs the design's precision rather than a restatement
|
||||
- Modify: `src/content/docs/guides/runtimes.md` — the shutdown table gains teardown, and edge gains its row
|
||||
- Modify: `src/content/docs/guides/dependency-injection.md` — line 56 describes what `close()` does
|
||||
- Modify: `README.md` in core — new public API, per `AGENTS.md:83`
|
||||
- Modify: `CHANGELOG.md` in core
|
||||
|
||||
Two repositories, one change. This is the first real test of the seam Phase 4 opened, and nothing fails if it is skipped — which is the point of doing it in the same session rather than leaving it to a follow-up.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope
|
||||
|
||||
- `onBoot` / `onReady`. `Hooks` is shaped to accommodate them; this plan does not build them.
|
||||
- Request-scope cleanup. Request values are recomputed per resolve and are garbage, not resources.
|
||||
- Edge teardown. Not possible.
|
||||
- A context argument for teardown callbacks (D4). Additive later if a real case appears.
|
||||
- Context integrity — a plugin's step can overwrite context keys and replace the `logger` and `rooms` builtins. Real, pre-existing, and recorded in the design's out-of-scope section so it is not lost.
|
||||
|
||||
## Verification
|
||||
|
||||
The design's list, restated as the gate for calling this done:
|
||||
|
||||
1. A plugin's `onShutdown` is awaited before `close()` resolves — asserted on Node, Deno and Bun separately.
|
||||
2. A provider with `dispose()` has it called; one without is skipped; one that failed to boot is not disposed.
|
||||
3. Reverse-topological order: `cache` needing `db` tears down first.
|
||||
4. A throwing teardown is logged, the rest still run, `close()` resolves.
|
||||
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
|
||||
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
|
||||
8. `close()` on an app with no teardown registered costs nothing measurable.
|
||||
|
||||
Plus the gates every change here passes: `npm run lint`, `npm run complexity:check`, `npm run typecheck`, `npm test`, and — because Task 5 exists — `npm run test:deno`, `npm run test:bun`, `npm run test:edge`.
|
||||
@@ -0,0 +1,82 @@
|
||||
# A teapot that may be absent, declared per teapot
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
|
||||
**Mesh stays alpha.**
|
||||
|
||||
## The decision
|
||||
|
||||
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
|
||||
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
|
||||
away is a degraded checkout; an authorization provider being away is not a degraded anything.
|
||||
|
||||
```ts
|
||||
mesh: {
|
||||
teapots: [
|
||||
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
|
||||
{ url: authUrl, secret }, // 'fail' — the default
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Why `expects` is required for `'degrade'`, and not inferred
|
||||
|
||||
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
|
||||
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
|
||||
validation fails the boot anyway — degrading would fail identically, just later.
|
||||
|
||||
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
|
||||
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
|
||||
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
|
||||
loudly.
|
||||
|
||||
It also pushes the developer to state what a service depends on, which is the same discipline the
|
||||
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
|
||||
`expects`, naming the teapot.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
|
||||
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
|
||||
and throws `503`, naming the token and the teapot it belongs to.
|
||||
|
||||
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
|
||||
simply do not exist locally, because a route needs a method and a pattern we were never told. A
|
||||
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
|
||||
silent.
|
||||
|
||||
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
|
||||
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
|
||||
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
|
||||
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
|
||||
logged and emitted.
|
||||
|
||||
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
|
||||
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
|
||||
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
|
||||
|
||||
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
|
||||
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
|
||||
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
|
||||
instead of a boot manifest.
|
||||
|
||||
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
|
||||
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
|
||||
wrong, not a reason to write a second one.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
|
||||
`expects`.
|
||||
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
|
||||
3. `degraded()` reporting per D3, plus the warn and the event.
|
||||
4. Background attempt loop per D4, and adoption per D5/D6.
|
||||
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
|
||||
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
|
||||
refused, and `'degrade'` without `expects` fails at `createApp`.
|
||||
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
|
||||
|
||||
## Size
|
||||
|
||||
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
|
||||
three runtimes. Not a follow-up to squeeze into another change.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Mesh reconnection, with a refusing manifest policy
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
|
||||
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
|
||||
unusable in production; it does not move the label, because the label is a statement about how much
|
||||
we know, and we will know more once this runs somewhere real.
|
||||
|
||||
## The problem
|
||||
|
||||
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
|
||||
serially and throwing on any failure (`src/app/index.ts:631`):
|
||||
|
||||
- a teapot down at boot → the teacup does not start;
|
||||
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
|
||||
|
||||
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
|
||||
load-bearing. That is a worse operational property than any gap currently written in the docs.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
|
||||
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
|
||||
words must not be used interchangeably in code, CHANGELOG or docs.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
|
||||
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
|
||||
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
|
||||
`connectLink` becomes "establish, then keep established".
|
||||
|
||||
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
|
||||
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
|
||||
configured" with "this dependency is temporarily away".
|
||||
|
||||
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
|
||||
heartbeat, so reconnection never holds a process open on its own.
|
||||
|
||||
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
|
||||
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
|
||||
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
|
||||
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
|
||||
|
||||
Rationale: the graph was validated at boot against the old manifest and is already running. A token
|
||||
that vanished cannot be validated away after the fact, and serving requests against a manifest that
|
||||
no longer backs the graph is how you get a 500 that looks like application code.
|
||||
|
||||
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
|
||||
not spliced in. Documented, not silent.
|
||||
|
||||
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
|
||||
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
|
||||
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
|
||||
|
||||
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
|
||||
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
|
||||
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
|
||||
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
|
||||
place to be breaking.
|
||||
|
||||
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
|
||||
provider is resolved once at boot and frozen into the container as `() => value`
|
||||
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
|
||||
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
|
||||
call on the reconnect path, where its failure has nowhere to go. This closes the documented
|
||||
"app-scope export survives its teapot with a stale value" gap.
|
||||
|
||||
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
|
||||
inline in the reconnect handler — that function is what reconciliation will reuse.
|
||||
|
||||
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
|
||||
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
|
||||
cannot exit.
|
||||
|
||||
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
|
||||
not a wait for `timeoutMs`.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
|
||||
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
|
||||
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
|
||||
`mesh:connect` on success (existing events; no new bus contract in alpha).
|
||||
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
|
||||
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
|
||||
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
|
||||
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
|
||||
Reconnect defaults **on**. Validate at boot like the other mesh options.
|
||||
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
|
||||
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
|
||||
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
|
||||
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
|
||||
where a swappable socket can break.
|
||||
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
|
||||
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
|
||||
a defect, not a feature.
|
||||
|
||||
## Not in this plan
|
||||
|
||||
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
|
||||
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
|
||||
@@ -23,4 +23,12 @@ export default tseslint.config(
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Nothing in core writes to console directly — every diagnostic goes through the injectable
|
||||
// `Logger`, or an application cannot redirect it. This is the rule form of a check that was
|
||||
// otherwise a `grep` somebody has to remember to run.
|
||||
files: ['src/**/*.ts'],
|
||||
ignores: ['src/logger.ts'], // the default logger *is* the console sink; that is its whole job
|
||||
rules: { 'no-console': 'error' },
|
||||
},
|
||||
);
|
||||
Generated
+3
-3
@@ -5670,9 +5670,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
||||
+5
-5
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"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",
|
||||
"author": "green-tea contributors <projects@expressive-tea.io>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/Expressive-Tea/green-tea/issues"
|
||||
"url": "https://github.com/Expressive-Tea/green-tea/issues",
|
||||
"email": "projects@expressive-tea.io"
|
||||
},
|
||||
"homepage": "https://green-tea.expressive-tea.io/docs/",
|
||||
"keywords": [
|
||||
@@ -90,14 +91,13 @@
|
||||
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
|
||||
"test:bun": "bun test test/bun/",
|
||||
"test:edge": "tsx test/edge/run.ts",
|
||||
"test:all": "npm test && npm run test:deno && npm run test:bun && npm run test:edge && deno publish --dry-run --allow-dirty",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
||||
"lint": "eslint src",
|
||||
"lint:fix": "eslint src --fix",
|
||||
"format": "prettier --write \"src/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\"",
|
||||
"docs:dev": "npm --prefix website run dev",
|
||||
"docs:build": "npm --prefix website run build",
|
||||
"complexity": "ccts src",
|
||||
"complexity:check": "node scripts/check-complexity.mjs",
|
||||
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
||||
|
||||
+420
-39
@@ -1,5 +1,6 @@
|
||||
import type http from 'http';
|
||||
import { Bus } from '../bus';
|
||||
import { createDefaultLogger, logRequests, type Logger } from '../logger';
|
||||
import { Container } from '../container';
|
||||
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||
@@ -11,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,
|
||||
@@ -26,7 +29,7 @@ import {
|
||||
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
||||
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||
import { connectLink, type Link } from '../mesh/link';
|
||||
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
|
||||
import { Rooms } from '../rooms';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import { buildRemote } from '../mesh/teacup';
|
||||
@@ -47,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[];
|
||||
@@ -85,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;
|
||||
@@ -103,6 +121,43 @@ export function createApp(opts: {
|
||||
viewEngine?: (source: string, data: unknown) => string;
|
||||
/** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */
|
||||
static?: boolean | string;
|
||||
/**
|
||||
* How long `close()` gives in-flight work before forcing remaining connections shut, in ms
|
||||
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
|
||||
* reached from a signal handler, a test helper or a shutdown hook you do not own, which is
|
||||
* where passing it per call is not an option.
|
||||
*/
|
||||
shutdownTimeoutMs?: number;
|
||||
/**
|
||||
* Milliseconds reserved out of the shutdown budget for teardown, in ms (default: none reserved).
|
||||
*
|
||||
* Teardown runs after the drain and inside the same `timeoutMs`, so `close()` never takes longer
|
||||
* than the caller asked for. Left unset, the drain may use the whole budget and teardown gets
|
||||
* whatever remains — possibly nothing. Set it when a connection *must* get its chance to close:
|
||||
* the drain is then bounded to `timeoutMs - teardownTimeoutMs` and this slice is guaranteed.
|
||||
*
|
||||
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
|
||||
*/
|
||||
teardownTimeoutMs?: number;
|
||||
/**
|
||||
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
|
||||
*
|
||||
* Registered here rather than declared as a provider, and the ordering is why: provider boot
|
||||
* events and the failures they report happen *while* the graph resolves, so a provider cannot
|
||||
* report its own boot failing, and shutdown warnings happen after the graph is gone. The logger
|
||||
* has to outlive the graph on both ends. It is also reachable from a step or handler as
|
||||
* `@needs('logger')` — one object, two access paths.
|
||||
*/
|
||||
logger?: Logger;
|
||||
/**
|
||||
* Log one line per completed request, and one per failed one (default: off).
|
||||
*
|
||||
* Off by default because a framework that writes to stdout without being asked is a framework
|
||||
* you have to configure before you can use it. On, it is a subscriber to the lifecycle stream
|
||||
* like any other consumer — `logRequests(app.bus, app.logger)` does the same thing by hand and
|
||||
* hands back an unsubscribe, so nothing here is reachable only through this flag.
|
||||
*/
|
||||
logRequests?: boolean;
|
||||
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
|
||||
experimental?: boolean;
|
||||
/**
|
||||
@@ -120,6 +175,8 @@ export function createApp(opts: {
|
||||
}
|
||||
|
||||
const bus = new Bus();
|
||||
const logger = opts.logger ?? createDefaultLogger();
|
||||
if (opts.logRequests) logRequests(bus, logger);
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
const streams = new Set<() => void>();
|
||||
@@ -129,8 +186,9 @@ export function createApp(opts: {
|
||||
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
|
||||
const registry = collectModules(opts.modules, viewsCtx);
|
||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||
mountPlugins(opts.plugins, bus, registry);
|
||||
provideBuiltins(registry);
|
||||
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.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
@@ -143,7 +201,7 @@ export function createApp(opts: {
|
||||
const meshLinks: Link[] = [];
|
||||
|
||||
const finalize = (): void => {
|
||||
({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth));
|
||||
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth));
|
||||
booted = true;
|
||||
};
|
||||
|
||||
@@ -159,7 +217,7 @@ export function createApp(opts: {
|
||||
// can only be built here, after finalize(), and never at construction time.
|
||||
const prepareGraph = async (): Promise<void> => {
|
||||
if (opts.mesh && !booted) {
|
||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
|
||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
|
||||
remoteRoutes = spliced.remoteRoutes;
|
||||
meshLinks.push(...spliced.meshLinks);
|
||||
finalize();
|
||||
@@ -207,7 +265,7 @@ export function createApp(opts: {
|
||||
registry,
|
||||
opts.overrides,
|
||||
() => orderedProviders,
|
||||
{ runners, container, providerMeta, bus },
|
||||
{ runners, container, providerMeta, providerInstances: registry.providerInstances, teardown, bus, logger },
|
||||
degradedProviders,
|
||||
ready,
|
||||
);
|
||||
@@ -215,6 +273,7 @@ export function createApp(opts: {
|
||||
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
|
||||
|
||||
const fetchOpts: HttpOptions = {
|
||||
bus,
|
||||
limits: opts.limits,
|
||||
tls: opts.tls,
|
||||
trustProxy: opts.trustProxy,
|
||||
@@ -245,6 +304,7 @@ export function createApp(opts: {
|
||||
const wsRoutes = buildWsRoutes(routePlans, deps);
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
|
||||
bus,
|
||||
limits: opts.limits,
|
||||
streams,
|
||||
tls: opts.tls,
|
||||
@@ -260,19 +320,8 @@ export function createApp(opts: {
|
||||
return server;
|
||||
};
|
||||
|
||||
const close = (): Promise<void> =>
|
||||
new Promise<void>((resolve) => {
|
||||
// before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen()
|
||||
// never runs) has links but no server, and would otherwise leak every teapot connection.
|
||||
// Closing a link rejects its in-flight RPCs via the socket's abort.
|
||||
closeLinks(meshLinks);
|
||||
|
||||
if (!server) return resolve();
|
||||
|
||||
server.close(() => resolve()); // waits for in-flight buffered to drain
|
||||
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
|
||||
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||
});
|
||||
const close = (options: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs);
|
||||
|
||||
return {
|
||||
listen,
|
||||
@@ -288,6 +337,7 @@ export function createApp(opts: {
|
||||
openapi,
|
||||
degraded: () => [...degradedProviders],
|
||||
bus,
|
||||
logger,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -306,6 +356,7 @@ function emptyRegistry(): Registry {
|
||||
stepNodes: [],
|
||||
runners,
|
||||
providerMeta: new Map(),
|
||||
providerInstances: new Map(),
|
||||
routePlans: [],
|
||||
exportedProviders: [],
|
||||
exportedSteps: [],
|
||||
@@ -322,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));
|
||||
}
|
||||
}
|
||||
@@ -438,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' };
|
||||
@@ -454,7 +534,17 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
|
||||
}
|
||||
|
||||
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
||||
function provideBuiltins(registry: Registry): void {
|
||||
function provideBuiltins(registry: Registry, logger: Logger): void {
|
||||
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
|
||||
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
|
||||
// same object createApp holds, not a second one — core cannot depend on the graph for something
|
||||
// it must use while the graph is still resolving.
|
||||
if (!registry.runners.has('logger')) {
|
||||
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
|
||||
registry.providerMeta.set('logger', { optional: false });
|
||||
registry.setRunner('logger', () => ({ logger }));
|
||||
}
|
||||
|
||||
if (registry.runners.has('rooms')) return;
|
||||
const roomsInstance = new Rooms();
|
||||
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||
@@ -473,6 +563,7 @@ const DEEP_GRAPH_WARN = 20;
|
||||
*/
|
||||
function finalizeGraph(
|
||||
registry: Registry,
|
||||
logger: Logger,
|
||||
warnDepth: number | false = DEEP_GRAPH_WARN,
|
||||
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
||||
const { providerNodes, stepNodes, routePlans } = registry;
|
||||
@@ -492,10 +583,11 @@ function finalizeGraph(
|
||||
const depth = closure.filter((node) => stepNodes.includes(node)).length;
|
||||
|
||||
if (warnDepth !== false && depth > warnDepth) {
|
||||
console.warn(
|
||||
`[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
|
||||
logger.warn(
|
||||
`${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
|
||||
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
|
||||
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
|
||||
{ route: plan.pattern, method: plan.method, depth, threshold: warnDepth },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -523,11 +615,102 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep trying to reach a teapot until `bootTimeoutMs` passes, then give up and fail the boot.
|
||||
*
|
||||
* The grace exists because "the container is thirty seconds behind" and "the teapot does not
|
||||
* exist" look identical for the first thirty seconds, and only one of them should stop a deploy.
|
||||
* When the deadline passes it still throws: a provider the graph depends on is not optional, and
|
||||
* booting without it would only move the failure to the first request, where it becomes a caller's
|
||||
* 503 instead of the deploy's error.
|
||||
*
|
||||
* Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator
|
||||
* watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever
|
||||
* collects lifecycle events rather than only to whoever is reading a terminal.
|
||||
*/
|
||||
async function connectUntilDeadline(
|
||||
mesh: MeshConfig,
|
||||
bus: Bus,
|
||||
logger: Logger,
|
||||
attempt: () => Promise<Link>,
|
||||
): Promise<Link> {
|
||||
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
|
||||
const deadline = Date.now() + budgetMs;
|
||||
let delay = 500;
|
||||
let attempts = 0;
|
||||
|
||||
for (;;) {
|
||||
try {
|
||||
return await attempt();
|
||||
} catch (error) {
|
||||
attempts += 1;
|
||||
const remaining = deadline - Date.now();
|
||||
|
||||
// A refusal is the teapot's decision, not the network's, and it will be the same decision in
|
||||
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
|
||||
// identical error, so it fails now.
|
||||
if (isPermanentRefusal(error)) {
|
||||
logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Rethrown as-is rather than wrapped: connectLink already says whether this was a refused
|
||||
// handshake, a version mismatch or a timeout, and each sends you somewhere different.
|
||||
if (remaining <= 0) {
|
||||
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
|
||||
logger.warn(
|
||||
`mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`,
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
|
||||
delay = Math.min(delay * 2, 5_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Warn when a teapot's shared secret would cross a network in cleartext.
|
||||
*
|
||||
* The `hello` frame carries the secret verbatim, so `ws://` to anywhere but this machine puts it on
|
||||
* the wire for anyone in the path to read. Loopback is exempt because there is no path.
|
||||
*
|
||||
* A warning rather than a refusal: a private network behind a service mesh that already does mutual
|
||||
* TLS is a legitimate deployment, and green-tea cannot tell it apart from an exposed one.
|
||||
*/
|
||||
function warnIfCleartext(url: string, logger: Logger): void {
|
||||
if (!url.startsWith('ws://')) return;
|
||||
const host = url.slice('ws://'.length).split('/')[0].split(':')[0];
|
||||
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return;
|
||||
|
||||
logger.warn(
|
||||
`mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` +
|
||||
'use wss:// unless the link already runs inside an encrypted network.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
|
||||
*
|
||||
* Named and separate rather than inlined in the reconnect handler: this is the seam a future
|
||||
* `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice.
|
||||
*
|
||||
* Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a
|
||||
* network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection.
|
||||
*/
|
||||
function invalidateRemoteBindings(rebind: Array<() => void>): void {
|
||||
for (const bind of rebind) bind();
|
||||
}
|
||||
|
||||
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
|
||||
async function spliceRemoteScopes(
|
||||
mesh: MeshConfig,
|
||||
bus: Bus,
|
||||
registry: Registry,
|
||||
logger: Logger,
|
||||
container: Container,
|
||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
@@ -535,13 +718,23 @@ async function spliceRemoteScopes(
|
||||
|
||||
try {
|
||||
for (const teapot of mesh.teapots ?? []) {
|
||||
const link = await connectLink({
|
||||
url: teapot.url,
|
||||
secret: teapot.secret,
|
||||
timeoutMs: mesh.timeoutMs,
|
||||
heartbeatMs: mesh.heartbeatMs,
|
||||
bus,
|
||||
});
|
||||
warnIfCleartext(teapot.url, logger);
|
||||
// Deferred so the reconnect callback can name this link's provider tokens, which are only
|
||||
// known once its manifest arrives — the callback is registered before the link can drop.
|
||||
const rebind: Array<() => void> = [];
|
||||
const link = await connectUntilDeadline(mesh, bus, logger, () =>
|
||||
connectLink({
|
||||
url: teapot.url,
|
||||
secret: teapot.secret,
|
||||
timeoutMs: mesh.timeoutMs,
|
||||
heartbeatMs: mesh.heartbeatMs,
|
||||
reconnect: mesh.reconnect,
|
||||
onManifestChange: mesh.onManifestChange,
|
||||
onReconnect: () => invalidateRemoteBindings(rebind),
|
||||
logger,
|
||||
bus,
|
||||
}),
|
||||
);
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link);
|
||||
const origin = `mesh:${teapot.url}`;
|
||||
@@ -550,6 +743,10 @@ async function spliceRemoteScopes(
|
||||
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
|
||||
registry.providerMeta.set(provider.name, { optional: false });
|
||||
registry.setRunner(provider.name, provider.run);
|
||||
// A remote app-scope value is resolved once at boot and frozen into the container, so it
|
||||
// would keep answering from a cache the teapot no longer stands behind. Re-registering
|
||||
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
|
||||
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
|
||||
}
|
||||
|
||||
for (const step of steps) {
|
||||
@@ -588,8 +785,8 @@ async function spliceRemoteScopes(
|
||||
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||
)
|
||||
) {
|
||||
console.warn(
|
||||
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||
logger.warn(
|
||||
`mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||
'the local route takes precedence and the remote one will not be reached. ' +
|
||||
'Remove one if that is not what you meant.',
|
||||
);
|
||||
@@ -599,7 +796,19 @@ async function spliceRemoteScopes(
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
transport: 'buffer',
|
||||
handler: async (req) => route.handler(req as RequestEnvelope),
|
||||
// Built explicitly rather than cast from the handler argument. The cast put the whole
|
||||
// internal request on the wire — `ip` and `protocol` included — and sent fields the
|
||||
// protocol never declared, so a teapot could come to rely on something we never promised.
|
||||
handler: async (req) =>
|
||||
route.handler({
|
||||
method: req.method,
|
||||
params: req.params,
|
||||
query: req.query,
|
||||
body: req.body,
|
||||
headers: req.headers,
|
||||
url: req.url,
|
||||
correlation: { requestId: req.requestId, traceId: req.traceId },
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -633,10 +842,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 } = deps;
|
||||
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
|
||||
const degraded: string[] = [];
|
||||
|
||||
for (const node of orderedProviders) {
|
||||
@@ -646,6 +858,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 });
|
||||
@@ -657,7 +878,10 @@ async function bootProviders(
|
||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||
degraded.push(node.name);
|
||||
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, {
|
||||
provider: node.name,
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,7 +903,10 @@ 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;
|
||||
},
|
||||
degradedProviders: string[],
|
||||
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
|
||||
@@ -692,8 +919,9 @@ function makeAppBooter(
|
||||
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
|
||||
|
||||
if (degradedProviders.length) {
|
||||
console.warn(
|
||||
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
|
||||
deps.logger.warn(
|
||||
`started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
|
||||
{ degraded: degradedProviders },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -730,7 +958,14 @@ function buildMeshControl(
|
||||
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
|
||||
|
||||
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
|
||||
const context = await runSteps(steps, seed, bus);
|
||||
// The caller's identity, adopted rather than replaced — the same rule an incoming
|
||||
// `x-request-id` gets, applied at the process boundary where it matters most. No `route`:
|
||||
// resolving a scope is not a route, and inventing one would put a token in a route label.
|
||||
const context = await runSteps(steps, seed, bus, {
|
||||
requestId: env.correlation?.requestId,
|
||||
traceId: env.correlation?.traceId,
|
||||
method: env.method,
|
||||
});
|
||||
|
||||
return context[name];
|
||||
};
|
||||
@@ -752,6 +987,13 @@ function buildMeshControl(
|
||||
bus,
|
||||
onError,
|
||||
transport: plan.transport,
|
||||
correlation: {
|
||||
requestId: env.correlation?.requestId,
|
||||
traceId: env.correlation?.traceId,
|
||||
route: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
},
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
|
||||
@@ -789,6 +1031,15 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
|
||||
bus,
|
||||
onError,
|
||||
transport: plan.transport,
|
||||
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete
|
||||
// paths gets one label per distinct URL, and that takes down the metrics backend.
|
||||
correlation: {
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
route: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
},
|
||||
seed: {
|
||||
...provided,
|
||||
req,
|
||||
@@ -957,6 +1208,136 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs registered teardown, bounded so it cannot push `close()` past the budget it was given.
|
||||
*
|
||||
* Bounding lives here rather than in {@link TeardownRegistry} because the registry has no business
|
||||
* knowing about deadlines — `closeApp` and `closeWithDeadline` each already own one, and a third
|
||||
* implementation is how the three drift into different meanings of the same `timeoutMs`.
|
||||
*
|
||||
* A teardown that overruns is left running rather than awaited: the callback is someone else's code
|
||||
* and there is no way to interrupt it, so the choice is between returning on time and waiting
|
||||
* indefinitely. It resolves on its own timer for the same reason `closeWithDeadline` does.
|
||||
*/
|
||||
function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: number): Promise<void> {
|
||||
if (teardown.size === 0) return Promise.resolve();
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
// Armed before `finish` exists, for the reason spelled out in `closeApp` below: setTimeout
|
||||
// cannot fire synchronously, so the forward reference to `finish` rests on a guarantee, while
|
||||
// the reverse ordering would rest on `teardown.run().then()` deferring.
|
||||
const timer = setTimeout(
|
||||
() => {
|
||||
if (settled) return;
|
||||
logger.warn(`shutdown teardown exceeded its ${Math.max(0, budgetMs)}ms budget — returning without it`, {
|
||||
budgetMs: Math.max(0, budgetMs),
|
||||
});
|
||||
finish();
|
||||
},
|
||||
Math.max(0, budgetMs),
|
||||
);
|
||||
|
||||
timer.unref?.();
|
||||
|
||||
const finish = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
|
||||
void teardown.run(logger).then(finish, finish);
|
||||
});
|
||||
}
|
||||
|
||||
function closeApp(
|
||||
server: http.Server | undefined,
|
||||
meshLinks: Link[],
|
||||
streams: Set<() => void>,
|
||||
options: { timeoutMs?: number },
|
||||
defaultTimeoutMs: number | undefined,
|
||||
logger: Logger,
|
||||
teardown: TeardownRegistry,
|
||||
reservedMs: number | undefined,
|
||||
): Promise<void> {
|
||||
const timeoutMs = options.timeoutMs ?? defaultTimeoutMs ?? 10_000;
|
||||
const startedAt = Date.now();
|
||||
// Unset reserves nothing: the drain may use the whole budget and teardown takes what is left.
|
||||
// Set, it is carved out of the same budget rather than added to it, so `close()` still returns
|
||||
// within `timeoutMs` — which is the whole reason the caller set that number.
|
||||
const drainBudget = timeoutMs - (reservedMs ?? 0);
|
||||
|
||||
const drain = new Promise<void>((resolve) => {
|
||||
// A mesh app booted through `app.fetch` has links but no server, and would leak every
|
||||
// teapot connection otherwise — so links close before we even check for a server.
|
||||
closeLinks(meshLinks);
|
||||
|
||||
// No server means the app is served through `app.fetch` rather than `listen()`, which is how
|
||||
// Deno, Bun and the edge all run. Draining is the transport's job and only the transport holds
|
||||
// the handle, so `close()` is deliberately Node-only here rather than pretending otherwise;
|
||||
// `serveDeno`/`serveBun` return a server with the same bounded `close({ timeoutMs })`.
|
||||
if (!server) {
|
||||
if (options.timeoutMs !== undefined) {
|
||||
logger.warn(
|
||||
'close({ timeoutMs }) does not drain connections here — this app has no listen()ed ' +
|
||||
'server, so it only bounds teardown. On Deno and Bun, call close() on the server ' +
|
||||
'serveDeno()/serveBun() returned; it takes the same option and drains too. On the ' +
|
||||
'edge the platform owns the lifecycle.',
|
||||
);
|
||||
}
|
||||
|
||||
// Falls through to teardown rather than returning from close(). An app served through
|
||||
// `app.fetch` still booted its providers, so it still has connections that were opened and
|
||||
// are owed a close — the transport being someone else's job does not make them not ours.
|
||||
// Running teardown twice is safe: the registry drains once, whichever entry point is first.
|
||||
return resolve();
|
||||
}
|
||||
|
||||
let settled = false;
|
||||
|
||||
// The timer is armed before `finish` exists, rather than the other way round, and the ordering
|
||||
// is the point. Whichever one comes second is referenced by the other before its declaration
|
||||
// runs, so what matters is which forward reference rests on a guarantee. setTimeout cannot
|
||||
// invoke its callback synchronously — that is the event loop, not an implementation detail —
|
||||
// so `finish` is always assigned by the time the callback can reach it. The reverse ordering
|
||||
// relied on `server.close(cb)` deferring, which is Node's behaviour rather than a promise to
|
||||
// us, and left a `ReferenceError` waiting in the shutdown path for whoever changed it.
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
|
||||
logger.warn(`graceful shutdown timed out after ${timeoutMs}ms — forcing remaining HTTP connections closed`, {
|
||||
timeoutMs,
|
||||
});
|
||||
|
||||
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
|
||||
// below — `engines` in package.json only guarantees >=18, so this matters.
|
||||
server.closeAllConnections();
|
||||
finish();
|
||||
}, drainBudget);
|
||||
|
||||
timer.unref?.();
|
||||
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
|
||||
server.close(() => finish());
|
||||
|
||||
for (const closeStream of streams) closeStream();
|
||||
server.closeIdleConnections();
|
||||
});
|
||||
|
||||
// Teardown runs after the drain and before close() resolves: an in-flight request may still be
|
||||
// using the connection a teardown is about to close, so draining first is not an ordering
|
||||
// preference. It gets whatever is left of the budget — at least the reservation, if one was made.
|
||||
return drain.then(() => runTeardown(teardown, logger, timeoutMs - (Date.now() - startedAt)));
|
||||
}
|
||||
|
||||
/** Best-effort close of every mesh link, ignoring individual failures. */
|
||||
function closeLinks(links: Link[]): void {
|
||||
for (const link of links) {
|
||||
|
||||
+52
-1
@@ -1,5 +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';
|
||||
@@ -35,7 +37,7 @@ export interface Explain {
|
||||
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/**
|
||||
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
|
||||
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
|
||||
@@ -62,6 +64,12 @@ export interface App {
|
||||
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
|
||||
degraded(): string[];
|
||||
bus: Bus;
|
||||
/**
|
||||
* Where framework diagnostics are written — the one passed to `createApp({ logger })`, or the
|
||||
* default. Exposed so the Deno and Bun adapters report through the application's logger rather
|
||||
* than reaching past it to `console`, and so a plugin or a test can read what core would write.
|
||||
*/
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
|
||||
@@ -95,4 +103,47 @@ export interface MeshConfig {
|
||||
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
||||
*/
|
||||
heartbeatMs?: number;
|
||||
/**
|
||||
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
|
||||
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
|
||||
*
|
||||
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
|
||||
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
|
||||
* together do not come back in lockstep.
|
||||
*/
|
||||
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
|
||||
/**
|
||||
* What to do when a returning teapot's manifest no longer exports something the graph was
|
||||
* validated against at boot (default: `'refuse'`).
|
||||
*
|
||||
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
|
||||
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
|
||||
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
|
||||
* rather than left implicit so that arriving is additive rather than a change of default.
|
||||
*/
|
||||
onManifestChange?: 'refuse';
|
||||
/**
|
||||
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
|
||||
* so 30s). Attempts use the same backoff as reconnection.
|
||||
*
|
||||
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
|
||||
* has not settled — should not fail a deploy, and this is the grace for that. A teapot that is
|
||||
* genuinely absent still fails the boot when the deadline passes, because a provider the graph
|
||||
* depends on is not optional: booting without it would only move the failure to the first
|
||||
* request, where it is somebody else's 503 instead of your deploy's error.
|
||||
*
|
||||
* `0` restores the old behaviour of a single attempt.
|
||||
*/
|
||||
bootTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lifecycle participation for an application that does not want to be a plugin.
|
||||
*
|
||||
* Every method is optional, and the shape is an object rather than a single callback so later
|
||||
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
|
||||
*/
|
||||
export interface Hooks {
|
||||
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
|
||||
onShutdown?: TeardownFn;
|
||||
}
|
||||
+42
-3
@@ -3,6 +3,7 @@ import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
|
||||
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||
@@ -21,10 +22,25 @@ interface BunWebSocketHandler {
|
||||
}
|
||||
interface BunServer {
|
||||
port: number;
|
||||
stop(closeActiveConnections?: boolean): void;
|
||||
// Returns a promise, verified on Bun 1.3 — the previous `void` here was simply wrong, and it
|
||||
// hid the fact that this is awaitable at all.
|
||||
stop(closeActiveConnections?: boolean): Promise<void>;
|
||||
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
|
||||
requestIP(request: Request): { address: string; family: string; port: number } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What {@link serveBun} hands back: Bun's own server, plus the bounded `close()` that
|
||||
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Bun,
|
||||
* because a Bun app is served through `app.fetch` and never through `listen()`.
|
||||
*/
|
||||
export interface BunServeResult extends BunServer {
|
||||
/**
|
||||
* Drains in-flight requests, then force-closes whatever is left after `timeoutMs` (default:
|
||||
* 10s). Same meaning as `app.close({ timeoutMs })` on Node.
|
||||
*/
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
}
|
||||
interface BunServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
@@ -56,9 +72,11 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
|
||||
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
|
||||
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
||||
* Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||
* the deployment platform or reverse proxy.
|
||||
*/
|
||||
export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||
return Bun.serve({
|
||||
export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult {
|
||||
const server = Bun.serve({
|
||||
...options,
|
||||
fetch(request, server) {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
@@ -95,4 +113,25 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
|
||||
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
|
||||
return Object.assign(server, {
|
||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.stop(false).then(() => app.close()),
|
||||
() => void server.stop(true),
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
|
||||
timeoutMs: ms,
|
||||
runtime: 'bun',
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
+53
-2
@@ -12,16 +12,52 @@ export type LifecycleEvent =
|
||||
| 'mesh:connect'
|
||||
| 'mesh:disconnect'
|
||||
| 'mesh:rpc:error'
|
||||
| 'plugin:mounted';
|
||||
// A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
|
||||
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
|
||||
// came up, and a deploy watching for trouble wants to tell those apart.
|
||||
| 'mesh:boot:retry'
|
||||
| 'plugin:mounted'
|
||||
| 'request:start'
|
||||
| 'request:end'
|
||||
| 'request:failed'
|
||||
| 'route:matched'
|
||||
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
|
||||
// misreport the other, and "no route ran" is the fact a consumer actually wants.
|
||||
| 'route:unmatched';
|
||||
|
||||
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */
|
||||
/**
|
||||
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
|
||||
* the fields that say which request it belongs to.
|
||||
*
|
||||
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
|
||||
* name, and requiring a shape they cannot fill would only mean inventing values for it.
|
||||
*/
|
||||
export interface EventPayload {
|
||||
name: string;
|
||||
scope?: string;
|
||||
error?: unknown;
|
||||
durationMs?: number;
|
||||
/** Correlates every event of one request. Adopted from `x-request-id` when a gateway sent one. */
|
||||
requestId?: string;
|
||||
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
|
||||
traceId?: string;
|
||||
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */
|
||||
route?: string;
|
||||
method?: string;
|
||||
transport?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of {@link EventPayload} that identifies a request, spread into each of its events.
|
||||
*
|
||||
* `route` carries the matched pattern rather than the URL that arrived, and that is load-bearing
|
||||
* rather than cosmetic: a metrics consumer that labels a counter with a concrete path gets one
|
||||
* label per distinct URL, and unbounded label cardinality takes down the metrics backend rather
|
||||
* than the application. Handing anyone that shape by default would be the framework's fault.
|
||||
*/
|
||||
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
|
||||
|
||||
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||
export class Bus {
|
||||
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
||||
@@ -34,6 +70,21 @@ export class Bus {
|
||||
return () => listenerSet.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether anything is listening to `event` — for skipping the *construction* of a payload nobody
|
||||
* will read.
|
||||
*
|
||||
* Not a micro-optimisation looking for a problem. A correlated payload is built by spreading the
|
||||
* request's identity into it, and that spread was measured at ~197 ns per request on a two-step
|
||||
* pipeline — against a ~4.5 µs in-process request, on a path where the overwhelmingly common
|
||||
* case is an application that subscribes to nothing at all. `emit` cannot help: its argument is
|
||||
* already built by the time it is called. Only the caller can decline to build it.
|
||||
*/
|
||||
hasListeners(event: LifecycleEvent): boolean {
|
||||
const listenerSet = this.listeners.get(event);
|
||||
return listenerSet !== undefined && listenerSet.size > 0;
|
||||
}
|
||||
|
||||
/** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
|
||||
emit(event: LifecycleEvent, payload: EventPayload): void {
|
||||
for (const listener of this.listeners.get(event) ?? []) {
|
||||
|
||||
+58
-2
@@ -1,5 +1,6 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
|
||||
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
|
||||
@@ -22,6 +23,23 @@ interface DenoHttpServer {
|
||||
finished: Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What {@link serveDeno} hands back: Deno's own server, plus the bounded `close()` that
|
||||
* `app.close()` cannot provide here. `app.close()` returns at its `if (!server)` guard on Deno,
|
||||
* because a Deno app is served through `app.fetch` and never through `listen()`.
|
||||
*/
|
||||
export interface DenoServer extends DenoHttpServer {
|
||||
/**
|
||||
* Drains in-flight requests, returning after at most `timeoutMs` (default: 10s).
|
||||
*
|
||||
* **The deadline bounds the wait, not the connections** — unlike Node's `app.close()` and Bun's
|
||||
* `close()`, which force the remainder shut. Deno offers no force-close that composes with a
|
||||
* drain already under way: aborting the serve signal at that point throws `BadResource` from
|
||||
* Deno's own listener, uncaught. Whatever is still open when this resolves ends with the process.
|
||||
*/
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
}
|
||||
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
|
||||
declare const Deno: {
|
||||
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
|
||||
@@ -31,9 +49,17 @@ declare const Deno: {
|
||||
/**
|
||||
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
|
||||
* WebSocket messages flow through app.upgrade over the shared neutral core.
|
||||
* Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||
* the deployment platform or reverse proxy.
|
||||
*/
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||
return Deno.serve(options ?? {}, (request, info) => {
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
|
||||
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to
|
||||
// own one to offer a deadline at all. A caller-supplied signal still works and still aborts the
|
||||
// server — it is chained into ours rather than replaced, so neither party loses its control.
|
||||
const ac = new AbortController();
|
||||
options?.signal?.addEventListener('abort', () => ac.abort(), { once: true });
|
||||
|
||||
const server = Deno.serve({ ...options, signal: ac.signal }, (request, info) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
|
||||
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
|
||||
@@ -46,4 +72,34 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer
|
||||
|
||||
return app.fetch(request);
|
||||
});
|
||||
|
||||
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
|
||||
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
|
||||
return Object.assign(server, {
|
||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.shutdown().then(() => app.close()),
|
||||
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
|
||||
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
|
||||
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
||||
// surfaces uncaught — not catchable at this call site, and fatal under `deno test`.
|
||||
// Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot
|
||||
// escalate from graceful to forced the way Node's closeAllConnections() and Bun's
|
||||
// stop(true) can, and the deadline here bounds how long `close()` waits, not when the
|
||||
// connections die. Exiting the process after `close()` resolves is what ends them.
|
||||
() => {},
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(
|
||||
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
|
||||
'a server that is already draining, so remaining connections end when the process does.',
|
||||
{ timeoutMs: ms, runtime: 'deno' },
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
|
||||
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
|
||||
// the caller as a {@link BodyReader}.
|
||||
import { HttpError, isHttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import type { MatchedRoute, HttpOptions } from './types';
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
export interface BodyFailure {
|
||||
fail: { status: number; headers: Record<string, string>; body: string };
|
||||
}
|
||||
|
||||
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
|
||||
export type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
|
||||
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
return value instanceof Promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the raw request body, enforcing `limit`.
|
||||
*
|
||||
* The adapter owns this and nothing else about the body, because enforcement is the one place the
|
||||
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
|
||||
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
|
||||
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
|
||||
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
|
||||
* without bound first.
|
||||
*
|
||||
* The failure branch is opaque on purpose: Node answers an over-limit request with
|
||||
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
|
||||
* That header means nothing on the fetch side, and is a forbidden response header on some
|
||||
* runtimes, so the adapter that needs it is the one that attaches it.
|
||||
*
|
||||
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
|
||||
* reader can be built **once per server** instead of once per request: a closure capturing the
|
||||
* request measured at 250 ns per request together with the error-context object it captured —
|
||||
* more than the duplicate route resolution this whole indirection removes.
|
||||
*/
|
||||
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
export async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
|
||||
*
|
||||
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
|
||||
* character for character, because each adapter had to route the request itself in order to know
|
||||
* whether to read a body — and so ended up owning every policy that depends on the matched route.
|
||||
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
|
||||
* runtimes quietly disagree about limits.
|
||||
*/
|
||||
export function acquireBody(
|
||||
read: BodyReader,
|
||||
source: unknown,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const acquired = read(source, limit);
|
||||
|
||||
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
|
||||
// this whole path without a single promise, and an `async` wrapper here would allocate one
|
||||
// regardless. Same reason `handle()` is not async.
|
||||
return isPromise(acquired)
|
||||
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
|
||||
: parseAcquired(acquired, matched, opts, req);
|
||||
}
|
||||
|
||||
function parseAcquired(
|
||||
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
if ('fail' in acquired) return acquired;
|
||||
|
||||
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
|
||||
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
|
||||
// off the promise path entirely.
|
||||
if (acquired.bytes === undefined) return { body: undefined };
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
|
||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
||||
'error' in parsed
|
||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
|
||||
: { body: parsed.body },
|
||||
);
|
||||
}
|
||||
+215
-9
@@ -5,23 +5,110 @@ import { isStreamResult, type PipelineResult } from '../pipeline';
|
||||
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
||||
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||
import { pickEncoder } from './stream';
|
||||
import { acquireBody, type BodyReader } from './body';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import type { Bus } from '../bus';
|
||||
|
||||
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
|
||||
/**
|
||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
||||
*
|
||||
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
|
||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
||||
*
|
||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
||||
* why that job is pinned to the floor rather than to the current release.
|
||||
*
|
||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the
|
||||
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`.
|
||||
*/
|
||||
const randomUUID: () => string = (() => {
|
||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
|
||||
})();
|
||||
|
||||
/**
|
||||
* A runtime-neutral inbound request.
|
||||
*
|
||||
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
|
||||
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
|
||||
* body, it first had to route the request itself — a body is only read for a request that reaches
|
||||
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
|
||||
* a four-route app walked its table two and a half times per request. Handing over the *ability*
|
||||
* to read instead of the result moves that decision here, where the route is known anyway.
|
||||
*/
|
||||
export interface NeutralRequest {
|
||||
method: string;
|
||||
url: string; // path + query, e.g. "/users/9?x=1"
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
body: unknown; // already-parsed body
|
||||
/** Called only once a route matches, so an unmatched request still never reads a body. */
|
||||
readBody: BodyReader;
|
||||
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
|
||||
source: unknown;
|
||||
secure: boolean;
|
||||
ip: string;
|
||||
requestId: string;
|
||||
traceId?: string;
|
||||
}
|
||||
|
||||
// Module scope, not a local inside `correlateRequest`. Declared there it was a closure allocated
|
||||
// on every single request, which measured at 0.16 us against a ~4.4 us one — 45% of the whole
|
||||
// observability overhead, for a helper that captures nothing.
|
||||
const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
|
||||
|
||||
/**
|
||||
* Derives a request's identity from its headers, for the adapters to stamp on a `NeutralRequest`.
|
||||
*
|
||||
* **Called by the adapters, not by {@link handle}**, and the placement is the point. An adapter's
|
||||
* `BodyReader` renders its own `413` (`server.ts`, `web.ts`) without `handle()` ever producing it,
|
||||
* so identity has to exist before the read starts. Generating it in here would leave precisely the
|
||||
* failures an operator most wants to correlate with nothing to correlate them by.
|
||||
*
|
||||
* An `x-request-id` from a gateway is adopted rather than replaced — a service behind a proxy must
|
||||
* not open a second identity for a request that already has one. `traceparent` is carried through
|
||||
* untouched: core implements no propagation spec, and W3C Trace Context belongs to the exporter.
|
||||
*/
|
||||
export function correlateRequest(headers: Record<string, string | string[] | undefined>): {
|
||||
requestId: string;
|
||||
traceId?: string;
|
||||
} {
|
||||
const incoming = first(headers['x-request-id'])?.trim();
|
||||
const traceId = first(headers.traceparent)?.trim();
|
||||
|
||||
// `randomUUID` is not the lazy choice here, it is the measured one. Every supported runtime
|
||||
// already batches entropy behind it, so the obvious "faster" replacements are not:
|
||||
//
|
||||
// crypto.randomUUID() 76 ns
|
||||
// batched getRandomValues + hex, 12 bytes 50 ns cross-runtime, saves 0.26% of a request
|
||||
// batched + Buffer.toString('hex') 49 ns Node-only, so it cannot be used here
|
||||
// uint32 -> toString(36) from a pool 114 ns
|
||||
// Math.random() x2 -> base36 265 ns 3.5x SLOWER; string work dominates
|
||||
// getRandomValues per call, unbatched 472 ns
|
||||
//
|
||||
// The only cross-runtime win is 26 ns, against ~10.19 us for a real socketed request. A hand-
|
||||
// rolled entropy pool is not worth 0.26%. A lazy getter is separately useless: the adapters and
|
||||
// the payload builders both spread this object, and the first spread materialises it.
|
||||
return { requestId: incoming || randomUUID(), traceId: traceId || undefined };
|
||||
}
|
||||
|
||||
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
|
||||
export type NeutralOutcome =
|
||||
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
|
||||
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder };
|
||||
| {
|
||||
kind: 'stream';
|
||||
headers: Record<string, string>;
|
||||
stream: AsyncIterable<unknown>;
|
||||
encoder: StreamEncoder;
|
||||
/** The matched route's pattern, for naming the stream lifecycle events. */
|
||||
route: string;
|
||||
};
|
||||
|
||||
/** {@link handle}'s result for a normal (non-preflight) request. */
|
||||
export interface HandleResult {
|
||||
@@ -56,7 +143,7 @@ function errorOutcome(
|
||||
opts: HttpOptions | undefined,
|
||||
headers: Record<string, string> = {},
|
||||
): HandleResult {
|
||||
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||
const rendered = renderError(error, req, opts?.onError);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
@@ -104,15 +191,91 @@ async function unmatchedOutcome(
|
||||
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||
}
|
||||
|
||||
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
||||
interface Trace {
|
||||
route?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
||||
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
|
||||
*
|
||||
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
|
||||
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
|
||||
* here in milliseconds while its connection may live for hours, and ending the span at close would put
|
||||
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
|
||||
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
|
||||
*/
|
||||
export async function handle(
|
||||
export function handle(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const bus = opts?.bus;
|
||||
|
||||
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
|
||||
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
|
||||
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
|
||||
if (
|
||||
bus === undefined ||
|
||||
!(
|
||||
bus.hasListeners('request:start') ||
|
||||
bus.hasListeners('request:end') ||
|
||||
bus.hasListeners('route:matched') ||
|
||||
bus.hasListeners('route:unmatched')
|
||||
)
|
||||
) {
|
||||
return dispatch(routes, opts, req, undefined, undefined);
|
||||
}
|
||||
|
||||
return observedDispatch(routes, opts, req, bus);
|
||||
}
|
||||
|
||||
async function observedDispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const watchingEnd = bus.hasListeners('request:end');
|
||||
const startedAt = watchingEnd ? performance.now() : 0;
|
||||
const trace: Trace = {};
|
||||
|
||||
if (bus.hasListeners('request:start'))
|
||||
bus.emit('request:start', {
|
||||
name: `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
const result = await dispatch(routes, opts, req, bus, trace);
|
||||
|
||||
if (watchingEnd) {
|
||||
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
||||
// by the time anything is piped.
|
||||
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
|
||||
bus.emit('request:end', {
|
||||
name: trace.route ?? `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
route: trace.route,
|
||||
status,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function dispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus | undefined,
|
||||
trace: Trace | undefined,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const injected = computeInjected(opts, req);
|
||||
let path: string;
|
||||
@@ -129,7 +292,39 @@ export async function handle(
|
||||
|
||||
const matched = resolveRoute(routes, req.method, path);
|
||||
|
||||
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
if (!matched) {
|
||||
if (bus?.hasListeners('route:unmatched'))
|
||||
bus.emit('route:unmatched', {
|
||||
name: `${req.method} ${path}`,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
}
|
||||
|
||||
if (trace) trace.route = matched.def.pattern;
|
||||
|
||||
if (bus?.hasListeners('route:matched'))
|
||||
bus.emit('route:matched', {
|
||||
name: matched.def.pattern,
|
||||
route: matched.def.pattern,
|
||||
method: req.method,
|
||||
transport: matched.def.transport,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
|
||||
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
|
||||
// object per request bought nothing.
|
||||
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
|
||||
|
||||
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
|
||||
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
|
||||
// caller merges `injected` into it exactly as it does for every other outcome.
|
||||
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
|
||||
|
||||
let result: PipelineResult;
|
||||
|
||||
@@ -140,17 +335,28 @@ export async function handle(
|
||||
headers: req.headers,
|
||||
params: matched.params,
|
||||
query: parseQuery(req.url),
|
||||
body: req.body,
|
||||
body: acquired.body,
|
||||
protocol: req.secure ? 'https' : 'http',
|
||||
ip: req.ip,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
} catch (error) {
|
||||
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||
result = renderError(error, req, opts?.onError);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'stream',
|
||||
headers: encoder.headers,
|
||||
stream: result.stream,
|
||||
encoder,
|
||||
route: matched.def.pattern,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+12
-2
@@ -1,5 +1,7 @@
|
||||
import { mergeVary } from '../security';
|
||||
|
||||
const hasOwn = Object.prototype.hasOwnProperty;
|
||||
|
||||
/**
|
||||
* Merges a handler's response headers with authoritative `injected` headers
|
||||
* (security + CORS). Injected keys win case-insensitively; `vary` is merged.
|
||||
@@ -10,7 +12,6 @@ export function mergeInjectedHeaders(
|
||||
injected: Record<string, string>,
|
||||
): Record<string, any> {
|
||||
const merged: Record<string, any> = {};
|
||||
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
|
||||
let handlerVary: string | undefined;
|
||||
|
||||
if (handlerHeaders)
|
||||
@@ -22,7 +23,16 @@ export function mergeInjectedHeaders(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
|
||||
// `injected` is looked up directly instead of through a lowercased Set rebuilt per response.
|
||||
// Every key it can hold is written as a lowercase literal in `src/security.ts` — both
|
||||
// `buildSecurityHeaders` and `resolveCors`, which are its only sources — so lowercasing them
|
||||
// again produced a copy of the keys it already had. Three allocations per response (an array,
|
||||
// a mapped array, a Set) to answer a question the object answers itself: 146.4 ns against
|
||||
// 55.9 ns.
|
||||
//
|
||||
// `hasOwnProperty` rather than `in`: a handler is free to send a header called `constructor`
|
||||
// or `toString`, and `in` would find those on Object.prototype and silently drop them.
|
||||
if (!hasOwn.call(injected, lowerKey)) merged[key] = handlerHeaders[key];
|
||||
}
|
||||
|
||||
Object.assign(merged, injected);
|
||||
|
||||
+111
-10
@@ -13,6 +13,8 @@ export interface CompiledPattern {
|
||||
segments: CompiledSegment[];
|
||||
kinds: number[];
|
||||
catchAll: boolean;
|
||||
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
|
||||
allStatic: boolean;
|
||||
}
|
||||
|
||||
const compiledCache = new Map<string, CompiledPattern>();
|
||||
@@ -158,21 +160,88 @@ export function compilePattern(pattern: string): CompiledPattern {
|
||||
.filter((segment) => segment.kind !== 'catchAll')
|
||||
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||
allStatic: segments.every((segment) => segment.kind === 'static'),
|
||||
};
|
||||
compiledCache.set(pattern, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
|
||||
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
|
||||
|
||||
/**
|
||||
* Classifies one path segment as `.`, `..`, or neither.
|
||||
*
|
||||
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
|
||||
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
|
||||
* plain form resolves away from.
|
||||
*/
|
||||
function dotSegment(segment: string): '.' | '..' | undefined {
|
||||
if (segment === '.' || segment === '..') return segment;
|
||||
if (segment.length > 6 || !segment.includes('%')) return undefined;
|
||||
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
|
||||
return decoded === '.' || decoded === '..' ? decoded : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
|
||||
*
|
||||
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
|
||||
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
|
||||
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
|
||||
* simply not recoverable there, so rejecting dot segments outright — which is what this module
|
||||
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
|
||||
* runtimes. Resolving is the only rule all four can agree on.
|
||||
*
|
||||
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
|
||||
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
|
||||
*/
|
||||
function resolveDotSegments(path: string): string {
|
||||
const out: string[] = [];
|
||||
|
||||
for (const segment of path.split('/').slice(1)) {
|
||||
const dots = dotSegment(segment);
|
||||
if (dots === '.') continue;
|
||||
|
||||
if (dots === '..') {
|
||||
out.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
out.push(segment);
|
||||
}
|
||||
|
||||
return `/${out.join('/')}`;
|
||||
}
|
||||
|
||||
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||
export function normalizeRequestPath(path: string): string {
|
||||
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
|
||||
try {
|
||||
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
|
||||
} catch {
|
||||
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||
// Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no
|
||||
// `%` at all — which is most of them — pays only the scans.
|
||||
const resolved =
|
||||
(path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path;
|
||||
const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
|
||||
|
||||
// Validation only — the decoded value is deliberately discarded, matching is done on the raw
|
||||
// path. So the work is skipped entirely unless there is something to validate.
|
||||
//
|
||||
// This used to split the path and call `decodeURIComponent` per segment, on every request, and
|
||||
// throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment
|
||||
// route — around 8% of a whole request, spent proving that a string nobody decodes could be
|
||||
// decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths.
|
||||
//
|
||||
// One call on the whole string rather than per segment is the same check: `decodeURIComponent`
|
||||
// throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment
|
||||
// decodes fine either way. Only the throw matters here, never the result.
|
||||
if (normalized.includes('%')) {
|
||||
try {
|
||||
decodeURIComponent(normalized);
|
||||
} catch {
|
||||
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||
}
|
||||
}
|
||||
|
||||
return normalized;
|
||||
@@ -182,8 +251,18 @@ function decodeSegment(value: string): string {
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
|
||||
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
|
||||
const pathSegs = path.split('/').filter(Boolean);
|
||||
/**
|
||||
* Splits a request path into its non-empty segments.
|
||||
*
|
||||
* Called once per request by the scanning functions below, not once per candidate route. It used to
|
||||
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
|
||||
* registered route on every request, always producing the same array.
|
||||
*/
|
||||
function splitPath(path: string): string[] {
|
||||
return path.split('/').filter(Boolean);
|
||||
}
|
||||
|
||||
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let index = 0; index < compiled.segments.length; index++) {
|
||||
@@ -211,7 +290,7 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
|
||||
|
||||
/** Matches a compiled segment pattern and returns its decoded parameters. */
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
return matchCompiled(compilePattern(pattern), path);
|
||||
return matchCompiled(compilePattern(pattern), splitPath(path));
|
||||
}
|
||||
|
||||
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
|
||||
@@ -232,14 +311,26 @@ function moreSpecific(a: string, b: string): number {
|
||||
|
||||
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
const pathSegs = splitPath(path);
|
||||
let best: MatchedRoute | undefined;
|
||||
let bestPattern = '';
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.method !== method) continue;
|
||||
const params = matchPattern(route.pattern, path);
|
||||
const compiled = compilePattern(route.pattern);
|
||||
const params = matchCompiled(compiled, pathSegs);
|
||||
if (!params) continue;
|
||||
|
||||
// An all-static match ends the scan. Specificity ranks a literal segment above every other
|
||||
// kind, so no pattern that also matches this path can outrank one made only of literals — and
|
||||
// an equal rank keeps registration order, which is this route. Finishing the scan would
|
||||
// re-derive the answer already in hand.
|
||||
//
|
||||
// The scan used to run to the end regardless: `/hello` cost the same whether it was declared
|
||||
// first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per
|
||||
// registered route on every request, and it grows with the route table.
|
||||
if (compiled.allStatic) return { params, def: route };
|
||||
|
||||
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||
best = { params, def: route };
|
||||
bestPattern = route.pattern;
|
||||
@@ -271,10 +362,11 @@ const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'
|
||||
|
||||
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
const pathSegs = splitPath(path);
|
||||
const methods = new Set<string>();
|
||||
|
||||
for (const route of routes) {
|
||||
if (!matchPattern(route.pattern, path)) continue;
|
||||
if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
|
||||
methods.add(route.method);
|
||||
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
||||
}
|
||||
@@ -291,6 +383,15 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
// Most requests carry no query string, and the work below is not free for them: `split` builds
|
||||
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
|
||||
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
|
||||
//
|
||||
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
|
||||
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
|
||||
// means, and that is a behaviour question rather than a performance one.
|
||||
if (!url.includes('?')) return {};
|
||||
|
||||
const queryString = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||
|
||||
+42
-117
@@ -1,29 +1,23 @@
|
||||
import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import { isHttpError, HttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import { normalizeRequestPath, resolveRoute } from './router';
|
||||
import { readBody, deriveSecure, deriveIp } from './request';
|
||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { handle } from './core';
|
||||
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
||||
import { handle, correlateRequest } from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
bus?: Bus;
|
||||
opts?: HttpOptions;
|
||||
maxBody: number;
|
||||
trustProxy: boolean;
|
||||
}
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
|
||||
|
||||
/** Builds the {@link ErrorRequest} handed to a user error renderer. */
|
||||
function errorRequest(req: http.IncomingMessage): ErrorRequest {
|
||||
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
|
||||
@@ -44,9 +38,8 @@ export function createHttpServer(
|
||||
meshControl?: MeshControl,
|
||||
opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const trustProxy = opts?.trustProxy ?? false;
|
||||
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
|
||||
const handler = createRequestHandler({ routes, bus, opts, trustProxy });
|
||||
|
||||
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
|
||||
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
|
||||
@@ -59,6 +52,8 @@ export function createHttpServer(
|
||||
const server: http.Server = (opts?.tls
|
||||
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: nodeHttp.createServer(handler)) as unknown as http.Server;
|
||||
const maxConnections = opts?.limits?.maxConnections ?? 1000;
|
||||
if (maxConnections > 0) server.maxConnections = maxConnections;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
@@ -68,21 +63,23 @@ export function createHttpServer(
|
||||
|
||||
/**
|
||||
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
|
||||
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`,
|
||||
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is
|
||||
* installed here — and stays the single source of truth for merging headers into every response —
|
||||
* so `handle()`'s own `injected` is intentionally unused by this adapter.
|
||||
* Describes the request, supplies the {@link BodyReader} the core calls once a route matches, then
|
||||
* writes the result to `res` (buffered or streamed). Routing, body parsing, limits and error
|
||||
* rendering all live in the core. The security-header monkeypatch is installed here — and stays the
|
||||
* single source of truth for merging headers into every response — so `handle()`'s own `injected`
|
||||
* is intentionally unused by this adapter.
|
||||
*/
|
||||
function createRequestHandler(cfg: HandlerConfig) {
|
||||
const { routes, bus, opts, maxBody, trustProxy } = cfg;
|
||||
const { routes, bus, opts, trustProxy } = cfg;
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
const method = req.method ?? 'GET';
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(req.headers);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
@@ -90,36 +87,13 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
// by reference at writeHead time, so keys added here still land on every response.
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
|
||||
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
||||
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
||||
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
||||
let matched: ReturnType<typeof resolveRoute>;
|
||||
|
||||
try {
|
||||
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
|
||||
} catch {
|
||||
matched = undefined; // handle() owns the standard 400 envelope and injected headers
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
|
||||
if (matched) {
|
||||
const acquired = await acquireBody(req, matched, opts, maxBody);
|
||||
|
||||
if ('fail' in acquired) {
|
||||
res.writeHead(acquired.fail.status, acquired.fail.headers);
|
||||
res.end(acquired.fail.body);
|
||||
return;
|
||||
}
|
||||
|
||||
body = acquired.body;
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
method,
|
||||
url,
|
||||
...correlation,
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
body,
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
@@ -131,7 +105,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
}
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
|
||||
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -140,34 +114,27 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
|
||||
async function acquireBody(
|
||||
req: http.IncomingMessage,
|
||||
matched: MatchedRoute,
|
||||
/**
|
||||
* The Node half of body acquisition: bytes off the socket, and the over-limit answer.
|
||||
*
|
||||
* `readBody` enforces the limit against the running total as chunks arrive, so an oversized upload
|
||||
* is rejected without being buffered. `connection: close` on that response is load-bearing — it
|
||||
* stops the remainder of the upload from continuing to arrive on a kept-alive socket.
|
||||
*/
|
||||
function readRequestBytes(
|
||||
source: unknown,
|
||||
limit: number,
|
||||
opts: HttpOptions | undefined,
|
||||
maxBody: number,
|
||||
): Promise<{ body: unknown } | BodyFailure> {
|
||||
let buf: Buffer | undefined;
|
||||
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
|
||||
): Promise<{ bytes: Buffer | undefined } | BodyFailure> {
|
||||
const req = source as http.IncomingMessage;
|
||||
|
||||
try {
|
||||
buf = await readBody(req, bodyLimit);
|
||||
} catch (error) {
|
||||
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
}
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
|
||||
|
||||
if ('error' in parsed) {
|
||||
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
|
||||
return { fail: rendered };
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
return readBodyBytes(req, limit).then(
|
||||
(bytes) => ({ bytes }),
|
||||
(error: unknown) => {
|
||||
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,45 +151,3 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
export async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Bounds a graceful shutdown by a deadline, forcing whatever is left.
|
||||
*
|
||||
* Shared by the Deno and Bun adapters so the two cannot drift into different meanings of the same
|
||||
* `timeoutMs`, and shaped like the Node path in `closeApp`: try to drain, and if the deadline
|
||||
* passes first, force the remainder and resolve anyway.
|
||||
*
|
||||
* The race is the point, and it is not paranoia. Both runtimes' force calls were measured against
|
||||
* a handler that never resolves and returned immediately, but `Bun.stop(true)` was also measured
|
||||
* waiting out a handler with a pending timer — same call, ~2s, because it awaits pending async
|
||||
* work rather than only open connections. Awaiting the force call would therefore inherit exactly
|
||||
* the unbounded wait the deadline exists to prevent. Resolving on our own timer means `close()`
|
||||
* returns within `timeoutMs` whatever either runtime decides to wait for.
|
||||
*
|
||||
* @param graceful Drain in flight work. Unbounded — that is what the deadline is for.
|
||||
* @param force Stop waiting and drop what is left. Fire-and-forget; its promise is not awaited.
|
||||
*/
|
||||
export function closeWithDeadline(
|
||||
graceful: () => Promise<void>,
|
||||
force: () => void,
|
||||
timeoutMs: number,
|
||||
onTimeout?: (timeoutMs: number) => void,
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
// Armed before `finish` exists, and deliberately: setTimeout cannot invoke its callback
|
||||
// synchronously, so `finish` is always assigned by the time this can reach it. The reverse
|
||||
// ordering would rest on when the runtime's own promise settles. Mirrors `closeApp`.
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
onTimeout?.(timeoutMs);
|
||||
force();
|
||||
finish();
|
||||
}, timeoutMs);
|
||||
|
||||
timer.unref?.();
|
||||
|
||||
const finish = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
|
||||
// A graceful path that rejects still has to end the shutdown: the deadline covers a slow
|
||||
// close, not a broken one, and leaving close() pending forever is the worse failure.
|
||||
void graceful().then(finish, finish);
|
||||
});
|
||||
}
|
||||
+13
-1
@@ -4,10 +4,12 @@ import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import type { StaticResolver } from '../views';
|
||||
import type { Bus } from '../bus';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
/** Per-request and per-server resource ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
@@ -16,6 +18,12 @@ export interface RequestLimits {
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
export interface HttpOptions {
|
||||
/**
|
||||
* Lifecycle events go here. Carried on the options rather than as a parameter so `handle()` —
|
||||
* the one place both the Node and Fetch adapters meet — can emit without either adapter growing
|
||||
* a separate channel for it.
|
||||
*/
|
||||
bus?: Bus;
|
||||
limits?: RequestLimits;
|
||||
streams?: Set<() => void>;
|
||||
tls?: TlsOptions;
|
||||
@@ -37,6 +45,10 @@ export type RouteHandler = (req: {
|
||||
body: unknown;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
/** Correlates every lifecycle event this request emits; see `correlateRequest` in `./core`. */
|
||||
requestId: string;
|
||||
/** An incoming `traceparent`, carried verbatim for an exporter to interpret. */
|
||||
traceId?: string;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */
|
||||
|
||||
+72
-76
@@ -1,11 +1,10 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, type HandleResult } from './core';
|
||||
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { parseRequestBody } from './server';
|
||||
import { normalizeRequestPath, resolveRoute } from './router';
|
||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
||||
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
|
||||
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
|
||||
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
||||
@@ -44,60 +43,66 @@ function headersToRecord(headers: Headers): Record<string, string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
|
||||
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where
|
||||
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures
|
||||
* (413/400/501) carry them too.
|
||||
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
|
||||
*
|
||||
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
|
||||
* or not at all, so the limit can only be checked once the bytes are already in memory. That
|
||||
* difference is exactly why the limit is passed in rather than applied by the shared core.
|
||||
*/
|
||||
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response {
|
||||
const headers = mergeInjectedHeaders(rendered.headers, injected);
|
||||
return new Response(rendered.body, { status: rendered.status, headers });
|
||||
function readFetchBytes(
|
||||
source: unknown,
|
||||
limit: number,
|
||||
opts: HttpOptions | undefined,
|
||||
): MaybePromise<{ bytes: Buffer | undefined } | BodyFailure> {
|
||||
const request = source as Request;
|
||||
// Not `async`: a bodiless request answers without allocating a promise at all.
|
||||
if (!request.body) return { bytes: undefined };
|
||||
|
||||
return request.arrayBuffer().then((arrayBuffer) => {
|
||||
if (arrayBuffer.byteLength > limit) {
|
||||
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
|
||||
// a `url`/`headers` pair captured up-front cost more than the work it saved.
|
||||
const url = new URL(request.url);
|
||||
const errReq: ErrorRequest = {
|
||||
method: request.method,
|
||||
url: url.pathname + url.search,
|
||||
headers: headersToRecord(request.headers),
|
||||
};
|
||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
|
||||
}
|
||||
|
||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
|
||||
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure.
|
||||
* Whatever the host runtime's `Response` accepts as a body. Derived from the constructor rather
|
||||
* than written as `BodyInit`, because that name is not global under this `lib` (`es2020` plus
|
||||
* `@types/node`) even though `Response` itself is — and Deno spells the same idea from its own lib.
|
||||
*/
|
||||
async function acquireFetchBody(
|
||||
request: Request,
|
||||
matched: MatchedRoute,
|
||||
headers: Record<string, string>,
|
||||
path: string,
|
||||
maxBody: number,
|
||||
opts: HttpOptions | undefined,
|
||||
injected: Record<string, string>,
|
||||
): Promise<{ body: unknown } | { response: Response }> {
|
||||
const errReq: ErrorRequest = { method: request.method, url: path, headers };
|
||||
let buf: Buffer | undefined;
|
||||
type ResponseBody = ConstructorParameters<typeof Response>[0];
|
||||
|
||||
if (request.body) {
|
||||
const arrayBuffer = await request.arrayBuffer();
|
||||
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
|
||||
|
||||
if (arrayBuffer.byteLength > bodyLimit) {
|
||||
return {
|
||||
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected),
|
||||
};
|
||||
}
|
||||
|
||||
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
const contentType = headers['content-type'] ?? '';
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
|
||||
|
||||
if ('error' in parsed) {
|
||||
return {
|
||||
response: errorResponse(
|
||||
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
|
||||
injected,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
/**
|
||||
* Narrows a buffered body to something the runtime's `Response` accepts.
|
||||
*
|
||||
* A Node `Buffer` is a `Uint8Array` at runtime, so every runtime here takes one — but its declared
|
||||
* backing store is `ArrayBufferLike`, which admits `SharedArrayBuffer`, and `BodyInit` accepts only
|
||||
* `ArrayBuffer`-backed views. Deno's lib therefore rejects it outright: this is the `app.fetch` path,
|
||||
* so the mismatch reaches Deno, Bun and edge alike. Node never allocates a Buffer over a
|
||||
* `SharedArrayBuffer`, which is what makes the assertion on the backing store safe to state.
|
||||
*
|
||||
* `byteOffset`/`byteLength` are load-bearing, not defensive. `Buffer.from` and `Buffer.allocUnsafe`
|
||||
* hand back a window into a shared 8 KB pool, so re-viewing the backing store without them yields
|
||||
* the whole pool — neighbouring allocations included. Today the only Buffer reaching here comes from
|
||||
* `fs.promises.readFile`, which returns an exactly-sized allocation, so nothing currently trips that.
|
||||
* `StaticHit.body` is typed `Buffer` though, and a pooled one is a correct value for it.
|
||||
*
|
||||
* Re-viewing rather than copying: this is the buffered-response path, and a copy per response would
|
||||
* be a real cost on the runtimes that have no other adapter.
|
||||
*/
|
||||
export function toBodyInit(body: string | Buffer): ResponseBody {
|
||||
if (typeof body === 'string') return body;
|
||||
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
|
||||
}
|
||||
|
||||
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
||||
@@ -108,48 +113,39 @@ function outcomeToResponse(result: HandleResult): Response {
|
||||
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||
}
|
||||
|
||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
|
||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
|
||||
return new Response(body, { status: result.outcome.status, headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
|
||||
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the
|
||||
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed).
|
||||
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
|
||||
* calls once a route matches, and converts the outcome to a `Response` (buffered or streamed).
|
||||
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
|
||||
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
|
||||
*/
|
||||
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname + url.search;
|
||||
const headers = headersToRecord(request.headers);
|
||||
let matched: ReturnType<typeof resolveRoute>;
|
||||
|
||||
try {
|
||||
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
|
||||
} catch {
|
||||
matched = undefined; // handle() renders the shared 400 response without reading a body
|
||||
}
|
||||
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(headers);
|
||||
const secure = url.protocol === 'https:';
|
||||
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
||||
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
||||
// would have installed before body acquisition.
|
||||
// Computed up-front from the same inputs `handle()` uses, so a preflight — the one response
|
||||
// this adapter builds itself — carries the same security/CORS headers every other one does.
|
||||
const injected = computeInjected(opts, { secure, headers });
|
||||
let body: unknown;
|
||||
|
||||
if (matched) {
|
||||
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
|
||||
if ('response' in acquired) return acquired.response;
|
||||
body = acquired.body;
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
body,
|
||||
readBody,
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
|
||||
+7
-2
@@ -40,7 +40,7 @@ export {
|
||||
Options,
|
||||
Html,
|
||||
} from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export type { Transport, HttpMethod, RouteDecorator } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
|
||||
// Transformers & error signals
|
||||
@@ -58,12 +58,17 @@ export {
|
||||
|
||||
// Bus & flow
|
||||
export { Bus } from './bus';
|
||||
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
|
||||
export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
|
||||
// Parameter decorators
|
||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
|
||||
|
||||
// Observability
|
||||
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
|
||||
export type { Logger, LogLevel, LogFields } from './logger';
|
||||
|
||||
// Streaming
|
||||
export { channel, isAsyncIterable } from './channel';
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// src/lifecycle.ts — the teardown registry. Knows nothing about plugins, providers, apps or HTTP;
|
||||
// the doors into it live where those things do.
|
||||
import type { Logger } from './logger';
|
||||
|
||||
/**
|
||||
* Something to run before the app goes away.
|
||||
*
|
||||
* Takes no arguments on purpose. State lives in the closure that registered it — a provider's
|
||||
* `dispose()` already holds its own connection, and a plugin's callback already holds whatever the
|
||||
* plugin built. Nothing has to cross a scope, which is what makes this a registry rather than an
|
||||
* event bus: a bus solves "tell someone I do not know", and this is "run the thing I registered".
|
||||
*/
|
||||
export type TeardownFn = () => void | Promise<void>;
|
||||
|
||||
/**
|
||||
* Await-aware teardown, deliberately not the {@link Bus}.
|
||||
*
|
||||
* `Bus.on` takes a synchronous listener and `emit` swallows failures, both so that an observer can
|
||||
* never break the pipeline. A teardown needs the opposite of each: it must be awaited, and its
|
||||
* failure must be visible. Same word, opposite guarantees — see D1 of the design.
|
||||
*
|
||||
* Bounding is deliberately *not* here. `closeApp` and `closeWithDeadline` already implement a
|
||||
* deadline each, and a third implementation is how the three drift into different meanings of the
|
||||
* same `timeoutMs`.
|
||||
*/
|
||||
export class TeardownRegistry {
|
||||
private readonly callbacks: TeardownFn[] = [];
|
||||
private drained = false;
|
||||
|
||||
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
|
||||
add(fn: TeardownFn): void {
|
||||
this.callbacks.push(fn);
|
||||
}
|
||||
|
||||
/** How many callbacks are registered; lets a caller skip the whole path when nothing wants it. */
|
||||
get size(): number {
|
||||
return this.callbacks.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run every callback, newest first, awaiting each.
|
||||
*
|
||||
* **Reverse registration order is load-bearing.** Providers register as they boot, and they boot
|
||||
* in topological order, so reversing registration is what gives dependants teardown before their
|
||||
* dependencies: a `cache` that needs `db` closes before the `db` it is still holding.
|
||||
*
|
||||
* Sequential rather than parallel, for the same reason — an order only means something if it is
|
||||
* waited on.
|
||||
*
|
||||
* A failing callback is reported and the next one still runs. One broken teardown must not strand
|
||||
* the rest or leave the process up. This mirrors `Bus`'s "a subscriber cannot break the system",
|
||||
* but with the visibility `Bus` lacks: `Bus` swallows silently because no logger existed when it
|
||||
* was written, and one exists now.
|
||||
*
|
||||
* Never throws, and never runs twice — `close()` is called twice by more real applications than
|
||||
* anyone expects, and a second call must not re-close what the first one closed.
|
||||
*/
|
||||
async run(logger: Logger): Promise<void> {
|
||||
if (this.drained) return;
|
||||
this.drained = true;
|
||||
|
||||
for (let index = this.callbacks.length - 1; index >= 0; index--) {
|
||||
try {
|
||||
await this.callbacks[index]();
|
||||
} catch (error) {
|
||||
logger.warn(`a shutdown teardown failed: ${(error as Error)?.message ?? String(error)}`, { error });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
import type { EventPayload } from './bus';
|
||||
|
||||
/**
|
||||
* The logging contract. Four levels, because four have callers: core diagnostics are all `warn`
|
||||
* today, request logging adds `info` and `error`, and the graph diagnostics add `debug`. No
|
||||
* `trace`, no `fatal`, no `silent` — a level nothing emits is a decision handed to the user for
|
||||
* no reason.
|
||||
*/
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
|
||||
/** Structured context attached to a log record. Flattened into the JSON output alongside the message. */
|
||||
export type LogFields = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* What `createApp({ logger })` accepts, and what core writes every diagnostic through.
|
||||
*
|
||||
* Message first, fields second, so a call reads as a sentence and the structured part stays
|
||||
* optional. Bridging a `pino`- or `winston`-style logger is a four-line adapter in either
|
||||
* direction; core defines the shape it needs rather than adopting anyone's.
|
||||
*/
|
||||
export interface Logger {
|
||||
debug(message: string, fields?: LogFields): void;
|
||||
info(message: string, fields?: LogFields): void;
|
||||
warn(message: string, fields?: LogFields): void;
|
||||
error(message: string, fields?: LogFields): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether output should be human-readable rather than JSON.
|
||||
*
|
||||
* Decided once, when the logger is built, and never per call — the answer cannot change while the
|
||||
* process runs, and asking on every record would put a syscall-shaped question on a path that is
|
||||
* supposed to be cheap. `process` is absent on the edge, so the guard is not defensive padding:
|
||||
* unattended is the correct default there, and JSON is the unattended format.
|
||||
*/
|
||||
function isInteractive(): boolean {
|
||||
const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;
|
||||
return Boolean(proc?.stdout?.isTTY);
|
||||
}
|
||||
|
||||
const CONSOLE_METHOD: Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'> = {
|
||||
debug: 'debug',
|
||||
info: 'info',
|
||||
warn: 'warn',
|
||||
error: 'error',
|
||||
};
|
||||
|
||||
function renderPretty(level: LogLevel, message: string, fields?: LogFields): string {
|
||||
const pairs = fields
|
||||
? Object.entries(fields)
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
|
||||
: [];
|
||||
|
||||
return `[green-tea] ${level.toUpperCase()} ${message}${pairs.length ? ' ' + pairs.join(' ') : ''}`;
|
||||
}
|
||||
|
||||
function renderJson(level: LogLevel, message: string, fields?: LogFields): string {
|
||||
// `name` rather than the `[green-tea]` prefix the messages used to carry inline: a log
|
||||
// aggregator filters on a field, and cannot filter on a substring of prose.
|
||||
return JSON.stringify({ level, time: new Date().toISOString(), name: 'green-tea', msg: message, ...fields });
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a logger so a throwing one cannot go silent.
|
||||
*
|
||||
* `Bus.emit` isolates listener failures on purpose — an observer must never be able to break a
|
||||
* request — but that guarantee has a cost when the observer is the logger itself: a user logger
|
||||
* that throws would simply stop writing, with nothing to say so. Falling back to `console` keeps
|
||||
* the Bus's promise without paying for it in silence.
|
||||
*
|
||||
* Exported because request logging is not the only thing that should survive a broken logger.
|
||||
*/
|
||||
export function withConsoleFallback(logger: Logger): Logger {
|
||||
const guard =
|
||||
(level: LogLevel) =>
|
||||
(message: string, fields?: LogFields): void => {
|
||||
try {
|
||||
logger[level](message, fields);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
renderJson('error', 'the configured logger threw; falling back to console', {
|
||||
level,
|
||||
originalMessage: message,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
...fields,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return { debug: guard('debug'), info: guard('info'), warn: guard('warn'), error: guard('error') };
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes request logging to the lifecycle stream: `info` per completed request, `error` per
|
||||
* failed one. Returns an unsubscribe function, so it is as removable as it is composable — which
|
||||
* is what "a composable step, not a global middleware" has to mean in practice.
|
||||
*
|
||||
* Reads the stream rather than being called from the request path, so there is exactly one account
|
||||
* of what happened to a request. A second path would eventually disagree with the first.
|
||||
*/
|
||||
export function logRequests(bus: BusLike, logger: Logger): () => void {
|
||||
const safe = withConsoleFallback(logger);
|
||||
const offEnd = bus.on('request:end', (event) => {
|
||||
safe.info(`${event.method ?? ''} ${event.route ?? event.name} ${event.status ?? ''}`.trim(), {
|
||||
requestId: event.requestId,
|
||||
traceId: event.traceId,
|
||||
route: event.route,
|
||||
method: event.method,
|
||||
status: event.status,
|
||||
durationMs: event.durationMs,
|
||||
});
|
||||
});
|
||||
const offFailed = bus.on('request:failed', (event) => {
|
||||
safe.error(`${event.method ?? ''} ${event.route ?? event.name} failed`.trim(), {
|
||||
requestId: event.requestId,
|
||||
traceId: event.traceId,
|
||||
route: event.route,
|
||||
method: event.method,
|
||||
error: event.error instanceof Error ? event.error.message : event.error,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
offEnd();
|
||||
offFailed();
|
||||
};
|
||||
}
|
||||
|
||||
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
|
||||
interface BusLike {
|
||||
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The logger used when `createApp` is given none: structured JSON, or human-readable on a TTY.
|
||||
*
|
||||
* Writes through `console`, which is the whole reason core can have a logging contract without a
|
||||
* logging dependency — `reflect-metadata` stays the only runtime dependency, and anything richer
|
||||
* (transports, sampling, rotation) is a `Logger` a user passes in.
|
||||
*/
|
||||
export function createDefaultLogger(pretty: boolean = isInteractive()): Logger {
|
||||
const write = (level: LogLevel, message: string, fields?: LogFields): void => {
|
||||
console[CONSOLE_METHOD[level]](pretty ? renderPretty(level, message, fields) : renderJson(level, message, fields));
|
||||
};
|
||||
|
||||
return {
|
||||
debug: (message, fields) => write('debug', message, fields),
|
||||
info: (message, fields) => write('info', message, fields),
|
||||
warn: (message, fields) => write('warn', message, fields),
|
||||
error: (message, fields) => write('error', message, fields),
|
||||
};
|
||||
}
|
||||
+312
-60
@@ -1,6 +1,8 @@
|
||||
import type { Bus } from '../bus';
|
||||
import type { Logger } from '../logger';
|
||||
import { HttpError } from '../signals';
|
||||
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
|
||||
import { compilePattern } from '../http/router';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
@@ -11,15 +13,71 @@ export interface Link {
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Backoff bounds for reconnection. `false` disables reconnecting entirely. */
|
||||
export interface ReconnectOptions {
|
||||
/** Delay before the first retry; doubles from here (default: 500ms). */
|
||||
initialDelayMs?: number;
|
||||
/** Ceiling the doubling stops at (default: 30s). */
|
||||
maxDelayMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do when a reconnecting teapot answers with a manifest that no longer backs the graph.
|
||||
*
|
||||
* Only `'refuse'` exists. It is a named strategy rather than implicit behaviour so that hot graph
|
||||
* reconciliation can arrive later as `'reconcile'` *additively* — peers run on separate deploy
|
||||
* cadences, and silently changing what the default means is the worst kind of breaking change.
|
||||
*/
|
||||
export type ManifestPolicy = 'refuse';
|
||||
|
||||
/**
|
||||
* A connection failure the peer decided, rather than one the network caused.
|
||||
*
|
||||
* The distinction is what boot retry needs: a refused secret or a version mismatch will fail
|
||||
* identically forever, so retrying one spends a deploy's patience to reach the same error. It is
|
||||
* derived from whether the socket ever *opened* — a peer that accepted the connection and then hung
|
||||
* up before the manifest rejected us on purpose; one that never accepted it may simply not be up.
|
||||
*/
|
||||
export function isPermanentRefusal(error: unknown): boolean {
|
||||
return (error as { meshRefused?: boolean } | undefined)?.meshRefused === true;
|
||||
}
|
||||
|
||||
/** Tag an error as a decision by the peer, so the caller does not retry it. */
|
||||
function refused(message: string): Error {
|
||||
const error = new Error(message) as Error & { meshRefused: boolean };
|
||||
error.meshRefused = true;
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
||||
type PendingEntry = {
|
||||
/** The token or route asked for. Kept so an error can be reported by name — the frame only carries the id. */
|
||||
name: string;
|
||||
resolve: (v: unknown) => void;
|
||||
reject: (e: unknown) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
/** Mutable per-link state: which socket is current, and whether the application hung up for good. */
|
||||
interface LinkState {
|
||||
socket: WsSocket | undefined;
|
||||
closed: boolean;
|
||||
retry: ReturnType<typeof setTimeout> | undefined;
|
||||
}
|
||||
|
||||
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
|
||||
interface Session {
|
||||
socket: WsSocket;
|
||||
manifest: Manifest;
|
||||
heartbeat: { stop: () => void; markAlive: () => void };
|
||||
}
|
||||
|
||||
const DEFAULT_INITIAL_DELAY_MS = 500;
|
||||
const DEFAULT_MAX_DELAY_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Reject and clear every in-flight RPC — used when the link closes.
|
||||
* Reject and clear every in-flight RPC — used when a session ends.
|
||||
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
|
||||
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
|
||||
*/
|
||||
@@ -34,7 +92,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
|
||||
|
||||
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
||||
function sendRpc(
|
||||
socket: WsSocket,
|
||||
socket: WsSocket | undefined,
|
||||
pending: Map<string, PendingEntry>,
|
||||
id: string,
|
||||
kind: 'scope' | 'route',
|
||||
@@ -44,8 +102,9 @@ function sendRpc(
|
||||
): Promise<unknown> {
|
||||
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
|
||||
// would make every request to a downed teapot hang for the full timeout (30s by default)
|
||||
// before failing anyway — the caller pays for a verdict already known.
|
||||
if (!socket.isOpen) {
|
||||
// before failing anyway — the caller pays for a verdict already known. This is also the
|
||||
// window a reconnecting link sits in: down, and answering immediately.
|
||||
if (!socket?.isOpen) {
|
||||
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
|
||||
}
|
||||
|
||||
@@ -57,30 +116,11 @@ function sendRpc(
|
||||
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
|
||||
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
|
||||
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
|
||||
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
}
|
||||
|
||||
/** Assemble the client-facing Link once the manifest arrives. */
|
||||
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
|
||||
// ids only need to be unique within this link: `pending` is per-connection, so a
|
||||
// per-link counter suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
|
||||
return {
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = String(counter++);
|
||||
|
||||
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
|
||||
},
|
||||
close() {
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
||||
function settleRpcResponse(
|
||||
pending: Map<string, PendingEntry>,
|
||||
@@ -95,7 +135,10 @@ function settleRpcResponse(
|
||||
if (frame.ok) {
|
||||
entry.resolve(frame.result);
|
||||
} else {
|
||||
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
||||
// `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report
|
||||
// "0" or "1" where every other emitter reports what failed — including the teapot's own
|
||||
// emit for the same call, which made the two sides of one failure impossible to line up.
|
||||
bus?.emit('mesh:rpc:error', { name: entry.name, error: frame.error });
|
||||
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||
}
|
||||
}
|
||||
@@ -118,7 +161,8 @@ const CLOSE_HEARTBEAT_TIMEOUT = 4011;
|
||||
* A TCP connection can die without either side noticing — a dropped route, a killed container,
|
||||
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
|
||||
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
|
||||
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
|
||||
* turns that into an immediate 503 from the dead-link guard, emits `mesh:disconnect`, and starts
|
||||
* the reconnect backoff.
|
||||
*
|
||||
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
||||
*/
|
||||
@@ -144,25 +188,24 @@ function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
|
||||
/** Handle for the in-flight handshake, so the frame loop can settle the session promise. */
|
||||
interface Handshake {
|
||||
url: string;
|
||||
socket: WsSocket;
|
||||
pending: Map<string, PendingEntry>;
|
||||
timeoutMs: number;
|
||||
bus?: Bus;
|
||||
resolve: (link: Link) => void;
|
||||
resolve: (session: Session) => void;
|
||||
reject: (error: unknown) => void;
|
||||
onManifest: () => void;
|
||||
onManifest: (socket: WsSocket) => Session['heartbeat'];
|
||||
onPong: () => void;
|
||||
}
|
||||
|
||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
|
||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else hand back the session. */
|
||||
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
|
||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||
hs.socket.close();
|
||||
hs.reject(
|
||||
new Error(
|
||||
refused(
|
||||
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
|
||||
),
|
||||
);
|
||||
@@ -170,12 +213,15 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
|
||||
return;
|
||||
}
|
||||
|
||||
hs.onManifest();
|
||||
hs.bus?.emit('mesh:connect', { name: hs.url });
|
||||
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
|
||||
const heartbeat = hs.onManifest(hs.socket);
|
||||
|
||||
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
|
||||
// the graph is refused after this point, and announcing a connection we are about to hang up on
|
||||
// would tell an operator the opposite of what happened.
|
||||
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
|
||||
}
|
||||
|
||||
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
async function readFrames(hs: Handshake): Promise<void> {
|
||||
for await (const data of hs.socket.inbound) {
|
||||
let frame: Frame;
|
||||
@@ -192,49 +238,61 @@ async function readFrames(hs: Handshake): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
/** Everything a link needs to open one session, shared by the first connect and every retry. */
|
||||
interface SessionArgs {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
timeoutMs: number;
|
||||
heartbeatMs: number;
|
||||
pending: Map<string, PendingEntry>;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
let manifest = false;
|
||||
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
|
||||
onEnd: () => void;
|
||||
}
|
||||
|
||||
return new Promise<Link>((resolve, reject) => {
|
||||
/**
|
||||
* Open one authenticated session: connect, handshake, and resolve once the manifest arrives.
|
||||
*
|
||||
* `onEnd` fires when this session's socket aborts — on a clean close and on an error alike — and is
|
||||
* where the supervisor rejects in-flight RPCs and decides whether to retry. It fires for a session
|
||||
* that never handshook too, which is what turns a refused connection into a scheduled retry rather
|
||||
* than a silent stall.
|
||||
*/
|
||||
function openSession(args: SessionArgs): Promise<Session> {
|
||||
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
||||
let heartbeat: Session['heartbeat'] | undefined;
|
||||
let handshook = false;
|
||||
let accepted = false;
|
||||
|
||||
return new Promise<Session>((resolve, reject) => {
|
||||
const connectTimer = setTimeout(() => {
|
||||
socket.close();
|
||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||
}, timeoutMs);
|
||||
}, args.timeoutMs);
|
||||
|
||||
const hs: Handshake = {
|
||||
url: args.url,
|
||||
socket,
|
||||
pending,
|
||||
timeoutMs,
|
||||
pending: args.pending,
|
||||
bus: args.bus,
|
||||
resolve,
|
||||
reject,
|
||||
onManifest: () => {
|
||||
manifest = true;
|
||||
onManifest: (established) => {
|
||||
handshook = true;
|
||||
clearTimeout(connectTimer);
|
||||
// started only once authenticated: an unauthenticated peer should not be pinging
|
||||
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
|
||||
heartbeat = startHeartbeat(established, args.heartbeatMs);
|
||||
|
||||
return heartbeat;
|
||||
},
|
||||
onPong: () => heartbeat?.markAlive(),
|
||||
};
|
||||
|
||||
opened.then(
|
||||
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
|
||||
() => {
|
||||
accepted = true;
|
||||
socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }));
|
||||
},
|
||||
(error) => reject(error),
|
||||
);
|
||||
|
||||
@@ -245,9 +303,16 @@ export function connectLink(args: {
|
||||
() => {
|
||||
clearTimeout(connectTimer);
|
||||
heartbeat?.stop();
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
|
||||
if (!handshook) {
|
||||
// Opened and then hung up before answering: the teapot refused this peer — a bad secret,
|
||||
// or a version it would not speak. Never opened: it may just not be listening yet.
|
||||
const message = `mesh handshake failed: ${args.url}`;
|
||||
|
||||
reject(accepted ? refused(message) : new Error(message));
|
||||
}
|
||||
|
||||
args.onEnd();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
@@ -257,3 +322,190 @@ export function connectLink(args: {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
|
||||
function scopeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
|
||||
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
|
||||
*/
|
||||
function routeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the boot manifest had that a returning one does not.
|
||||
*
|
||||
* The graph was validated at boot against the first manifest and is already serving. A token that
|
||||
* vanished cannot be validated away after the fact, so a manifest missing anything this link
|
||||
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
|
||||
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
|
||||
*/
|
||||
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||
const scopes = scopeKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const scope of booted.scopes) {
|
||||
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
|
||||
}
|
||||
|
||||
for (const route of booted.routes) {
|
||||
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
|
||||
missing.push(`route '${route.method} ${route.pattern}'`);
|
||||
}
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
|
||||
function backoffBounds(
|
||||
reconnect: boolean | ReconnectOptions | undefined,
|
||||
): { initial: number; max: number } | undefined {
|
||||
if (reconnect === false) return undefined;
|
||||
const opts = typeof reconnect === 'object' ? reconnect : {};
|
||||
|
||||
return {
|
||||
initial: opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS,
|
||||
max: opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. The returned `Link` outlives any single socket: when a session drops, the link keeps its
|
||||
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
|
||||
*
|
||||
* `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
/** Reconnect after a dropped session (default: on). `false` restores the old fail-once behaviour. */
|
||||
reconnect?: boolean | ReconnectOptions;
|
||||
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
|
||||
onManifestChange?: ManifestPolicy;
|
||||
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
|
||||
onReconnect?: () => void;
|
||||
logger?: Logger;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||
const bounds = backoffBounds(args.reconnect);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
|
||||
let refusalLogged = '';
|
||||
|
||||
const link: Link = {
|
||||
// replaced with the real manifest before this object escapes; a reconnect never changes it,
|
||||
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
|
||||
manifest: { scopes: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
close: () => {
|
||||
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||
// the application hung up would leave a process that cannot exit.
|
||||
state.closed = true;
|
||||
clearTimeout(state.retry);
|
||||
state.socket?.close();
|
||||
},
|
||||
};
|
||||
// ids only need to be unique within this link: `pending` is per-link, so a per-link counter
|
||||
// suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
|
||||
const sessionArgs = (onEnd: () => void): SessionArgs => ({
|
||||
url: args.url,
|
||||
secret: args.secret,
|
||||
timeoutMs,
|
||||
heartbeatMs,
|
||||
pending,
|
||||
bus: args.bus,
|
||||
Ctor: args.Ctor,
|
||||
onEnd,
|
||||
});
|
||||
|
||||
/** Schedule the next attempt, doubling from `initial` up to `max` with jitter. */
|
||||
const scheduleRetry = (attempt: number): void => {
|
||||
if (state.closed || !bounds) return;
|
||||
const capped = Math.min(bounds.initial * 2 ** attempt, bounds.max);
|
||||
// Full jitter: peers that went down together must not come back in lockstep and stampede
|
||||
// the teapot the moment it returns.
|
||||
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
|
||||
|
||||
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
|
||||
state.retry.unref?.();
|
||||
};
|
||||
|
||||
/** End the current session: nothing can be delivered on it, so fail what was waiting. */
|
||||
const endSession = (attempt: number): void => {
|
||||
state.socket = undefined;
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
scheduleRetry(attempt);
|
||||
};
|
||||
|
||||
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
|
||||
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => {
|
||||
const missing = missingFromManifest(link.manifest, session.manifest);
|
||||
|
||||
if (missing.length > 0) {
|
||||
session.heartbeat.stop();
|
||||
session.socket.close();
|
||||
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
|
||||
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
|
||||
// link keeps retrying rather than giving up.
|
||||
const fingerprint = missing.join('|');
|
||||
|
||||
if (fingerprint !== refusalLogged) {
|
||||
refusalLogged = fingerprint;
|
||||
args.logger?.warn(
|
||||
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
|
||||
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
refusalLogged = '';
|
||||
state.socket = session.socket;
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
if (reconnected) args.onReconnect?.();
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const attemptReconnect = async (attempt: number): Promise<void> => {
|
||||
if (state.closed) return;
|
||||
|
||||
try {
|
||||
const session = await openSession(sessionArgs(() => endSession(attempt)));
|
||||
|
||||
if (state.closed) {
|
||||
session.socket.close(); // hung up while this attempt was in flight
|
||||
return;
|
||||
}
|
||||
|
||||
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
|
||||
} catch {
|
||||
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
|
||||
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
|
||||
if (!state.socket && !state.retry) scheduleRetry(attempt);
|
||||
}
|
||||
};
|
||||
|
||||
return openSession(sessionArgs(() => endSession(0))).then((session) => {
|
||||
link.manifest = session.manifest;
|
||||
adopt(session, 0, false);
|
||||
|
||||
return link;
|
||||
});
|
||||
}
|
||||
+117
-3
@@ -1,18 +1,46 @@
|
||||
/**
|
||||
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
|
||||
* cadences — possibly on different runtimes — so the frame shapes are a contract between
|
||||
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
|
||||
* refuse each other on mismatch rather than misparsing downstream.
|
||||
* green-tea versions, not an internal detail. Peers refuse each other on mismatch rather
|
||||
* than misparsing downstream.
|
||||
*
|
||||
* **This is a compatibility boundary, not a changelog.** Bump it only when a peer running the
|
||||
* old version would *misparse a frame or misbehave silently*:
|
||||
*
|
||||
* - removing or renaming a field, or changing its type or meaning;
|
||||
* - adding a **required** field;
|
||||
* - adding a frame type that expects an answer — an old peer cannot decode it, drops it as
|
||||
* undecodable, and the sender waits for a reply that will never come.
|
||||
*
|
||||
* Adding an **optional** field is not one of those: `decode` validates only the fields a frame
|
||||
* type requires and passes extras through untouched, so an old peer ignores what it does not
|
||||
* know and keeps answering. That is degraded, not broken, and does not earn a bump.
|
||||
*
|
||||
* Bumping per change would make the number mean "work happened" rather than "we are
|
||||
* incompatible", which is the one thing it is here to say.
|
||||
*/
|
||||
export const MESH_PROTOCOL_VERSION = 1;
|
||||
|
||||
/** Serialized request context sent across the mesh for a scope or route RPC. */
|
||||
/**
|
||||
* Serialized request context sent across the mesh for a scope or route RPC.
|
||||
*
|
||||
* `correlation` and `url` are optional by protocol, not by intent: a teapot running an older
|
||||
* green-tea simply ignores them, which costs the correlation of that hop and nothing else.
|
||||
*/
|
||||
export interface RequestEnvelope {
|
||||
method: string;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
/** The requested URL, so a teapot's handler sees the same path its caller did. */
|
||||
url?: string;
|
||||
/**
|
||||
* The caller's request identity, so a request that crosses the mesh keeps one id end to end.
|
||||
* Without it every hop opens a new investigation, in the one place a distributed trace is
|
||||
* the whole point.
|
||||
*/
|
||||
correlation?: { requestId?: string; traceId?: string };
|
||||
}
|
||||
|
||||
/** Manifest entry for an exported scope token and its lifetime. */
|
||||
@@ -87,6 +115,92 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
||||
},
|
||||
};
|
||||
|
||||
/** How much of a value the transport check walks before it stops looking. */
|
||||
const TRANSPORT_SCAN_BUDGET = 10_000;
|
||||
|
||||
/** Names what a value is, for an error a reader can act on: `Pool`, `Map`, `Date`, `function`. */
|
||||
function describe(value: unknown): string {
|
||||
if (typeof value === 'function') return 'a function';
|
||||
const name = (value as object).constructor?.name;
|
||||
|
||||
return name ? `a ${name} instance` : 'an object with no prototype';
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first part of `value` that cannot survive the wire, or `undefined` if all of it can.
|
||||
*
|
||||
* The wire is JSON, so the mesh transports **data, never behaviour**. Before this check, exporting a
|
||||
* value with methods — a connection pool, a client, a `Map` — serialized to `{}` and arrived looking
|
||||
* alive: truthy, an object, and missing every method. The failure then surfaced as
|
||||
* `db.query is not a function` at the call site, arbitrarily far from the export that caused it.
|
||||
*
|
||||
* The rule is an allowlist rather than a denylist, on purpose. `Date` is refused too: it would
|
||||
* arrive as a string, which is not the type the caller declared and is the same silent difference
|
||||
* in a smaller costume.
|
||||
*
|
||||
* Bounded by a node budget so a large legitimate payload is never turned into an error by the cost
|
||||
* of checking it — past the budget the value is assumed fine, since the shapes this catches are
|
||||
* structural and show up immediately.
|
||||
*/
|
||||
export function untransportable(value: unknown, path = 'result'): Offender | undefined {
|
||||
return walk(value, path, { left: TRANSPORT_SCAN_BUDGET });
|
||||
}
|
||||
|
||||
/** What could not cross, and where it sat in the value. */
|
||||
type Offender = { path: string; what: string };
|
||||
|
||||
/** Remaining nodes the scan may visit, shared across the whole walk. */
|
||||
type Budget = { left: number };
|
||||
|
||||
/** Values JSON cannot represent at all, whatever they are nested in. */
|
||||
function isBehaviour(kind: string): boolean {
|
||||
return kind === 'function' || kind === 'symbol' || kind === 'bigint';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a container survives the round trip as itself: a plain object or a null-prototype bag.
|
||||
* Anything else is a class instance whose identity JSON discards — `Pool`, `Map`, `Set`, `Date`.
|
||||
*/
|
||||
function isPlainContainer(node: object): boolean {
|
||||
const proto = Object.getPrototypeOf(node);
|
||||
|
||||
return proto === Object.prototype || proto === null;
|
||||
}
|
||||
|
||||
/** Walk labelled children in order, returning the first offender. */
|
||||
function walkEntries(entries: Array<[string, unknown]>, budget: Budget): Offender | undefined {
|
||||
for (const [at, item] of entries) {
|
||||
const found = walk(item, at, budget);
|
||||
|
||||
if (found) return found;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** One node of the scan: reject behaviour and class instances, otherwise descend. */
|
||||
function walk(node: unknown, at: string, budget: Budget): Offender | undefined {
|
||||
if (budget.left-- <= 0 || node === null) return undefined;
|
||||
const kind = typeof node;
|
||||
|
||||
if (isBehaviour(kind)) return { path: at, what: describe(node) };
|
||||
if (kind !== 'object') return undefined;
|
||||
|
||||
if (Array.isArray(node)) {
|
||||
return walkEntries(
|
||||
node.map((item, index) => [`${at}[${index}]`, item] as [string, unknown]),
|
||||
budget,
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainContainer(node as object)) return { path: at, what: describe(node) };
|
||||
|
||||
return walkEntries(
|
||||
Object.entries(node as Record<string, unknown>).map(([key, item]) => [`${at}.${key}`, item] as [string, unknown]),
|
||||
budget,
|
||||
);
|
||||
}
|
||||
|
||||
/** Serialize a frame to a JSON wire string. */
|
||||
export function encode(frame: Frame): string {
|
||||
return JSON.stringify(frame);
|
||||
|
||||
+14
-2
@@ -14,14 +14,26 @@ export interface RemoteRoute {
|
||||
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
|
||||
}
|
||||
|
||||
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
|
||||
/**
|
||||
* Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh.
|
||||
*
|
||||
* `url` and `correlation` are read off `ctx.req`, the handler argument the pipeline seeds the
|
||||
* context with — so a request that crosses to a teapot arrives carrying the id it already had,
|
||||
* and its events on the far side join the same trace instead of starting a new one.
|
||||
*/
|
||||
export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
const req = ctx?.req;
|
||||
const correlation = { requestId: req?.requestId, traceId: req?.traceId };
|
||||
|
||||
return {
|
||||
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
|
||||
method: req?.method ?? ctx?.method ?? 'GET',
|
||||
params: ctx?.params ?? {},
|
||||
query: ctx?.query ?? {},
|
||||
body: ctx?.body,
|
||||
headers: ctx?.headers ?? {},
|
||||
url: req?.url,
|
||||
// omitted rather than sent empty: an envelope with no identity should look like one
|
||||
...(correlation.requestId || correlation.traceId ? { correlation } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+53
-1
@@ -9,6 +9,7 @@ import { isHttpError } from '../signals';
|
||||
import {
|
||||
encode,
|
||||
decode,
|
||||
untransportable,
|
||||
MESH_PROTOCOL_VERSION,
|
||||
type Manifest,
|
||||
type RequestEnvelope,
|
||||
@@ -19,6 +20,28 @@ import {
|
||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
/**
|
||||
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
||||
*
|
||||
* The teacup has always bounded its side of the handshake; the teapot had no equivalent, so a peer
|
||||
* could connect and simply never send `hello`, holding a socket indefinitely without proving
|
||||
* anything. Generous on purpose — this is a deadline against silence, not a latency budget.
|
||||
*/
|
||||
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Largest control frame the teapot will parse, in characters.
|
||||
*
|
||||
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
|
||||
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
|
||||
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
|
||||
* documented ceiling on the platform sockets Deno and Bun provide).
|
||||
*
|
||||
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
|
||||
* overhead of the envelope around it.
|
||||
*/
|
||||
const MAX_FRAME_CHARS = 4_000_000;
|
||||
|
||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||
export function buildManifest(args: {
|
||||
providers: string[]; // exported provider tokens (app-scope)
|
||||
@@ -133,6 +156,19 @@ async function handleRpc(
|
||||
|
||||
try {
|
||||
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
|
||||
// Checked here, on the side that still holds the real value. Past `encode` the evidence is
|
||||
// gone: JSON turns a pool into `{}`, which arrives looking alive and fails at the call site.
|
||||
const offender = untransportable(result);
|
||||
|
||||
if (offender) {
|
||||
const error: any = new Error(
|
||||
`mesh cannot transport '${name}': ${offender.path} is ${offender.what}. ` +
|
||||
'The wire is JSON, so a mesh export carries data, never behaviour — export what the ' +
|
||||
'handle produces rather than the handle.',
|
||||
);
|
||||
error.status = 500;
|
||||
throw error;
|
||||
}
|
||||
|
||||
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
} catch (err) {
|
||||
@@ -151,19 +187,34 @@ async function serveFrames(
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<void> {
|
||||
let authed = false;
|
||||
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
|
||||
// says nothing is indistinguishable from a slow one until this fires.
|
||||
const handshakeTimer = setTimeout(() => {
|
||||
if (!authed) socket.close(1008, 'mesh handshake timeout');
|
||||
}, HANDSHAKE_TIMEOUT_MS);
|
||||
handshakeTimer.unref?.();
|
||||
|
||||
try {
|
||||
for await (const data of socket.inbound) {
|
||||
const raw = String(data);
|
||||
|
||||
// Checked before `decode`, because decoding is the expensive part being defended.
|
||||
if (raw.length > MAX_FRAME_CHARS) {
|
||||
socket.close(1009, 'mesh frame too large');
|
||||
break;
|
||||
}
|
||||
|
||||
let frame: Frame;
|
||||
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
frame = decode(raw);
|
||||
} catch {
|
||||
continue; // undecodable frames are ignored, as before
|
||||
}
|
||||
|
||||
if (!authed) {
|
||||
authed = handleHandshake(socket, frame, deps);
|
||||
if (authed) clearTimeout(handshakeTimer);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -183,6 +234,7 @@ async function serveFrames(
|
||||
} catch {
|
||||
/* socket failed; the disconnect emit below is the same signal a clean close gives */
|
||||
} finally {
|
||||
clearTimeout(handshakeTimer);
|
||||
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
|
||||
}
|
||||
}
|
||||
|
||||
+39
-30
@@ -100,48 +100,57 @@ export function Route(prefix: string): ClassDecorator {
|
||||
};
|
||||
}
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
return (
|
||||
path: string,
|
||||
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
|
||||
): MethodDecorator =>
|
||||
(target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
routes.push({
|
||||
method,
|
||||
path,
|
||||
handlerName: String(propertyKey),
|
||||
transport,
|
||||
export: opts?.export ?? false,
|
||||
duplicates: opts?.duplicates,
|
||||
maxBodyBytes: opts?.maxBodyBytes,
|
||||
maxParts: opts?.maxParts,
|
||||
});
|
||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||
};
|
||||
/**
|
||||
* The shape every route decorator shares: a path, optional per-route overrides, and the
|
||||
* `MethodDecorator` that records them against the controller.
|
||||
*
|
||||
* Named rather than inferred because JSR rejects an inferred type on a public symbol — an inferred
|
||||
* one forces every consumer's type checker to re-derive it from the implementation instead of
|
||||
* reading it from the declaration. It also gives callers a name for the shape.
|
||||
*/
|
||||
export type RouteDecorator = (
|
||||
path: string,
|
||||
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
|
||||
) => MethodDecorator;
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
|
||||
return (path, opts) => (target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
routes.push({
|
||||
method,
|
||||
path,
|
||||
handlerName: String(propertyKey),
|
||||
transport,
|
||||
export: opts?.export ?? false,
|
||||
duplicates: opts?.duplicates,
|
||||
maxBodyBytes: opts?.maxBodyBytes,
|
||||
maxParts: opts?.maxParts,
|
||||
});
|
||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||
};
|
||||
}
|
||||
|
||||
/** Declares a buffered `GET` route. */
|
||||
export const Get = routeDecorator('GET', 'buffer');
|
||||
export const Get: RouteDecorator = routeDecorator('GET', 'buffer');
|
||||
/** Declares a buffered `HEAD` route. */
|
||||
export const Head = routeDecorator('HEAD', 'buffer');
|
||||
export const Head: RouteDecorator = routeDecorator('HEAD', 'buffer');
|
||||
/** Declares a buffered `POST` route. */
|
||||
export const Post = routeDecorator('POST', 'buffer');
|
||||
export const Post: RouteDecorator = routeDecorator('POST', 'buffer');
|
||||
/** Declares a buffered `PUT` route. */
|
||||
export const Put = routeDecorator('PUT', 'buffer');
|
||||
export const Put: RouteDecorator = routeDecorator('PUT', 'buffer');
|
||||
/** Declares a buffered `PATCH` route. */
|
||||
export const Patch = routeDecorator('PATCH', 'buffer');
|
||||
export const Patch: RouteDecorator = routeDecorator('PATCH', 'buffer');
|
||||
/** Declares a buffered `DELETE` route. */
|
||||
export const Delete = routeDecorator('DELETE', 'buffer');
|
||||
export const Delete: RouteDecorator = routeDecorator('DELETE', 'buffer');
|
||||
/** Declares a buffered `OPTIONS` route. */
|
||||
export const Options = routeDecorator('OPTIONS', 'buffer');
|
||||
export const Options: RouteDecorator = routeDecorator('OPTIONS', 'buffer');
|
||||
/** Declares a `GET` route streamed as Server-Sent Events. */
|
||||
export const Sse = routeDecorator('GET', 'sse');
|
||||
export const Sse: RouteDecorator = routeDecorator('GET', 'sse');
|
||||
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
||||
export const Stream = routeDecorator('GET', 'negotiate');
|
||||
export const Stream: RouteDecorator = routeDecorator('GET', 'negotiate');
|
||||
/** Declares a `GET` route upgraded to a WebSocket. */
|
||||
export const Ws = routeDecorator('GET', 'ws');
|
||||
export const Ws: RouteDecorator = routeDecorator('GET', 'ws');
|
||||
|
||||
/** Attaches a response transformer to a handler method. */
|
||||
export function Transformer(fn: TransformerFn): MethodDecorator {
|
||||
|
||||
+30
-19
@@ -32,34 +32,45 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
|
||||
Reflect.defineMetadata(ARGS, map, ctor);
|
||||
}
|
||||
|
||||
function envelope(source: ArgSource) {
|
||||
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
|
||||
(target, methodKey, index) => {
|
||||
const spec: ArgSpec = { index, source };
|
||||
if (Array.isArray(arg)) spec.keys = arg;
|
||||
else if (typeof arg === 'string') spec.key = arg;
|
||||
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
|
||||
/**
|
||||
* The shape every argument decorator shares: an optional key, key list or schema, an optional
|
||||
* second schema, and the `ParameterDecorator` that records the resulting spec.
|
||||
*
|
||||
* Named for the same reason as `RouteDecorator` in `./metadata` — JSR rejects an inferred type on a
|
||||
* public symbol, because consumers would have to re-derive it from the implementation on every check.
|
||||
*/
|
||||
export type ArgDecorator = (
|
||||
arg?: string | string[] | StandardSchemaV1,
|
||||
schema?: StandardSchemaV1,
|
||||
) => ParameterDecorator;
|
||||
|
||||
if (schema !== undefined) {
|
||||
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||
spec.schema = schema;
|
||||
}
|
||||
function envelope(source: ArgSource): ArgDecorator {
|
||||
return (arg, schema) => (target, methodKey, index) => {
|
||||
const spec: ArgSpec = { index, source };
|
||||
if (Array.isArray(arg)) spec.keys = arg;
|
||||
else if (typeof arg === 'string') spec.key = arg;
|
||||
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
|
||||
|
||||
record(target, methodKey, spec);
|
||||
};
|
||||
if (schema !== undefined) {
|
||||
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||
spec.schema = schema;
|
||||
}
|
||||
|
||||
record(target, methodKey, spec);
|
||||
};
|
||||
}
|
||||
|
||||
/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */
|
||||
export const param = envelope('params');
|
||||
export const param: ArgDecorator = envelope('params');
|
||||
/** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */
|
||||
export const query = envelope('query');
|
||||
export const query: ArgDecorator = envelope('query');
|
||||
/** Inject the request body; pass a schema to validate it. */
|
||||
export const body = envelope('body');
|
||||
export const body: ArgDecorator = envelope('body');
|
||||
/** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */
|
||||
export const headers = envelope('headers');
|
||||
export const headers: ArgDecorator = envelope('headers');
|
||||
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
|
||||
export const header = envelope('headers');
|
||||
export const header: ArgDecorator = envelope('headers');
|
||||
|
||||
/** Inject a value produced upstream by a step or provider, addressed by key. */
|
||||
export function needs(key: string): ParameterDecorator {
|
||||
|
||||
+55
-9
@@ -1,4 +1,4 @@
|
||||
import { Bus } from './bus';
|
||||
import { Bus, type Correlation } from './bus';
|
||||
import { renderError, type ErrorRenderer } from './transformers';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import type { TransformerFn, Transport } from './metadata';
|
||||
@@ -45,15 +45,56 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
|
||||
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
|
||||
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
|
||||
*/
|
||||
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> {
|
||||
export async function runSteps(
|
||||
steps: PipelineStep[],
|
||||
seed: Record<string, unknown>,
|
||||
bus: Bus,
|
||||
correlation: Correlation = {},
|
||||
): Promise<any> {
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
const context: any = seed;
|
||||
// One timestamp per boundary, not one pair per step: a step's end is the next one's start, so
|
||||
// N steps need N+1 readings rather than 2N. Measured at 25.2ns vs 45.3ns per step, against a
|
||||
// ~10.19us request — 0.25%, below the 0.3% run-to-run CV of the project's own benchmark, which
|
||||
// is why this is always on instead of hiding behind a flag nobody could tune with evidence.
|
||||
// Hoisted out of the loop: listeners are registered at boot, so re-deciding this per step buys
|
||||
// nothing. When nothing is listening — the common case — the whole block below costs a branch
|
||||
// instead of building four payloads and reading three clocks for an audience of nobody.
|
||||
const watchingEnter = bus.hasListeners('request:step:enter');
|
||||
const watchingLeave = bus.hasListeners('request:step:leave');
|
||||
const watchingError = bus.hasListeners('request:step:error');
|
||||
const timing = watchingLeave || watchingError;
|
||||
let mark = timing ? performance.now() : 0;
|
||||
|
||||
for (const step of steps) {
|
||||
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
|
||||
const output = await step.run(context);
|
||||
Object.assign(context, output);
|
||||
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
|
||||
if (watchingEnter) bus.emit('request:step:enter', { name: step.name, scope: step.origin, ...correlation });
|
||||
|
||||
try {
|
||||
const output = await step.run(context);
|
||||
Object.assign(context, output);
|
||||
} catch (error) {
|
||||
// Emitted here, where the step that failed is still known. The outer catch in runPipeline
|
||||
// only sees "something in the pipeline threw" and used to report `name: 'pipeline'`, which
|
||||
// threw away the one fact the event exists to carry. Rethrown unchanged — this observes.
|
||||
if (watchingError) {
|
||||
bus.emit('request:step:error', {
|
||||
name: step.name,
|
||||
scope: step.origin,
|
||||
error,
|
||||
durationMs: performance.now() - mark,
|
||||
...correlation,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (timing) {
|
||||
const now = performance.now();
|
||||
if (watchingLeave)
|
||||
bus.emit('request:step:leave', { name: step.name, scope: step.origin, durationMs: now - mark, ...correlation });
|
||||
mark = now;
|
||||
}
|
||||
}
|
||||
|
||||
return context;
|
||||
@@ -72,13 +113,14 @@ export async function runPipeline(args: {
|
||||
bus: Bus;
|
||||
transport: Transport;
|
||||
onError?: ErrorRenderer;
|
||||
correlation?: Correlation;
|
||||
}): Promise<PipelineResult> {
|
||||
const { steps, handler, transformer, seed, bus, transport, onError } = args;
|
||||
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args;
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
let context: any = { ...seed };
|
||||
|
||||
try {
|
||||
context = await runSteps(steps, context, bus);
|
||||
context = await runSteps(steps, context, bus, correlation);
|
||||
const result = await handler(context);
|
||||
const streaming = isAsyncIterable(result);
|
||||
const contract = TRANSPORT_RETURN[transport];
|
||||
@@ -95,7 +137,11 @@ export async function runPipeline(args: {
|
||||
const transformed = transformer(result);
|
||||
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
|
||||
} catch (error) {
|
||||
bus.emit('request:step:error', { name: 'pipeline', error });
|
||||
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
|
||||
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
|
||||
// what produces a trace that says a request failed without saying where.
|
||||
if (bus.hasListeners('request:failed'))
|
||||
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
|
||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||
return renderError(
|
||||
error,
|
||||
|
||||
+21
-4
@@ -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' });
|
||||
}
|
||||
@@ -439,6 +439,28 @@ describe('devGraph endpoint', () => {
|
||||
});
|
||||
|
||||
describe('graceful shutdown', () => {
|
||||
// A module whose only route never responds, so shutdown always has something in flight to give
|
||||
// up on — the deadline is the only thing that can end close().
|
||||
const hangModule = () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/hang') hang() {
|
||||
return new Promise(() => {});
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
return M;
|
||||
};
|
||||
|
||||
const listenHanging = async (app: ReturnType<typeof createApp>): Promise<number> => {
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
|
||||
await new Promise((r) => setTimeout(r, 50)); // let the request reach the handler
|
||||
return port;
|
||||
};
|
||||
|
||||
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@@ -464,6 +486,49 @@ describe('graceful shutdown', () => {
|
||||
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
|
||||
reader.cancel().catch(() => {});
|
||||
});
|
||||
|
||||
it('close({ timeoutMs }) forces shutdown when a handler never responds', async () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/hang') hang() {
|
||||
return new Promise(() => {}); // never resolves — simulates a stuck handler
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
|
||||
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
const start = Date.now();
|
||||
await app.close({ timeoutMs: 300 });
|
||||
expect(Date.now() - start).toBeLessThan(600);
|
||||
});
|
||||
|
||||
// The app-level default exists for the case where close() is reached from a signal handler or a
|
||||
// test helper nobody local owns, so it has to work with close() called bare.
|
||||
it('createApp({ shutdownTimeoutMs }) applies when close() is called with no options', async () => {
|
||||
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 300 });
|
||||
await listenHanging(app);
|
||||
|
||||
const start = Date.now();
|
||||
await app.close();
|
||||
expect(Date.now() - start).toBeLessThan(600);
|
||||
});
|
||||
|
||||
// The interesting half of the precedence rule: an app-level default long enough to fail this
|
||||
// test if it won, so the assertion can only pass if the per-call value took priority.
|
||||
it('close({ timeoutMs }) overrides the app-level default', async () => {
|
||||
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 30_000 });
|
||||
await listenHanging(app);
|
||||
|
||||
const start = Date.now();
|
||||
await app.close({ timeoutMs: 300 });
|
||||
expect(Date.now() - start).toBeLessThan(600);
|
||||
});
|
||||
});
|
||||
|
||||
describe('overrides', () => {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Reconnection under the real Bun runtime.
|
||||
//
|
||||
// Separate from the Node and Deno suites deliberately. Bun's WebSocket lifecycle is a third
|
||||
// implementation — its socket events land on a server-level handler rather than the socket — and a
|
||||
// link that swaps its socket underneath a live graph is precisely where three implementations
|
||||
// stop behaving the same. Defining this on Node and hoping is not enough.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { runtime: 'bun' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
|
||||
function freePort(): number {
|
||||
const probe = Bun.serve({ port: 0, fetch: () => new Response('') });
|
||||
const { port } = probe;
|
||||
probe.stop(true);
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
|
||||
function startTeapot(port: number) {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = serveBun(app, { port });
|
||||
|
||||
return {
|
||||
stop: async () => {
|
||||
server.stop(true);
|
||||
await app.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
|
||||
const port = freePort();
|
||||
let teapot = startTeapot(port);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: {
|
||||
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
|
||||
heartbeatMs: 50,
|
||||
timeoutMs: 2000,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||
expect(before.status).toBe(200);
|
||||
|
||||
await teapot.stop();
|
||||
await settle(100);
|
||||
|
||||
// the down window answers immediately rather than waiting out timeoutMs
|
||||
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||
expect(down.status).toBe(503);
|
||||
|
||||
teapot = startTeapot(port);
|
||||
await settle(400);
|
||||
|
||||
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||
expect(after.status).toBe(200);
|
||||
expect((await after.json()).auth).toEqual({ token: 'xyz' });
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// Real Bun integration test for the bounded close() serveBun returns. app.close() cannot do this
|
||||
// job on Bun — it returns at its `if (!server)` guard, because a Bun app is served through
|
||||
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
|
||||
// handle. See issue #15.
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Get, Module } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/hang')
|
||||
hang() {
|
||||
return new Promise(() => {}); // never resolves — a stuck handler
|
||||
}
|
||||
@Get('/slow')
|
||||
async slow() {
|
||||
await Bun.sleep(200); // finite, so draining has something real to wait out
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
|
||||
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
|
||||
await Bun.sleep(50); // let the request actually reach the handler
|
||||
|
||||
const start = Date.now();
|
||||
await server.close({ timeoutMs: 300 });
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
// The assertion that matters is the upper bound: without the deadline this never returns.
|
||||
expect(elapsed).toBeLessThan(2000);
|
||||
expect(elapsed).toBeGreaterThanOrEqual(250);
|
||||
});
|
||||
|
||||
test('serveBun close() drains an in-flight request rather than cutting it', async () => {
|
||||
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
|
||||
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
|
||||
|
||||
await server.close({ timeoutMs: 5000 });
|
||||
|
||||
expect(await inFlight).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
// D7 of the teardown design: proving the Node path works proves nothing here, because app.close()
|
||||
// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses.
|
||||
test('serveBun close() runs registered teardown', async () => {
|
||||
const closed: string[] = [];
|
||||
const app = createApp({
|
||||
modules: [M],
|
||||
hooks: [{ onShutdown: () => void closed.push('hook') }],
|
||||
plugins: [(api) => api.onShutdown(async () => {
|
||||
await Bun.sleep(10);
|
||||
closed.push('plugin');
|
||||
})],
|
||||
});
|
||||
const server = serveBun(app, { port: 0 });
|
||||
|
||||
await server.close({ timeoutMs: 2000 });
|
||||
|
||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||
expect(closed).toEqual(['plugin', 'hook']);
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// The teapot's frame loop under Deno, driven by a raw client rather than by another green-tea.
|
||||
//
|
||||
// The two guards here are close-code behaviour, and close codes are exactly where the runtimes
|
||||
// have already differed once — a client may only send 1000 or 3000-4999, which is why the mesh
|
||||
// heartbeat uses 4011 instead of 1011. Server-side closes deserve the same suspicion.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Step, Module } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run() {
|
||||
return { auth: { ok: true } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
async function startTeapot() {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
let port = 0;
|
||||
const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
||||
}
|
||||
|
||||
/** Opens a raw control-channel socket and resolves with how it ended. */
|
||||
function rawClient(port: number, send: string): Promise<{ code: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`);
|
||||
ws.onopen = () => ws.send(send);
|
||||
ws.onclose = (event) => resolve({ code: event.code });
|
||||
ws.onerror = () => reject(new Error('socket errored'));
|
||||
});
|
||||
}
|
||||
|
||||
Deno.test('mesh on Deno: the teapot hangs up on an oversized control frame', async () => {
|
||||
const teapot = await startTeapot();
|
||||
|
||||
try {
|
||||
// over the 4,000,000-character cap, and sent by a peer that has not authenticated
|
||||
const oversized = `{"type":"hello","v":1,"secret":"${'a'.repeat(4_000_001)}"}`;
|
||||
const { code } = await rawClient(teapot.port(), oversized);
|
||||
|
||||
assertEquals(code, 1009);
|
||||
} finally {
|
||||
await teapot.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
// Reconnection under the real Deno runtime.
|
||||
//
|
||||
// This exists separately from the Node suite because the teacup's WebSocket client is a different
|
||||
// implementation here — Deno's global `WebSocket`, not the `ws` package — and a link that swaps its
|
||||
// socket underneath a live graph is exactly the kind of thing that works on one and not the other.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { runtime: 'deno' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
|
||||
function freePort(): number {
|
||||
const probe = Deno.listen({ port: 0 });
|
||||
const { port } = probe.addr as Deno.NetAddr;
|
||||
probe.close();
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
|
||||
async function startTeapot(port: number) {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = serveDeno(app, { port });
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
return {
|
||||
stop: async () => {
|
||||
await server.shutdown();
|
||||
await app.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async () => {
|
||||
const port = freePort();
|
||||
let teapot = await startTeapot(port);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: {
|
||||
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
|
||||
heartbeatMs: 50,
|
||||
timeoutMs: 2000,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||
assertEquals(before.status, 200);
|
||||
|
||||
await teapot.stop();
|
||||
await settle(100);
|
||||
|
||||
// the down window answers immediately rather than waiting out timeoutMs
|
||||
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||
assertEquals(down.status, 503);
|
||||
|
||||
teapot = await startTeapot(port);
|
||||
await settle(400);
|
||||
|
||||
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||
assertEquals(after.status, 200);
|
||||
assertEquals((await after.json()).auth, { token: 'xyz' });
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
// Real Deno integration test for the bounded close() serveDeno returns. app.close() cannot do this
|
||||
// job on Deno — it returns at its `if (!server)` guard, because a Deno app is served through
|
||||
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
|
||||
// handle. See issue #15.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Route, Get, Module } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/hang')
|
||||
hang() {
|
||||
return new Promise(() => {}); // never resolves — a stuck handler
|
||||
}
|
||||
@Get('/slow')
|
||||
async slow() {
|
||||
await new Promise((r) => setTimeout(r, 200)); // finite, so draining has something real to wait out
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const portOf = (server: { addr?: { port: number } }): number => server.addr!.port;
|
||||
|
||||
// On Deno the deadline bounds the wait, not the connections — see the comment on serveDeno's
|
||||
// force callback. This test asserts exactly that: close() returns on time, and does so without
|
||||
// the uncaught BadResource that aborting a draining server produces. The test runner fails on
|
||||
// that error even when the assertions pass, so a green run here is the real assertion.
|
||||
Deno.test('serveDeno close({ timeoutMs }) returns on a stuck handler without forcing', async () => {
|
||||
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
|
||||
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
|
||||
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
|
||||
|
||||
const start = Date.now();
|
||||
await server.close({ timeoutMs: 300 });
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
// The assertion that matters is the upper bound: without the deadline this never returns.
|
||||
if (elapsed >= 2000) throw new Error(`close() took ${elapsed}ms — the deadline did not fire`);
|
||||
if (elapsed < 250) throw new Error(`close() returned in ${elapsed}ms — it did not wait the deadline`);
|
||||
});
|
||||
|
||||
Deno.test('serveDeno close() drains an in-flight request rather than cutting it', async () => {
|
||||
const server = serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
|
||||
const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json());
|
||||
await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close
|
||||
|
||||
await server.close({ timeoutMs: 5000 });
|
||||
|
||||
const body = await inFlight;
|
||||
if (body.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(body)}`);
|
||||
});
|
||||
|
||||
Deno.test('a caller-supplied signal still aborts the server', async () => {
|
||||
const ac = new AbortController();
|
||||
const server = serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} });
|
||||
|
||||
ac.abort();
|
||||
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
|
||||
});
|
||||
|
||||
// D7 of the teardown design: a teardown must run on every runtime that has a shutdown, and it must
|
||||
// run from the close() the runtime actually uses. app.close() returns at its no-server guard here,
|
||||
// so proving the Node path works proves nothing about this one — hence a Deno assertion of its own.
|
||||
Deno.test('serveDeno close() runs registered teardown', async () => {
|
||||
const closed: string[] = [];
|
||||
const app = createApp({
|
||||
modules: [M],
|
||||
hooks: [{ onShutdown: () => void closed.push('hook') }],
|
||||
plugins: [(api) => api.onShutdown(async () => {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
closed.push('plugin');
|
||||
})],
|
||||
});
|
||||
const server = serveDeno(app, { port: 0 });
|
||||
|
||||
await server.close({ timeoutMs: 2000 });
|
||||
|
||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
|
||||
});
|
||||
+21
-2
@@ -112,18 +112,37 @@ describe('request hardening', () => {
|
||||
const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) });
|
||||
expect(res.status).toBe(413);
|
||||
expect(ran).toBe(false);
|
||||
// Load-bearing, not cosmetic: without it the rest of the upload keeps arriving on a
|
||||
// kept-alive socket after the response. Node-only — `Connection` is a forbidden response
|
||||
// header on the fetch side, which is why the adapter attaches it rather than the shared core.
|
||||
expect(res.headers.get('connection')).toBe('close');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('sets the configured server timeouts', async () => {
|
||||
it('sets the configured server timeouts and connection limit', async () => {
|
||||
const server = createHttpServer([], [], undefined, undefined,
|
||||
{ limits: { requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
||||
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
||||
expect(server.maxConnections).toBe(2468);
|
||||
expect(server.requestTimeout).toBe(12345);
|
||||
expect(server.headersTimeout).toBe(6789);
|
||||
expect(server.keepAliveTimeout).toBe(4321);
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('caps concurrent connections by default', () => {
|
||||
const server = createHttpServer([]);
|
||||
expect(server.maxConnections).toBe(1000);
|
||||
server.close();
|
||||
});
|
||||
|
||||
it.each([0, -1])('treats maxConnections=%i as unlimited', (maxConnections) => {
|
||||
const server = createHttpServer([], [], undefined, undefined, {
|
||||
limits: { maxConnections },
|
||||
});
|
||||
expect(server.maxConnections).toBeUndefined();
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
|
||||
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
|
||||
const server = createHttpServer(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { createApp, createDefaultLogger, logRequests, Route, Get, Step, Module, Provider, needs } from '../src/index';
|
||||
import type { Logger, LogFields } from '../src/index';
|
||||
|
||||
/** Captures every call so a test can assert on what core wrote rather than on console output. */
|
||||
function recordingLogger(): Logger & { records: Array<{ level: string; message: string; fields?: LogFields }> } {
|
||||
const records: Array<{ level: string; message: string; fields?: LogFields }> = [];
|
||||
const at =
|
||||
(level: string) =>
|
||||
(message: string, fields?: LogFields): void => {
|
||||
records.push({ level, message, fields });
|
||||
};
|
||||
|
||||
return { records, debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('default logger', () => {
|
||||
it('writes one JSON object per record when not on a TTY', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
createDefaultLogger(false).warn('something happened', { route: '/x', count: 2 });
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
const written = JSON.parse(spy.mock.calls[0][0] as string);
|
||||
expect(written).toMatchObject({ level: 'warn', name: 'green-tea', msg: 'something happened', route: '/x', count: 2 });
|
||||
// A log aggregator filters on a field; it cannot filter on a substring of prose.
|
||||
expect(written.msg).not.toContain('[green-tea]');
|
||||
expect(typeof written.time).toBe('string');
|
||||
});
|
||||
|
||||
it('writes a readable line instead when interactive', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
createDefaultLogger(true).warn('something happened', { route: '/x' });
|
||||
|
||||
const written = spy.mock.calls[0][0] as string;
|
||||
expect(written).toBe('[green-tea] WARN something happened route=/x');
|
||||
});
|
||||
|
||||
it('routes each level to the matching console method', () => {
|
||||
const spies = {
|
||||
debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
|
||||
info: vi.spyOn(console, 'info').mockImplementation(() => {}),
|
||||
warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
|
||||
error: vi.spyOn(console, 'error').mockImplementation(() => {}),
|
||||
};
|
||||
const logger = createDefaultLogger(false);
|
||||
logger.debug('d');
|
||||
logger.info('i');
|
||||
logger.warn('w');
|
||||
logger.error('e');
|
||||
|
||||
for (const spy of Object.values(spies)) expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createApp({ logger })', () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/ok')
|
||||
ok() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
it('sends framework diagnostics to the supplied logger, not to console', async () => {
|
||||
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const logger = recordingLogger();
|
||||
const app = createApp({ modules: [M], logger });
|
||||
|
||||
// close({ timeoutMs }) on an app that never listen()ed is one of the diagnostics core emits.
|
||||
await app.close({ timeoutMs: 100 });
|
||||
|
||||
expect(logger.records).toHaveLength(1);
|
||||
expect(logger.records[0].level).toBe('warn');
|
||||
expect(logger.records[0].message).toContain('has no listen()ed server');
|
||||
// The point of the contract: nothing reached console behind the logger's back.
|
||||
expect(consoleWarn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('exposes the logger on the app so adapters and plugins share it', () => {
|
||||
const logger = recordingLogger();
|
||||
expect(createApp({ modules: [M], logger }).logger).toBe(logger);
|
||||
});
|
||||
|
||||
it('warns about a deep dependency chain through the logger, with structured fields', () => {
|
||||
const logger = recordingLogger();
|
||||
|
||||
@Step({ provides: 's0' })
|
||||
class S0 {
|
||||
run() {
|
||||
return { s0: 0 };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 's1', needs: ['s0'] })
|
||||
class S1 {
|
||||
run() {
|
||||
return { s1: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/deep')
|
||||
class DeepCtl {
|
||||
@Get('/go')
|
||||
go(@needs('s1') s: unknown) {
|
||||
return { s };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [S0, S1], controllers: [DeepCtl] })
|
||||
class DeepModule {}
|
||||
|
||||
createApp({ modules: [DeepModule], logger, warnGraphDepth: 1 });
|
||||
|
||||
const warned = logger.records.find((r) => r.message.includes('unusually deep'));
|
||||
expect(warned).toBeDefined();
|
||||
// Structured, so a dashboard can group by route instead of parsing the sentence.
|
||||
expect(warned!.fields).toMatchObject({ route: '/deep/go', method: 'GET', depth: 2, threshold: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('request logging', () => {
|
||||
@Route('/api')
|
||||
class Ctl {
|
||||
@Get('/ok')
|
||||
ok() {
|
||||
return { ok: true };
|
||||
}
|
||||
@Get('/boom')
|
||||
boom(): never {
|
||||
throw new Error('handler exploded');
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
it('is off unless asked for', async () => {
|
||||
const logger = recordingLogger();
|
||||
const app = createApp({ modules: [M], logger });
|
||||
|
||||
await app.fetch(new Request('http://x/api/ok'));
|
||||
|
||||
// A framework that writes to stdout uninvited is one you must configure before using.
|
||||
expect(logger.records).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('logs one info per completed request, with the pattern and a duration', async () => {
|
||||
const logger = recordingLogger();
|
||||
const app = createApp({ modules: [M], logger, logRequests: true });
|
||||
|
||||
await app.fetch(new Request('http://x/api/ok'));
|
||||
|
||||
expect(logger.records).toHaveLength(1);
|
||||
const [record] = logger.records;
|
||||
expect(record.level).toBe('info');
|
||||
expect(record.fields).toMatchObject({ route: '/api/ok', method: 'GET', status: 200 });
|
||||
expect(typeof record.fields!.requestId).toBe('string');
|
||||
expect(record.fields!.durationMs).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('logs an error for a failed request, correlated with it', async () => {
|
||||
const logger = recordingLogger();
|
||||
const app = createApp({ modules: [M], logger, logRequests: true });
|
||||
|
||||
await app.fetch(new Request('http://x/api/boom'));
|
||||
|
||||
const failed = logger.records.find((r) => r.level === 'error');
|
||||
expect(failed).toBeDefined();
|
||||
expect(failed!.fields).toMatchObject({ route: '/api/boom', error: 'handler exploded' });
|
||||
|
||||
// Same request, so the failure and the completion carry one identity between them.
|
||||
const completed = logger.records.find((r) => r.level === 'info');
|
||||
expect(completed!.fields!.requestId).toBe(failed!.fields!.requestId);
|
||||
});
|
||||
|
||||
it('unsubscribes, so it is removable and not just optional', async () => {
|
||||
const logger = recordingLogger();
|
||||
const app = createApp({ modules: [M], logger });
|
||||
const stop = logRequests(app.bus, logger);
|
||||
|
||||
await app.fetch(new Request('http://x/api/ok'));
|
||||
expect(logger.records).toHaveLength(1);
|
||||
|
||||
stop();
|
||||
await app.fetch(new Request('http://x/api/ok'));
|
||||
expect(logger.records).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps writing, and keeps serving, when the logger throws on every call', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const exploding: Logger = {
|
||||
debug: () => {
|
||||
throw new Error('logger is broken');
|
||||
},
|
||||
info: () => {
|
||||
throw new Error('logger is broken');
|
||||
},
|
||||
warn: () => {
|
||||
throw new Error('logger is broken');
|
||||
},
|
||||
error: () => {
|
||||
throw new Error('logger is broken');
|
||||
},
|
||||
};
|
||||
const app = createApp({ modules: [M], logger: exploding, logRequests: true });
|
||||
|
||||
const res = await app.fetch(new Request('http://x/api/ok'));
|
||||
|
||||
// The request is unharmed: Bus.emit isolates listener failures by design.
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
|
||||
// And the failure is not silent, which is what the wrapper buys on top of that guarantee.
|
||||
expect(consoleError).toHaveBeenCalled();
|
||||
const written = JSON.parse(consoleError.mock.calls[0][0] as string);
|
||||
expect(written.msg).toContain('the configured logger threw');
|
||||
expect(written.error).toBe('logger is broken');
|
||||
});
|
||||
});
|
||||
|
||||
describe('logger as a dependency', () => {
|
||||
it('is injectable with @needs("logger") and is the same instance', async () => {
|
||||
const logger = recordingLogger();
|
||||
let seen: unknown;
|
||||
|
||||
@Provider({ provides: 'noop' })
|
||||
class Noop {
|
||||
provide() {
|
||||
return { noop: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/log')
|
||||
log(@needs('logger') injected: Logger) {
|
||||
seen = injected;
|
||||
injected.info('from a handler', { where: 'handler' });
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [Noop], controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M], logger });
|
||||
await app.fetch(new Request('http://x/log'));
|
||||
|
||||
// One object, two access paths — not a second logger wired into the graph.
|
||||
expect(seen).toBe(logger);
|
||||
expect(logger.records).toContainEqual({ level: 'info', message: 'from a handler', fields: { where: 'handler' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run() {
|
||||
return { auth: { ok: true } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('auth') auth: any) {
|
||||
return { auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const collect = () => {
|
||||
const lines: string[] = [];
|
||||
return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } };
|
||||
};
|
||||
|
||||
describe('mesh boot retry', () => {
|
||||
it('waits for a teapot that starts late, rather than failing the deploy', async () => {
|
||||
const port = await new Promise<number>((resolve) => {
|
||||
const probe = require('node:net').createServer();
|
||||
probe.listen(0, () => {
|
||||
const { port: p } = probe.address();
|
||||
probe.close(() => resolve(p));
|
||||
});
|
||||
});
|
||||
const { lines, logger } = collect();
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: {
|
||||
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }],
|
||||
timeoutMs: 500,
|
||||
bootTimeoutMs: 4000,
|
||||
},
|
||||
});
|
||||
|
||||
// the teapot arrives *after* the teacup has already started trying
|
||||
const pending = teacup.fetch(new Request('http://x/api/local/who'));
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
const server = await teapot.listen(port);
|
||||
|
||||
try {
|
||||
const res = await pending;
|
||||
expect(res.status).toBe(200);
|
||||
expect(lines.some((l) => l.includes('of boot budget left'))).toBe(true);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
it('still fails the boot once the budget is spent — a needed provider is not optional', async () => {
|
||||
const { lines, logger } = collect();
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: {
|
||||
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
|
||||
timeoutMs: 200,
|
||||
bootTimeoutMs: 600,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||
expect(lines.some((l) => l.includes('giving up after'))).toBe(true);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
it('does not retry a wrong secret — the teapot refused, and it will refuse again', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
const { lines, logger } = collect();
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: {
|
||||
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'WRONG' }],
|
||||
timeoutMs: 500,
|
||||
bootTimeoutMs: 30_000,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const started = Date.now();
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||
// with a 30s budget, retrying would have taken 30s to reach the same error
|
||||
expect(Date.now() - started).toBeLessThan(3000);
|
||||
expect(lines.some((l) => l.includes('refused this peer'))).toBe(true);
|
||||
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
}, 40_000);
|
||||
|
||||
it('bootTimeoutMs: 0 makes one attempt, as before', async () => {
|
||||
const { lines, logger } = collect();
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: {
|
||||
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
|
||||
timeoutMs: 200,
|
||||
bootTimeoutMs: 0,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
}
|
||||
}, 15_000);
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { connectLink } from '../../src/mesh/link';
|
||||
import { envelopeFrom } from '../../src/mesh/teacup';
|
||||
import { createMeshControl } from '../../src/mesh/teapot';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||
import { Bus } from '../../src/bus';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('auth') auth: any) {
|
||||
return { auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const V = MESH_PROTOCOL_VERSION;
|
||||
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||
|
||||
/** Drives a control handler with a scripted socket, capturing what it sends and how it closes. */
|
||||
function fakeSocket() {
|
||||
const queue: string[] = [];
|
||||
let push: ((v: string) => void) | undefined;
|
||||
let done = false;
|
||||
const sent: string[] = [];
|
||||
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||
|
||||
return {
|
||||
sent,
|
||||
closes,
|
||||
feed: (frame: string) => (push ? push(frame) : queue.push(frame)),
|
||||
end: () => {
|
||||
done = true;
|
||||
push?.('');
|
||||
},
|
||||
socket: {
|
||||
get isOpen() {
|
||||
return !done;
|
||||
},
|
||||
abort: new AbortController().signal,
|
||||
send: (data: string) => sent.push(data),
|
||||
close: (code?: number, reason?: string) => {
|
||||
closes.push({ code, reason });
|
||||
done = true;
|
||||
},
|
||||
terminate: () => undefined,
|
||||
inbound: {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
while (!done) {
|
||||
if (queue.length) {
|
||||
yield queue.shift()!;
|
||||
continue;
|
||||
}
|
||||
const next = await new Promise<string>((resolve) => (push = resolve));
|
||||
if (done) return;
|
||||
yield next;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
describe('envelopeFrom', () => {
|
||||
it('carries the url and the caller correlation off ctx.req', () => {
|
||||
const envelope = envelopeFrom({
|
||||
req: { method: 'POST', url: '/orders/7?x=1', requestId: 'req-1', traceId: 'trace-1' },
|
||||
params: { id: '7' },
|
||||
query: { x: '1' },
|
||||
headers: { 'x-token': 'abc' },
|
||||
body: { total: 10 },
|
||||
});
|
||||
|
||||
expect(envelope.url).toBe('/orders/7?x=1');
|
||||
expect(envelope.correlation).toEqual({ requestId: 'req-1', traceId: 'trace-1' });
|
||||
expect(envelope.method).toBe('POST');
|
||||
});
|
||||
|
||||
it('omits correlation entirely when the caller has none, rather than sending an empty one', () => {
|
||||
expect(envelopeFrom({ req: { method: 'GET', url: '/x' } })).not.toHaveProperty('correlation');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mesh rpc errors', () => {
|
||||
it('reports the token that failed, not the wire id', async () => {
|
||||
const wss = new WebSocketServer({ port: 0 });
|
||||
wss.on('connection', (ws) => {
|
||||
let authed = false;
|
||||
ws.on('message', (data) => {
|
||||
const frame = decode(data.toString());
|
||||
if (!authed && frame.type === 'hello') {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
|
||||
return;
|
||||
}
|
||||
if (frame.type === 'rpc-req') {
|
||||
ws.send(encode({ type: 'rpc-res', id: frame.id, ok: false, error: { message: 'nope', status: 403 } }));
|
||||
}
|
||||
});
|
||||
});
|
||||
const port = (wss.address() as { port: number }).port;
|
||||
const bus = new Bus();
|
||||
const seen: string[] = [];
|
||||
bus.on('mesh:rpc:error', (payload) => seen.push(String(payload.name)));
|
||||
|
||||
const link = await connectLink({ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x', bus });
|
||||
await expect(link.rpc('scope', 'billing', env)).rejects.toMatchObject({ status: 403 });
|
||||
|
||||
// used to be "0" — the per-link counter — which no operator could match to anything
|
||||
expect(seen).toEqual(['billing']);
|
||||
link.close();
|
||||
wss.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('teapot hardening', () => {
|
||||
const control = () =>
|
||||
createMeshControl({
|
||||
secret: 'good',
|
||||
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
|
||||
resolveScope: async () => 'value',
|
||||
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
|
||||
});
|
||||
|
||||
it('hangs up on an oversized frame before parsing it', async () => {
|
||||
const fake = fakeSocket();
|
||||
const running = control().handle(fake.socket as never);
|
||||
|
||||
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
|
||||
await running;
|
||||
|
||||
expect(fake.closes[0]?.code).toBe(1009);
|
||||
// never answered: the frame died before decode, so no manifest went out
|
||||
expect(fake.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('serves normally when a frame is under the cap', async () => {
|
||||
const fake = fakeSocket();
|
||||
const running = control().handle(fake.socket as never);
|
||||
|
||||
fake.feed(encode({ type: 'hello', v: V, secret: 'good' }));
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
fake.end();
|
||||
await running;
|
||||
|
||||
expect(JSON.parse(fake.sent[0]).type).toBe('manifest');
|
||||
});
|
||||
});
|
||||
|
||||
describe('correlation across the mesh', () => {
|
||||
it("the teapot's own events carry the caller's request id, not one it opened itself", async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
|
||||
// what the teapot reports about its *own* work — the far end of the trace
|
||||
const far: Array<string | undefined> = [];
|
||||
teapot.bus.on('request:step:leave', (payload) => far.push(payload.requestId));
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||
});
|
||||
|
||||
try {
|
||||
// the id a gateway would have set; core adopts it rather than minting a new one
|
||||
const res = await teacup.fetch(
|
||||
new Request('http://x/api/local/who', { headers: { 'x-request-id': 'from-the-gateway' } }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
expect(far.length).toBeGreaterThan(0);
|
||||
// before this change the teapot saw no id at all, so a request crossing the mesh
|
||||
// became two unrelated investigations
|
||||
expect(new Set(far)).toEqual(new Set(['from-the-gateway']));
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleartext secret warning', () => {
|
||||
it('warns for a remote ws:// teapot, and stays quiet for loopback', async () => {
|
||||
const remote: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => remote.push(m), error() {} };
|
||||
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
|
||||
// loopback: there is no network path, so nothing to warn about
|
||||
const local = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||
});
|
||||
|
||||
try {
|
||||
await local.fetch(new Request('http://x/api/local/who'));
|
||||
expect(remote.filter((m) => m.includes('not encrypted'))).toEqual([]);
|
||||
} finally {
|
||||
await local.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('warns when the secret would cross a network in cleartext', async () => {
|
||||
const warned: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => warned.push(m), error() {} };
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
// unreachable on purpose: the warning is emitted before the connection is attempted,
|
||||
// because it is about what would be sent, not about what succeeded
|
||||
mesh: { teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], timeoutMs: 300 },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
|
||||
} finally {
|
||||
await teacup.close();
|
||||
}
|
||||
|
||||
expect(warned.some((m) => m.includes('not encrypted') && m.includes('wss://'))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { connectLink, missingFromManifest } from '../../src/mesh/link';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest } from '../../src/mesh/protocol';
|
||||
|
||||
const V = MESH_PROTOCOL_VERSION;
|
||||
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||
|
||||
/**
|
||||
* A teapot bound to a fixed port so it can be killed and restarted at the same URL — which is the
|
||||
* whole point here: reconnection means returning to the *same* teapot, not finding another one.
|
||||
* Its manifest is swappable so a restart can come back exporting something different.
|
||||
*/
|
||||
function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true }) {
|
||||
const wss = new WebSocketServer({ port });
|
||||
wss.on('connection', (ws) => {
|
||||
let authed = false;
|
||||
ws.on('message', (d) => {
|
||||
const frame = decode(d.toString());
|
||||
if (!authed) {
|
||||
if (frame.type === 'hello' && frame.secret === 'good') {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
|
||||
} else ws.close(1008);
|
||||
return;
|
||||
}
|
||||
if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
|
||||
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: answer }));
|
||||
});
|
||||
});
|
||||
|
||||
return new Promise<{ close: () => Promise<void> }>((resolve) => {
|
||||
wss.on('listening', () =>
|
||||
resolve({
|
||||
close: () =>
|
||||
new Promise<void>((done) => {
|
||||
for (const client of wss.clients) client.terminate();
|
||||
wss.close(() => done());
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** A free port, taken by opening and immediately closing a server on port 0. */
|
||||
async function freePort(): Promise<number> {
|
||||
const probe = new WebSocketServer({ port: 0 });
|
||||
await new Promise((r) => probe.on('listening', r));
|
||||
const port = (probe.address() as { port: number }).port;
|
||||
await new Promise((r) => probe.close(r));
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
|
||||
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
|
||||
|
||||
describe('mesh reconnection', () => {
|
||||
it('reconnects to the same teapot and serves again', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
|
||||
|
||||
await teapot.close();
|
||||
await settle(50);
|
||||
// the window where the link is down answers immediately rather than after timeoutMs
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
|
||||
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
|
||||
await settle(300);
|
||||
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
|
||||
link.close();
|
||||
await teapot.close();
|
||||
});
|
||||
|
||||
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
const warnings: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
|
||||
|
||||
await teapot.close();
|
||||
await settle(50);
|
||||
|
||||
// comes back exporting nothing — the graph was validated against 'auth' at boot
|
||||
teapot = await teapotOn(port, { scopes: [], routes: [] });
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
|
||||
// logged once per distinct manifest, not once per attempt
|
||||
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
|
||||
|
||||
link.close();
|
||||
await teapot.close();
|
||||
});
|
||||
|
||||
it('stops reconnecting once the application closes the link', async () => {
|
||||
const port = await freePort();
|
||||
const teapot = await teapotOn(port, SCOPES);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||
|
||||
await teapot.close();
|
||||
link.close();
|
||||
|
||||
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
|
||||
// which is what would leave app.close() with a process that cannot exit
|
||||
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
await revived.close();
|
||||
});
|
||||
|
||||
it('reconnect: false keeps the old fail-once behaviour', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
|
||||
|
||||
await teapot.close();
|
||||
teapot = await teapotOn(port, SCOPES);
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
link.close();
|
||||
await teapot.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('missingFromManifest', () => {
|
||||
const booted: Manifest = {
|
||||
scopes: [
|
||||
{ token: 'auth', scope: 'request' },
|
||||
{ token: 'config', scope: 'app' },
|
||||
],
|
||||
routes: [{ method: 'GET', pattern: '/svc/:id' }],
|
||||
};
|
||||
|
||||
it('accepts an identical manifest', () => {
|
||||
expect(missingFromManifest(booted, booted)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
|
||||
const wider: Manifest = {
|
||||
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
|
||||
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
|
||||
};
|
||||
expect(missingFromManifest(booted, wider)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts a route parameter that was only renamed', () => {
|
||||
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
|
||||
expect(missingFromManifest(booted, renamed)).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
|
||||
const flipped: Manifest = {
|
||||
scopes: [
|
||||
{ token: 'auth', scope: 'app' },
|
||||
{ token: 'config', scope: 'app' },
|
||||
],
|
||||
routes: booted.routes,
|
||||
};
|
||||
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
|
||||
});
|
||||
|
||||
it('reports a missing route by method and pattern', () => {
|
||||
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
|
||||
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Route, Get, Module, needs } from '../../src/index';
|
||||
import { untransportable } from '../../src/mesh/protocol';
|
||||
|
||||
describe('untransportable', () => {
|
||||
it('passes the shapes JSON actually round-trips', () => {
|
||||
expect(untransportable({ a: 1, b: 'x', c: true, d: null, e: [1, { f: 2 }] })).toBeUndefined();
|
||||
expect(untransportable([])).toBeUndefined();
|
||||
expect(untransportable('plain')).toBeUndefined();
|
||||
expect(untransportable(Object.create(null))).toBeUndefined();
|
||||
});
|
||||
|
||||
it('names the class whose identity JSON would discard, and where it sits', () => {
|
||||
class RemotePool {
|
||||
query() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
expect(untransportable({ db: new RemotePool() })).toEqual({ path: 'result.db', what: 'a RemotePool instance' });
|
||||
expect(untransportable({ seen: new Map() })).toEqual({ path: 'result.seen', what: 'a Map instance' });
|
||||
// refused rather than quietly delivered as a string, which is the same silent difference smaller
|
||||
expect(untransportable({ at: new Date() })).toEqual({ path: 'result.at', what: 'a Date instance' });
|
||||
});
|
||||
|
||||
it('finds behaviour nested in arrays and objects', () => {
|
||||
expect(untransportable({ list: [1, { run: () => 1 }] })).toEqual({
|
||||
path: 'result.list[1].run',
|
||||
what: 'a function',
|
||||
});
|
||||
});
|
||||
|
||||
it('gives up rather than rejecting a payload too large to check', () => {
|
||||
const huge: Record<string, unknown> = {};
|
||||
for (let i = 0; i < 11_000; i++) huge[`k${i}`] = i;
|
||||
huge.late = () => 1; // past the budget: assumed fine rather than turned into an error
|
||||
|
||||
expect(untransportable(huge)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
class Pool {
|
||||
query(sql: string) {
|
||||
return `ran:${sql}`;
|
||||
}
|
||||
}
|
||||
|
||||
@Provider({ provides: 'db', export: true })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: new Pool() };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class Ctl {
|
||||
@Get('/use')
|
||||
use(@needs('db') db: any) {
|
||||
return { got: typeof db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class TeacupModule {}
|
||||
|
||||
describe('exporting a handle over the mesh', () => {
|
||||
it('fails with a message naming the token, instead of delivering an empty object', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'x' } });
|
||||
const server = await teapot.listen(0);
|
||||
const port = (server.address() as { port: number }).port;
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] },
|
||||
});
|
||||
|
||||
try {
|
||||
// before this guard: HTTP 200 with `{}` — an object that passes any truthiness check and
|
||||
// then throws "db.query is not a function" somewhere else entirely
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/use'))).rejects.toThrow(
|
||||
/mesh cannot transport 'db'[\s\S]*Pool instance/,
|
||||
);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// The `engines` floor is `>=18`, and the global `crypto` only arrived unflagged in Node 19. That gap
|
||||
// shipped once: `correlateRequest` compiled cleanly against an ambient declaration and then threw
|
||||
// `ReferenceError: crypto is not defined` on the first request of every Node 18 process.
|
||||
//
|
||||
// CI's Node 18 job is what caught it, and this test is what makes it catchable without one — every
|
||||
// developer machine and every other runtime has the global, so the bug is invisible where it is
|
||||
// written. Stubbing the global away reproduces the floor's condition on any Node.
|
||||
//
|
||||
// If the floor ever moves above 18, this test and the fallback it guards can both go.
|
||||
describe('correlateRequest without a global crypto (Node 18)', () => {
|
||||
it('falls back to node:crypto instead of throwing ReferenceError', async () => {
|
||||
vi.stubGlobal('crypto', undefined);
|
||||
vi.resetModules();
|
||||
|
||||
const { correlateRequest } = await import('../src/http/core');
|
||||
const a = correlateRequest({});
|
||||
const b = correlateRequest({});
|
||||
|
||||
expect(a.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
|
||||
expect(a.requestId).not.toBe(b.requestId);
|
||||
expect(correlateRequest({ 'x-request-id': 'from-gateway' }).requestId).toBe('from-gateway');
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
||||
import type { EventPayload } from '../src/bus';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { name: 'db' } };
|
||||
}
|
||||
}
|
||||
|
||||
// Yields inside the step so two concurrent requests genuinely interleave their events rather
|
||||
// than each running to completion before the other starts. Without that, the correlation bug
|
||||
// this file exists to catch would not even show up.
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class LoadUser {
|
||||
async run() {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
return { user: { id: 'u1' } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'profile', needs: ['user'] })
|
||||
class LoadProfile {
|
||||
async run() {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
return { profile: { theme: 'dark' } };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/api')
|
||||
class Ctl {
|
||||
@Get('/me')
|
||||
me(@needs('profile') profile: unknown) {
|
||||
return { profile };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', providers: [Db], steps: [LoadUser, LoadProfile], controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
describe('event correlation', () => {
|
||||
it('attributes every step event to the request that caused it', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const seen: EventPayload[] = [];
|
||||
app.bus.on('request:step:enter', (p) => seen.push(p));
|
||||
app.bus.on('request:step:leave', (p) => seen.push(p));
|
||||
|
||||
// Concurrent on purpose: this is the only condition under which the defect appears.
|
||||
await Promise.all([
|
||||
app.fetch(new Request('http://x/api/me')),
|
||||
app.fetch(new Request('http://x/api/me')),
|
||||
]);
|
||||
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
expect(seen.every((event) => typeof event.requestId === 'string' && event.requestId.length > 0)).toBe(true);
|
||||
|
||||
// Two requests, two identities, and no event belonging to both.
|
||||
const ids = new Set(seen.map((event) => event.requestId));
|
||||
expect(ids.size).toBe(2);
|
||||
|
||||
// Each request must show its own complete run of the pipeline, which is the whole point of
|
||||
// correlating: counting events globally would pass even with the ids shuffled.
|
||||
// A step is named by what it `provides`, not by its class.
|
||||
for (const id of ids) {
|
||||
const forRequest = seen.filter((event) => event.requestId === id);
|
||||
expect(forRequest.filter((e) => e.name === 'user')).toHaveLength(2); // enter + leave
|
||||
expect(forRequest.filter((e) => e.name === 'profile')).toHaveLength(2);
|
||||
}
|
||||
});
|
||||
|
||||
it('labels events with the route pattern, never the concrete path', async () => {
|
||||
@Route('/things')
|
||||
class Things {
|
||||
// Needs a step on purpose: green-tea prunes steps no handler depends on, so a route that
|
||||
// needs nothing emits no step events and the assertion below would have nothing to read.
|
||||
@Get('/:id')
|
||||
one(@needs('user') user: unknown) {
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [Db], steps: [LoadUser, LoadProfile], controllers: [Things] })
|
||||
class ParamModule {}
|
||||
|
||||
const app = createApp({ modules: [ParamModule] });
|
||||
const seen: EventPayload[] = [];
|
||||
app.bus.on('request:step:leave', (p) => seen.push(p));
|
||||
|
||||
await app.fetch(new Request('http://x/things/42'));
|
||||
await app.fetch(new Request('http://x/things/1337'));
|
||||
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
// Two distinct URLs, one label. Labelling on the raw path is what gives a metrics backend
|
||||
// unbounded cardinality, so this is a contract and not an implementation detail.
|
||||
expect(new Set(seen.map((e) => e.route))).toEqual(new Set(['/things/:id']));
|
||||
});
|
||||
|
||||
it('times each step and reports it on leave', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const seen: EventPayload[] = [];
|
||||
app.bus.on('request:step:leave', (p) => seen.push(p));
|
||||
|
||||
await app.fetch(new Request('http://x/api/me'));
|
||||
|
||||
// Both steps sleep 10ms. Assert a range, never a value — a clock is not a promise.
|
||||
expect(seen).toHaveLength(2);
|
||||
for (const event of seen) {
|
||||
expect(event.durationMs).toBeGreaterThan(5);
|
||||
expect(event.durationMs).toBeLessThan(500);
|
||||
}
|
||||
});
|
||||
it('adopts an incoming x-request-id instead of starting a second identity', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const seen: EventPayload[] = [];
|
||||
app.bus.on('request:step:enter', (p) => seen.push(p));
|
||||
|
||||
await app.fetch(new Request('http://x/api/me', { headers: { 'x-request-id': 'from-the-gateway' } }));
|
||||
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
expect(seen.every((event) => event.requestId === 'from-the-gateway')).toBe(true);
|
||||
});
|
||||
|
||||
it('carries traceparent through as traceId without parsing it', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const traceparent = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01';
|
||||
const seen: EventPayload[] = [];
|
||||
app.bus.on('request:step:enter', (p) => seen.push(p));
|
||||
|
||||
await app.fetch(new Request('http://x/api/me', { headers: { traceparent } }));
|
||||
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
// Verbatim: core implements no propagation spec, that belongs to the exporter.
|
||||
expect(seen.every((event) => event.traceId === traceparent)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('failure reporting', () => {
|
||||
@Step({ provides: 'ok' })
|
||||
class Fine {
|
||||
run() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'boom', needs: ['ok'] })
|
||||
class Boom {
|
||||
run(): never {
|
||||
throw new Error('step exploded');
|
||||
}
|
||||
}
|
||||
@Route('/bad')
|
||||
class BadCtl {
|
||||
@Get('/go')
|
||||
go(@needs('boom') b: unknown) {
|
||||
return { b };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Fine, Boom], controllers: [BadCtl] })
|
||||
class BadModule {}
|
||||
|
||||
it('names the step that failed, and marks the request failed once', async () => {
|
||||
const app = createApp({ modules: [BadModule] });
|
||||
const stepErrors: EventPayload[] = [];
|
||||
const requestFailures: EventPayload[] = [];
|
||||
app.bus.on('request:step:error', (p) => stepErrors.push(p));
|
||||
app.bus.on('request:failed', (p) => requestFailures.push(p));
|
||||
|
||||
await app.fetch(new Request('http://x/bad/go'));
|
||||
|
||||
// The defect this replaces reported every failure as name: 'pipeline'.
|
||||
expect(stepErrors).toHaveLength(1);
|
||||
expect(stepErrors[0].name).toBe('boom');
|
||||
expect((stepErrors[0].error as Error).message).toBe('step exploded');
|
||||
|
||||
// Both fire, on purpose: one marks the span, the other the trace.
|
||||
expect(requestFailures).toHaveLength(1);
|
||||
expect(requestFailures[0].route).toBe('/bad/go');
|
||||
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -10,11 +10,31 @@ interface PackageMetadata {
|
||||
};
|
||||
readonly bugs?: {
|
||||
readonly url?: string;
|
||||
readonly email?: string;
|
||||
};
|
||||
readonly homepage?: string;
|
||||
readonly author?: string;
|
||||
}
|
||||
|
||||
const packageJson = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as PackageMetadata;
|
||||
interface DenoManifest {
|
||||
readonly name?: string;
|
||||
readonly version?: string;
|
||||
readonly license?: string;
|
||||
readonly exports?: Record<string, string>;
|
||||
}
|
||||
|
||||
const read = (file: string): string => readFileSync(resolve(process.cwd(), file), 'utf8');
|
||||
const packageJson = JSON.parse(read('package.json')) as PackageMetadata & { version: string; license: string };
|
||||
|
||||
// `deno.json` is JSONC and carries comments. Only whole-line `//` comments are stripped, so this
|
||||
// can never eat a `//` inside a string value — narrower than a general JSONC parser, and enough,
|
||||
// versus pulling in a dependency to read one config file.
|
||||
const denoJson = JSON.parse(
|
||||
read('deno.json')
|
||||
.split('\n')
|
||||
.filter((line) => !line.trim().startsWith('//'))
|
||||
.join('\n'),
|
||||
) as DenoManifest;
|
||||
|
||||
describe('package publication metadata', () => {
|
||||
it('links npm provenance to the public GitHub repository', () => {
|
||||
@@ -27,7 +47,31 @@ describe('package publication metadata', () => {
|
||||
it('links npm consumers to support and documentation', () => {
|
||||
expect(packageJson.bugs).toEqual({
|
||||
url: 'https://github.com/Expressive-Tea/green-tea/issues',
|
||||
email: 'projects@expressive-tea.io',
|
||||
});
|
||||
expect(packageJson.homepage).toBe('https://green-tea.expressive-tea.io/docs/');
|
||||
});
|
||||
|
||||
// A published package whose only contact is a GitHub URL is unreachable to anyone without
|
||||
// an account, so the address is pinned here rather than left to drift back out.
|
||||
it('gives npm an address to show for the package', () => {
|
||||
expect(packageJson.author).toBe('green-tea contributors <projects@expressive-tea.io>');
|
||||
});
|
||||
});
|
||||
|
||||
// npm and JSR are published from the same tag but read their identity from different files, so the
|
||||
// two can drift silently: bump package.json alone and the next release ships one version to npm and
|
||||
// the previous one to JSR, under the same tag. Nothing else notices, which is why this is here.
|
||||
describe('JSR manifest agrees with package.json', () => {
|
||||
it('publishes the same package at the same version', () => {
|
||||
expect(denoJson.name).toBe('@green-tea/core');
|
||||
expect(denoJson.version).toBe(packageJson.version);
|
||||
expect(denoJson.license).toBe(packageJson.license);
|
||||
});
|
||||
|
||||
// A reader following a docs example should not have to care which registry they installed from.
|
||||
it('offers the same entry points npm does', () => {
|
||||
const npmEntries = Object.keys(JSON.parse(read('package.json')).exports as Record<string, unknown>);
|
||||
expect(Object.keys(denoJson.exports ?? {})).toEqual(npmEntries);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import type { Server } from 'http';
|
||||
import { connect } from 'net';
|
||||
import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
@@ -69,6 +70,25 @@ async function both(path: string, init?: RequestInit) {
|
||||
return { node, web };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request line verbatim, bypassing `fetch`.
|
||||
*
|
||||
* `both()` cannot reach the cases below: `fetch()` normalizes the URL before it hits the wire, and
|
||||
* `new Request()` does the same, so a dot segment written into either is already resolved by the
|
||||
* time the adapter sees it. Only a hand-written request line proves what Node does with one.
|
||||
*/
|
||||
function rawStatus(target: string): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = connect(Number(new URL(base).port), '127.0.0.1', () => {
|
||||
socket.write(`GET ${target} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n`);
|
||||
});
|
||||
let raw = '';
|
||||
socket.on('data', (chunk) => (raw += chunk.toString()));
|
||||
socket.on('error', reject);
|
||||
socket.on('end', () => resolve(Number(raw.split(' ')[1])));
|
||||
});
|
||||
}
|
||||
|
||||
describe('Node vs app.fetch parity (Node is truth)', () => {
|
||||
it('GET /api/x', async () => {
|
||||
const { node, web } = await both('/api/x');
|
||||
@@ -125,6 +145,21 @@ describe('Node vs app.fetch parity (Node is truth)', () => {
|
||||
expect(web.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
}
|
||||
});
|
||||
// Regression: the same bytes on the wire used to route differently per runtime. Deno, Bun and
|
||||
// workerd resolve dot segments inside the `Request` constructor before green-tea sees anything,
|
||||
// and the raw target is unrecoverable there — so Node had to be taught to resolve them too.
|
||||
it('resolves dot segments to the same route the fetch adapter reaches', async () => {
|
||||
for (const target of ['/api/nope/../x', '/api/./x', '/api/nope/%2e%2e/x', '/nope/../api/x']) {
|
||||
expect(await rawStatus(target), `node ${target}`).toBe(200);
|
||||
expect((await app.fetch(new Request(base + target))).status, `fetch ${target}`).toBe(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not treat dots inside a segment as dot segments', async () => {
|
||||
expect(await rawStatus('/api/x.y')).toBe(404);
|
||||
expect((await app.fetch(new Request(base + '/api/x.y'))).status).toBe(404);
|
||||
});
|
||||
|
||||
it('SSE first two events', async () => {
|
||||
const nodeText = await (await fetch(base + '/api/s')).text();
|
||||
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
|
||||
|
||||
+37
-2
@@ -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);
|
||||
});
|
||||
@@ -76,6 +76,33 @@ describe('normalizeRequestPath', () => {
|
||||
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||
});
|
||||
|
||||
// The reference for every case below is `new URL('http://x' + path).pathname`, because that is
|
||||
// what Deno, Bun and workerd apply before green-tea is handed the request. Node has no such step,
|
||||
// so this is where the two adapters are made to agree.
|
||||
it('resolves dot segments the way the URL parser does', () => {
|
||||
expect(normalizeRequestPath('/public/../admin')).toBe('/admin');
|
||||
expect(normalizeRequestPath('/./admin')).toBe('/admin');
|
||||
expect(normalizeRequestPath('/a/b/../../c')).toBe('/c');
|
||||
expect(normalizeRequestPath('/a/.')).toBe('/a');
|
||||
expect(normalizeRequestPath('/..')).toBe('/');
|
||||
expect(normalizeRequestPath('/a/../..')).toBe('/');
|
||||
});
|
||||
|
||||
it('resolves percent-encoded dot segments, which the URL parser also treats as dots', () => {
|
||||
expect(normalizeRequestPath('/public/%2e%2e/admin')).toBe('/admin');
|
||||
expect(normalizeRequestPath('/public/%2E%2E/admin')).toBe('/admin');
|
||||
expect(normalizeRequestPath('/%2e/admin')).toBe('/admin');
|
||||
expect(normalizeRequestPath('/public/.%2e/admin')).toBe('/admin');
|
||||
});
|
||||
|
||||
it('leaves dots that are not whole segments alone', () => {
|
||||
expect(normalizeRequestPath('/assets/logo.png')).toBe('/assets/logo.png');
|
||||
expect(normalizeRequestPath('/files/.hidden')).toBe('/files/.hidden');
|
||||
expect(normalizeRequestPath('/v1.2/status')).toBe('/v1.2/status');
|
||||
// %2f is not a separator to the URL parser, so `..%2fb` is one ordinary segment.
|
||||
expect(normalizeRequestPath('/a/..%2fb')).toBe('/a/..%2fb');
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchRoute precedence', () => {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,10 @@ writeFileSync(join(root, 'index.html'), '<h1>Home</h1>');
|
||||
writeFileSync(join(root, 'app.css'), 'body{}');
|
||||
writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET');
|
||||
|
||||
// Bytes that no text encoding round-trips: a NUL, a lone high byte, an invalid UTF-8 sequence.
|
||||
const binary = Buffer.from([0x00, 0x89, 0x50, 0x4e, 0x47, 0xff, 0xfe, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
writeFileSync(join(root, 'pixel.bin'), binary);
|
||||
|
||||
@Route('/api')
|
||||
class Api {
|
||||
@Get('/ping')
|
||||
@@ -29,6 +33,16 @@ describe('static serving', () => {
|
||||
expect(res.headers.get('content-type')).toBe('text/css; charset=utf-8');
|
||||
expect(await res.text()).toBe('body{}');
|
||||
});
|
||||
// Static serving is the only path that puts a Buffer into a buffered outcome, so it is the only
|
||||
// integration cover for the Buffer→BodyInit conversion in the Fetch adapter. Every other assertion
|
||||
// in this file is text, which survives a conversion that mangles bytes; this one does not.
|
||||
it('serves binary bytes exactly', async () => {
|
||||
const res = await app.fetch(new Request('http://x/pixel.bin'));
|
||||
expect(res.status).toBe(200);
|
||||
const bytes = new Uint8Array(await res.arrayBuffer());
|
||||
expect(bytes.byteLength).toBe(binary.byteLength);
|
||||
expect([...bytes]).toEqual([...binary]);
|
||||
});
|
||||
it('serves index.html for /', async () => {
|
||||
expect(await (await app.fetch(new Request('http://x/'))).text()).toBe('<h1>Home</h1>');
|
||||
});
|
||||
|
||||
+25
-1
@@ -1,9 +1,33 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { asReadableStream } from '../src/http/web';
|
||||
import { asReadableStream, toBodyInit } from '../src/http/web';
|
||||
import { sseEncoder } from '../src/encoders';
|
||||
|
||||
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
|
||||
|
||||
describe('toBodyInit', () => {
|
||||
it('passes a string through untouched', () => {
|
||||
expect(toBodyInit('hello')).toBe('hello');
|
||||
});
|
||||
|
||||
// `Buffer.from` allocates inside a shared 8 KB pool, so these bytes sit at a non-zero byteOffset.
|
||||
// A conversion that re-views the backing store without the offset and length returns the entire
|
||||
// pool — every other allocation in it included. Asserting the length alone catches that.
|
||||
it('re-views a pooled Buffer as its own bytes, not the whole pool', async () => {
|
||||
const buf = Buffer.from([0x00, 0x89, 0xff, 0xfe, 0x0a]);
|
||||
expect(buf.byteOffset).toBeGreaterThan(0); // guards the premise: this Buffer really is pooled
|
||||
expect(buf.buffer.byteLength).toBeGreaterThan(buf.byteLength);
|
||||
|
||||
const bytes = new Uint8Array(await new Response(toBodyInit(buf)).arrayBuffer());
|
||||
expect(bytes.byteLength).toBe(5);
|
||||
expect([...bytes]).toEqual([0x00, 0x89, 0xff, 0xfe, 0x0a]);
|
||||
});
|
||||
|
||||
it('does not copy — the view shares the backing store', () => {
|
||||
const buf = Buffer.from([1, 2, 3]);
|
||||
expect((toBodyInit(buf) as Uint8Array).buffer).toBe(buf.buffer);
|
||||
});
|
||||
});
|
||||
|
||||
describe('asReadableStream', () => {
|
||||
it('encodes each yielded value with the encoder', async () => {
|
||||
const rs = asReadableStream(nums(), sseEncoder);
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { defineConfig } from 'astro/config';
|
||||
import starlight from '@astrojs/starlight';
|
||||
|
||||
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
|
||||
export default defineConfig({
|
||||
site: 'https://green-tea.expressive-tea.io',
|
||||
base: '/docs',
|
||||
integrations: [
|
||||
starlight({
|
||||
// GoatCounter — same site code as the marketing site, so /docs traffic lands in
|
||||
// the same dashboard and referrer paths stay comparable.
|
||||
head: [
|
||||
{
|
||||
tag: 'script',
|
||||
attrs: {
|
||||
'data-goatcounter': 'https://greentea.goatcounter.com/count',
|
||||
async: true,
|
||||
src: '//gc.zgo.at/count.js',
|
||||
},
|
||||
},
|
||||
],
|
||||
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
|
||||
disable404Route: true,
|
||||
title: 'Green Tea.',
|
||||
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
|
||||
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
|
||||
favicon: '/favicon.svg',
|
||||
customCss: ['./src/styles/brand.css'],
|
||||
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
|
||||
sidebar: [
|
||||
{
|
||||
label: 'Start here',
|
||||
items: [
|
||||
{ label: 'Introduction', link: '/' },
|
||||
{ label: 'Getting started', slug: 'getting-started' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Concepts',
|
||||
items: [
|
||||
{ label: 'The dependency graph', slug: 'concepts/the-graph' },
|
||||
{ label: 'The typed flow core', slug: 'concepts/flow' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Guides',
|
||||
items: [
|
||||
{ label: 'The matcha CLI', slug: 'guides/cli' },
|
||||
{ label: 'Routing', slug: 'guides/routing' },
|
||||
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
|
||||
{ label: 'Argument decorators', slug: 'guides/arguments' },
|
||||
{ label: 'Validation', slug: 'guides/validation' },
|
||||
{ label: 'Error handling', slug: 'guides/errors' },
|
||||
{ label: 'Streaming & real-time', slug: 'guides/streaming' },
|
||||
{ label: 'File uploads', slug: 'guides/uploads' },
|
||||
{ label: 'HTML & views', slug: 'guides/html' },
|
||||
{ label: 'Transport security', slug: 'guides/security' },
|
||||
{ label: 'Plugins & observability', slug: 'guides/plugins' },
|
||||
{ label: 'Graph introspection', slug: 'guides/introspection' },
|
||||
{ label: 'OpenAPI', slug: 'guides/openapi' },
|
||||
{ label: 'Runtimes', slug: 'guides/runtimes' },
|
||||
{ label: 'Testing', slug: 'guides/testing' },
|
||||
{ label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Reference',
|
||||
items: [
|
||||
{ label: 'Decorators', slug: 'reference/decorators' },
|
||||
{ label: 'createApp options', slug: 'reference/createapp' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
Generated
-6853
File diff suppressed because it is too large.
Load diff
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "green-tea-docs",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/starlight": "^0.41.6",
|
||||
"astro": "^7.1.6",
|
||||
"sharp": "^0.35.3"
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
|
||||
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
|
||||
|
||||
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
|
||||
<path d="M277 312 Q255 263 221 247"/>
|
||||
<path d="M338 276 Q382 305 393 340"/>
|
||||
<path d="M366 258 Q348 214 317 200"/>
|
||||
<path d="M443 186 Q469 204 475 224"/>
|
||||
</g>
|
||||
<g fill="#5FB88A">
|
||||
<circle cx="221" cy="247" r="13"/>
|
||||
<circle cx="393" cy="340" r="13"/>
|
||||
<circle cx="475" cy="224" r="11"/>
|
||||
</g>
|
||||
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
@@ -1,16 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
|
||||
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
|
||||
|
||||
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
|
||||
<path d="M277 312 Q255 263 221 247"/>
|
||||
<path d="M338 276 Q382 305 393 340"/>
|
||||
<path d="M366 258 Q348 214 317 200"/>
|
||||
<path d="M443 186 Q469 204 475 224"/>
|
||||
</g>
|
||||
<g fill="#5FB88A">
|
||||
<circle cx="221" cy="247" r="13"/>
|
||||
<circle cx="393" cy="340" r="13"/>
|
||||
<circle cx="475" cy="224" r="11"/>
|
||||
</g>
|
||||
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
@@ -1,7 +0,0 @@
|
||||
import { defineCollection } from 'astro:content';
|
||||
import { docsLoader } from '@astrojs/starlight/loaders';
|
||||
import { docsSchema } from '@astrojs/starlight/schema';
|
||||
|
||||
export const collections = {
|
||||
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
title: Page not found
|
||||
description: "The requested Green Tea documentation page does not exist."
|
||||
template: splash
|
||||
hero:
|
||||
tagline: The documentation page you requested could not be found.
|
||||
actions:
|
||||
- text: Back to documentation
|
||||
link: /docs/
|
||||
icon: right-arrow
|
||||
---
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: The typed flow core
|
||||
description: "The functional flow API where the compile-time dependency guarantee lives."
|
||||
---
|
||||
|
||||
The [decorator layer](/docs/guides/dependency-injection/) validates the graph at **boot**. The functional core, `flow`, validates it in the **type checker** — before the program ever runs.
|
||||
|
||||
```typescript
|
||||
import { flow } from '@green-tea/core';
|
||||
|
||||
const pipeline = flow()
|
||||
.step('db', () => ({ find: (id: string) => id }))
|
||||
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
|
||||
```
|
||||
|
||||
Each `.step(name, fn)` adds its output to the accumulated context **type** (`Acc & Out`). The next step's `ctx` is typed with everything produced so far — so reading `ctx.db` compiles only because a previous step provided `db`. Reference a key nothing produced and it is a **compile error**, not a runtime `undefined`.
|
||||
|
||||
This is the strongest guarantee green-tea offers: the type *is* the dependency contract, checked statically. The decorator layer gives you the same graph with boot-time validation and the ergonomics of classes and decorators; `flow` gives you compile-time proof.
|
||||
|
||||
:::note
|
||||
`npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation.
|
||||
:::
|
||||
|
||||
See [The dependency graph](/docs/concepts/the-graph/) for how both layers describe the same model.
|
||||
@@ -1,47 +0,0 @@
|
||||
---
|
||||
title: The dependency graph
|
||||
description: "How green-tea models the request and boot pipeline as an explicit dependency graph."
|
||||
---
|
||||
|
||||
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That bookkeeping is where bugs live.
|
||||
|
||||
green-tea puts the request **on the page**. You declare what each unit **needs** and **produces**; the framework computes the order, checks the wiring, and can print the whole thing.
|
||||
|
||||
## needs / provides
|
||||
|
||||
Every node declares its inputs and outputs:
|
||||
|
||||
- A **provider** produces an app-scope value (a database handle, a config object) — resolved once at boot and cached.
|
||||
- A **step** reads the request context and merges new keys into it (authentication producing `user`, say) — runs per request.
|
||||
- A **handler** (a route method) declares, through its argument decorators, exactly which keys it depends on.
|
||||
|
||||
green-tea builds a directed graph from these declarations and **topologically sorts** it. You never write "put this before that" — order is derived from `needs`/`provides`.
|
||||
|
||||
```typescript
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] }) // user depends on db and req
|
||||
class Authenticate { /* ... */ }
|
||||
```
|
||||
|
||||
## Why it matters
|
||||
|
||||
- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order.
|
||||
- **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route.
|
||||
- **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`.
|
||||
- **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/docs/guides/introspection/).
|
||||
|
||||
## Two layers
|
||||
|
||||
green-tea exposes the graph two ways:
|
||||
|
||||
1. **The typed functional core, [`flow`](/docs/concepts/flow/)** — the compile-time guarantee. A handler that reads `ctx.user` fails to **compile** if no step produces `user`.
|
||||
2. **The declarative decorator layer** — `@Provider` / `@Step` / `@Module` / `@Route` / `@Get` plus [argument decorators](/docs/guides/arguments/). Emits runtime metadata, builds and sorts the graph, and validates at boot.
|
||||
|
||||
Both describe the same graph; pick the ergonomics you want.
|
||||
|
||||
## Why legacy decorators
|
||||
|
||||
green-tea uses **legacy** (experimental) TypeScript decorators — set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
|
||||
|
||||
The argument-injection API (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators**, and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so `handler(@param('id') id: string)` is only expressible with legacy decorators.
|
||||
|
||||
"Stage 3" also means *not finalized* — the proposal can still change before engines ship it. green-tea tracks it and will revisit if parameter injection ever gets a standard path. It does **not** rely on `emitDecoratorMetadata` / `design:type` reflection — argument positions are recorded explicitly — so this is the only legacy surface it depends on.
|
||||
@@ -1,95 +0,0 @@
|
||||
---
|
||||
title: Getting started
|
||||
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
|
||||
---
|
||||
|
||||
## Scaffold it
|
||||
|
||||
The fastest path is [matcha](/docs/guides/cli/), green-tea's CLI. It writes a project that runs on the first command — no wiring, no config:
|
||||
|
||||
```bash
|
||||
matcha new my-api # --runtime node (default) | deno | bun
|
||||
cd my-api && matcha run
|
||||
```
|
||||
|
||||
## Or install by hand
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core reflect-metadata
|
||||
# optional, only if you use them:
|
||||
npm install ws # WebSocket routes (@Ws) and mesh
|
||||
npm install busboy # multipart/form-data file uploads
|
||||
```
|
||||
|
||||
green-tea runs on **Node ≥ 18, Deno, Bun, and the edge** — the same app, you only swap the entry point. This guide uses Node; see [runtimes](/docs/guides/runtimes/) for the others and for what the edge can't offer.
|
||||
|
||||
green-tea uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"target": "es2020",
|
||||
"moduleResolution": "node"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators) for the rationale.
|
||||
|
||||
## Your first app
|
||||
|
||||
A provider produces a value, a step transforms the request context, and a controller handler declares exactly what it needs:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createApp, Provider, Step, Route, Get, Module,
|
||||
Unauthorized, needs, param,
|
||||
} from '@green-tea/core';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Database {
|
||||
provide() {
|
||||
const users = { u1: { id: 'u1', name: 'Diego' } };
|
||||
return { db: { find: (token: string) => users[token] ?? null } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('invalid token'); // cut the request
|
||||
return { user }; // continue
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Get('/:id')
|
||||
getUser(@needs('user') user, @param('id') id) { // the signature IS the contract
|
||||
return { requested: id, you: user };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
console.log(app.explain('/api/users/:id')); // auditable: the ordered chain, with origins
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -H 'x-token: u1' http://localhost:3000/api/users/9
|
||||
# {"requested":"9","you":{"id":"u1","name":"Diego"}}
|
||||
```
|
||||
|
||||
The handler asked for `user` via `@needs('user')`. If nothing in the graph produced `user`, `createApp` would **throw at boot** with a "did you mean…" hint — you never serve `undefined`.
|
||||
|
||||
## Where to next
|
||||
|
||||
- [The dependency graph](/docs/concepts/the-graph/) — the mental model behind everything.
|
||||
- [Dependency injection](/docs/guides/dependency-injection/) — providers, steps, and modules in depth.
|
||||
- [Argument decorators](/docs/guides/arguments/) — everything a handler can inject.
|
||||
- [Streaming & real-time](/docs/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
|
||||
@@ -1,148 +0,0 @@
|
||||
---
|
||||
title: Argument decorators
|
||||
description: "Everything a handler can inject with needs, ctx, param, query, body, header, inbound, and abort."
|
||||
---
|
||||
|
||||
A handler's signature declares exactly what it wants — in any order, nothing more. Each
|
||||
parameter decorator injects one thing: a graph-produced value, part of the request envelope,
|
||||
or a stream handle. Some decorators add a **dependency edge** to the graph (boot-validated);
|
||||
most just read from the request.
|
||||
|
||||
## The decorators at a glance
|
||||
|
||||
| Decorator | Injects | Adds a graph dependency? | Forms |
|
||||
|---|---|---|---|
|
||||
| `@needs('user')` | a value produced by a provider/step (boot-validated) | **yes** | `('key')` |
|
||||
| `@ctx()` | the whole accumulated context | no | `()` |
|
||||
| `@param(...)` | route params | no | `()` · `('id')` · `('id', schema)` |
|
||||
| `@query(...)` | parsed query string | no | `()` · `('q')` · `(['a','b'])` · `(schema)` |
|
||||
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | no | `()` · `('field')` · `(schema)` |
|
||||
| `@headers(...)` | request headers (whole bag or picked) | no | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
|
||||
| `@header('name')` | one request header (singular alias of `@headers`) | no | `('x-trace')` · `('x-count', schema)` |
|
||||
| `@inbound()` | the incoming WS message channel | no (WS only) | `()` |
|
||||
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) | `()` |
|
||||
|
||||
## `@needs` — a graph-produced value
|
||||
|
||||
`@needs('token')` injects a value a provider or step produces, and declares a dependency edge
|
||||
in the graph. Its keys are **validated at boot**: if nothing provides the token, `createApp`
|
||||
throws with a clear error instead of serving `undefined`.
|
||||
|
||||
```typescript
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { requested: id, you: user };
|
||||
}
|
||||
```
|
||||
|
||||
See [Dependency injection](/docs/guides/dependency-injection/) for how `needs`/`provides` build the
|
||||
graph.
|
||||
|
||||
## `@ctx` — the whole context
|
||||
|
||||
`@ctx()` hands you the entire accumulated context — everything providers and steps have merged
|
||||
in, plus built-ins. Use it to read values like `ctx.protocol` and `ctx.ip` (populated when
|
||||
`trustProxy` is on).
|
||||
|
||||
## Envelope decorators — `@param`, `@query`, `@body`, `@headers`
|
||||
|
||||
These read from the parsed request. Each envelope decorator has **three access forms**:
|
||||
|
||||
- `@query()` — the whole object
|
||||
- `@query('q')` — one key
|
||||
- `@query(['q','date'])` — a subset
|
||||
|
||||
```typescript
|
||||
@Get('/:id')
|
||||
getUser(@param('id') id: string) { /* ... */ }
|
||||
```
|
||||
|
||||
- **`@param`** reads route params. It always needs a name to say which param it binds
|
||||
(`@param('id')`).
|
||||
- **`@query`** reads the parsed query string. Query values are always strings on the wire — a
|
||||
schema is often the coercion point (see below).
|
||||
- **`@body`** reads the parsed body. It handles `application/json`,
|
||||
`application/x-www-form-urlencoded`, and `multipart/form-data` (see the multipart note).
|
||||
- **`@headers`** reads request headers — the whole bag (`@headers()`), one key
|
||||
(`@headers('authorization')`), or a subset (`@headers(['a','b'])`).
|
||||
|
||||
## `@header` — one header, singular alias
|
||||
|
||||
`@header('name')` is the singular alias of `@headers`: it picks exactly one request header.
|
||||
|
||||
```typescript
|
||||
who(@header('x-trace') trace: string) { /* ... */ }
|
||||
```
|
||||
|
||||
It also accepts a schema in slot 2 — `@header('x-count', schema)`.
|
||||
|
||||
## Schema forms — validation & coercion
|
||||
|
||||
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema** (zod,
|
||||
valibot, arktype, …). The value the handler receives is the schema's **parsed/coerced output**,
|
||||
already typed:
|
||||
|
||||
```typescript
|
||||
create(@body(CreateUser) user: { email: string }) {
|
||||
return { created: user.email };
|
||||
}
|
||||
```
|
||||
|
||||
:::note[Access shape (asymmetry)]
|
||||
`@param('id', Schema)` takes the **key in slot 1** and the schema in slot 2 — `@param` always
|
||||
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
|
||||
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
|
||||
object.
|
||||
:::
|
||||
|
||||
A failing schema short-circuits the request with **422**. See [Validation](/docs/guides/validation/)
|
||||
for the full contract (fail-fast order, error shape, async schemas, and caveats).
|
||||
|
||||
## Multipart access asymmetry
|
||||
|
||||
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
|
||||
instead of a plain object.
|
||||
|
||||
:::caution[Access note]
|
||||
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`,
|
||||
not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use
|
||||
`@body()` and read `.fields` / `.files`, or key into the envelope itself with `@body('fields')`
|
||||
/ `@body('files')`.
|
||||
:::
|
||||
|
||||
```typescript
|
||||
upload(@body() form: MultipartBody) {
|
||||
const name = form.fields.name; // string | string[]
|
||||
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
|
||||
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
|
||||
}
|
||||
```
|
||||
|
||||
## Stream decorators — `@inbound` and `@abort`
|
||||
|
||||
These are for streaming handlers:
|
||||
|
||||
- **`@inbound()`** (WS only) gives you the incoming WebSocket message channel — the client's
|
||||
messages to consume. A `@Ws` handler returns the **outbound** channel.
|
||||
- **`@abort()`** (stream / WS) hands you an `AbortSignal` that fires on disconnect, so you can
|
||||
tear down work when the client goes away.
|
||||
|
||||
```typescript
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => {
|
||||
for await (const msg of incoming) out.push(`echo: ${msg}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
```
|
||||
|
||||
See [Streaming](/docs/guides/streaming/) for SSE, WebSocket duplex, and channels.
|
||||
|
||||
## Where to go next
|
||||
|
||||
- How injected values are produced: [Dependency injection](/docs/guides/dependency-injection/).
|
||||
- The mental model: [The graph](/docs/concepts/the-graph/).
|
||||
- Validating and coercing injected values: [Validation](/docs/guides/validation/).
|
||||
- The full API surface: [Decorator reference](/docs/reference/decorators/).
|
||||
@@ -1,79 +0,0 @@
|
||||
---
|
||||
title: The matcha CLI
|
||||
description: "Scaffold, run, and generate green-tea apps from a single native binary."
|
||||
---
|
||||
|
||||
**matcha** scaffolds green-tea projects, runs them in watch mode, and generates pieces already wired into your graph. It is a native binary — installing the CLI needs no JS runtime, and it only reaches for yours when it runs or type-checks your project.
|
||||
|
||||
That is deliberate: green-tea runs on Node, Deno, Bun, and the edge, so its tool shouldn't be bound to one of them.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Expressive-Tea/matcha/main/install.sh | sh
|
||||
```
|
||||
|
||||
Downloads a checksum-verified prebuilt binary into `~/.local/bin`. Environment variables go on the `sh` side of the pipe:
|
||||
|
||||
```bash
|
||||
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
|
||||
```
|
||||
|
||||
From source, if you have Rust:
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/Expressive-Tea/matcha
|
||||
```
|
||||
|
||||
## Scaffold — `matcha new`
|
||||
|
||||
```bash
|
||||
matcha new my-api # Node (the default)
|
||||
matcha new my-api --runtime deno # or deno | bun
|
||||
matcha new my-api --template-url gh:owner/repo # any git template
|
||||
```
|
||||
|
||||
The starter is alive on the first run: it serves an `index.html` and streams a rotating zen message over `@Sse('/zen')`. Open the browser and something is already moving — you are editing a working app, not assembling one.
|
||||
|
||||
Only the entry point and the config differ between runtimes. The `src/` tree is identical, which is the same portability the framework promises.
|
||||
|
||||
## Run — `matcha run`
|
||||
|
||||
```bash
|
||||
matcha run
|
||||
```
|
||||
|
||||
Detects the runtime and starts a watch loop. First match wins:
|
||||
|
||||
1. `matcha.toml` — an explicit `runtime = "node" | "deno" | "bun"`
|
||||
2. `deno.json` / `deno.jsonc` → deno
|
||||
3. `bun.lockb` / `bun.lock` → bun
|
||||
4. `package.json` → node
|
||||
|
||||
Edge is a deploy target, not a `matcha run` target.
|
||||
|
||||
## Generate — `matcha create`
|
||||
|
||||
```bash
|
||||
matcha create controller Users
|
||||
matcha create step Authenticate
|
||||
matcha create provider Database
|
||||
matcha create module Billing
|
||||
matcha create controller Users --check # type-check with your runtime afterward
|
||||
```
|
||||
|
||||
Writes the file **and wires it in** — into the right `@Module` array, or into `createApp({ modules })` for a module.
|
||||
|
||||
## Extend — `matcha add`
|
||||
|
||||
```bash
|
||||
matcha add sse # or: stream | buffer
|
||||
```
|
||||
|
||||
Inserts a handler of that shape into your controller.
|
||||
|
||||
## How the edits stay safe
|
||||
|
||||
`create` and `add` edit your TypeScript with [tree-sitter](https://tree-sitter.github.io), not string splicing or regex. Edits are **idempotent** — running the same command twice doesn't duplicate anything — and they **revert themselves** if the result wouldn't parse. A generator that corrupts your source is worse than no generator.
|
||||
|
||||
One case it deliberately refuses: if `modules` is a variable (`modules: MODULES`) rather than an array literal, `create module` won't add a second `modules` key. Duplicate keys parse cleanly, so nothing would fail — it would just silently shadow your value. It tells you instead.
|
||||
@@ -1,146 +0,0 @@
|
||||
---
|
||||
title: Dependency injection
|
||||
description: "Providers, steps, and modules, and how values flow through the graph."
|
||||
---
|
||||
|
||||
In green-tea the request pipeline is an explicit **dependency graph**. You declare what each
|
||||
piece needs and produces; the framework computes the order, validates the wiring at boot, and
|
||||
runs only the slice a route actually depends on. You never write "put this before that."
|
||||
|
||||
There are three building blocks:
|
||||
|
||||
- A **provider** is an app-scope singleton — constructed once, its value memoized for the
|
||||
lifetime of the app.
|
||||
- A **step** runs per request and transforms the context.
|
||||
- A **module** sets a mountpoint and wires providers, steps, and controllers together.
|
||||
|
||||
A handler's **argument decorators are its dependency declaration** — ask for what you want, in
|
||||
any order. If you `@needs` a token nothing produces, you get a **boot error**, not an
|
||||
`undefined` at runtime.
|
||||
|
||||
## The full example
|
||||
|
||||
```typescript
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Database {
|
||||
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx: any) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
|
||||
return { user }; // return = continue, merge into ctx
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Get('/:id')
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { requested: id, you: user }; // auto-serialized as JSON
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
await app.listen(3000);
|
||||
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
|
||||
|
||||
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
|
||||
```
|
||||
|
||||
## `@Provider` — app-scope, memoized
|
||||
|
||||
A provider produces a value once, when the app boots, and reuses it for every request. Its
|
||||
`provide()` method returns an object whose keys become tokens in the graph — here `db`.
|
||||
|
||||
```typescript
|
||||
@Provider({ provides: 'db' })
|
||||
class Database {
|
||||
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
|
||||
}
|
||||
```
|
||||
|
||||
Because it's app-scope, a provider is the right home for things you build once and share:
|
||||
database clients, config, connection pools.
|
||||
|
||||
:::note
|
||||
An optional provider (`optional: true`) that throws on boot does **not** abort startup — it is
|
||||
left unregistered and logged, and the failure surfaces at request time for routes that need it.
|
||||
Query the degraded set with `app.degraded()` or listen for the `boot:provider:fail` bus event.
|
||||
:::
|
||||
|
||||
## `@Step` — request-scope, transforms the context
|
||||
|
||||
A step runs once per request. Its `run(ctx)` receives the accumulated context and either:
|
||||
|
||||
- **returns an object** → the pipeline continues and the object is merged into `ctx`, or
|
||||
- **throws** → the request short-circuits (here `Unauthorized` becomes a `401`).
|
||||
|
||||
```typescript
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx: any) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
|
||||
return { user }; // return = continue, merge into ctx
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This step `provides: 'user'` and `needs: ['db', 'req']` — so green-tea knows the `db` provider
|
||||
and the built-in `req` must resolve before it runs, and it topologically sorts accordingly.
|
||||
|
||||
## How `needs` / `provides` build the graph
|
||||
|
||||
Every node declares what it **produces** (`provides`) and what it **consumes** (`needs`). The
|
||||
framework reads those declarations and computes a topological order — you never specify
|
||||
ordering by hand. A handler's argument decorators extend the same graph: `@needs('user')` on a
|
||||
parameter is a dependency edge exactly like a step's `needs`.
|
||||
|
||||
Because the graph is explicit, **each route runs only the transitive closure of its handler's
|
||||
`@needs`** — nothing else.
|
||||
|
||||
:::caution[Per-route execution]
|
||||
A route that doesn't `@needs('user')` does **not** run the `Authenticate` step. A cross-cutting
|
||||
*enforcement* step (e.g. auth that throws `401`) only protects routes that actually `@needs`
|
||||
its token. To run something on **every** route regardless of needs (logging, audit, a global
|
||||
guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` — steps that produce
|
||||
nothing run unconditionally. Don't rely on a token-providing step to guard routes that don't
|
||||
declare it.
|
||||
:::
|
||||
|
||||
## `@Module` — mountpoint and wiring
|
||||
|
||||
A module ties everything together: a `mountpoint` prefix for the routes, and the lists of
|
||||
`providers`, `steps`, and `controllers` that belong to it.
|
||||
|
||||
```typescript
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
```
|
||||
|
||||
Pass modules to `createApp({ modules: [ApiModule] })` to assemble the app.
|
||||
|
||||
## Boot validation of `@needs`
|
||||
|
||||
The payoff of declaring dependencies is that the wiring is checked before a single request is
|
||||
served. When you `@needs` a token, green-tea verifies some provider or step actually produces
|
||||
it. If nothing does, **`createApp` throws with a clear error** instead of letting your handler
|
||||
receive `undefined`. Boot fails loudly, so you never serve `undefined`.
|
||||
|
||||
## Where to go next
|
||||
|
||||
- New to green-tea? Start with [Getting started](/docs/getting-started/).
|
||||
- The mental model behind all of this: [The graph](/docs/concepts/the-graph/).
|
||||
- Everything a handler can inject: [Argument decorators](/docs/guides/arguments/) and the
|
||||
[decorator reference](/docs/reference/decorators/).
|
||||
- Coerce and validate injected values with Standard Schema: [Validation](/docs/guides/validation/).
|
||||
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/docs/guides/streaming/).
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
title: Error handling
|
||||
description: "Throw typed errors anywhere; render them however you like with onError."
|
||||
---
|
||||
|
||||
Errors are **thrown, not returned**. Throw a typed error anywhere in the pipeline — a provider, a step, or a handler — and green-tea converts it to a response at one place.
|
||||
|
||||
## The typed errors
|
||||
|
||||
All live in `@green-tea/core`:
|
||||
|
||||
| Throw | Status |
|
||||
|---|---|
|
||||
| `Unauthorized(msg?)` | `401` |
|
||||
| `NotFound(msg?)` | `404` |
|
||||
| `NotModified()` | `304` |
|
||||
| `Redirect(location)` | `302` + `Location` |
|
||||
| `ValidationError` | `422` (raised for you by schema validation) |
|
||||
| `HttpError(status, msg?, body?)` | any status |
|
||||
| anything else | `500` (message hidden — internals never leak) |
|
||||
|
||||
```typescript
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('invalid token'); // → 401, cuts the request
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
By default an error becomes JSON: `{ "error": "<message>" }` (validation adds `source` + per-field `issues`).
|
||||
|
||||
## Structured error bodies
|
||||
|
||||
An `HttpError` can carry a **body** — return a structured payload instead of the default `{ error }`:
|
||||
|
||||
```typescript
|
||||
throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
|
||||
// → 409 { "code": "DUP_EMAIL", "field": "email" }
|
||||
```
|
||||
|
||||
## Render errors your way — `onError`
|
||||
|
||||
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
||||
|
||||
```typescript
|
||||
import { HttpError } from '@green-tea/core';
|
||||
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
onError(error, req) {
|
||||
const status = error instanceof HttpError ? error.status : 500;
|
||||
// negotiate: HTML for browsers, JSON for API clients
|
||||
if (String(req.headers.accept).includes('text/html')) {
|
||||
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
||||
}
|
||||
return undefined; // fall back to the default JSON
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
||||
|
||||
:::note
|
||||
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
|
||||
:::
|
||||
@@ -1,161 +0,0 @@
|
||||
---
|
||||
title: HTML & views
|
||||
description: "The @Html decorator, the built-in template engine, and zero-config static file serving."
|
||||
---
|
||||
|
||||
Most of green-tea assumes JSON, but not every route is an API endpoint. `@Html` marks a handler as serving HTML instead of going through the JSON transformer — a string, a file, or a file rendered with data. Add a static directory on top and you've got a small server-rendered site without reaching for a template framework.
|
||||
|
||||
## `@Html` — three modes
|
||||
|
||||
### 1. Return a string — every runtime
|
||||
|
||||
Bare `@Html` sends the handler's return value as `text/html; charset=utf-8`. No filesystem involved, so this mode runs on Node, Deno, Bun, and the edge.
|
||||
|
||||
```typescript
|
||||
import { Route, Get, Html } from '@green-tea/core';
|
||||
|
||||
@Route('/')
|
||||
class PageController {
|
||||
@Get('/')
|
||||
@Html
|
||||
home() {
|
||||
return '<h1>Hello from green-tea</h1>';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Serve a file — Node/Deno/Bun
|
||||
|
||||
`@Html('file.html')` reads the file at boot, caches it, and serves it verbatim — the handler still runs (for side effects, guards, etc.) but its return value is ignored.
|
||||
|
||||
```typescript
|
||||
@Route('/about')
|
||||
class AboutController {
|
||||
@Get('/')
|
||||
@Html('about.html')
|
||||
about() {}
|
||||
}
|
||||
```
|
||||
|
||||
Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/docs/guides/runtimes/) for the edge alternative.
|
||||
|
||||
### 3. Render a template — Node/Deno/Bun
|
||||
|
||||
`@Html('file.html', { template: true })` reads the file at boot and renders it with whatever object the handler returns, on every request.
|
||||
|
||||
```typescript
|
||||
@Route('/user')
|
||||
class UserController {
|
||||
@Get('/:id')
|
||||
@Html('user.html', { template: true })
|
||||
show(@param('id') id: string) {
|
||||
return { name: lookupName(id) };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`user.html`:
|
||||
|
||||
```html
|
||||
<h1>Hi {{ name }}</h1>
|
||||
```
|
||||
|
||||
Same filesystem requirement as file mode: Node/Deno/Bun only.
|
||||
|
||||
:::caution[Return the right shape for each mode — never an `AsyncIterable`]
|
||||
`@Html` is a buffered route, so its return contract follows the mode: bare `@Html` returns a
|
||||
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
||||
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
||||
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
||||
handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
|
||||
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
||||
:::
|
||||
|
||||
## The `views` base directory
|
||||
|
||||
`@Html('file.html')` paths resolve against `createApp({ views })` — a relative path joins `views`, an absolute path is used as-is (handy for a template stored outside the project, e.g. on an NFS mount). `views` defaults to `process.cwd()` when unset.
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], views: 'templates' });
|
||||
// @Html('about.html') -> <cwd>/templates/about.html
|
||||
// @Html('/srv/shared/about.html') -> /srv/shared/about.html (absolute, used as-is)
|
||||
```
|
||||
|
||||
Files are read once, at boot — not on every request.
|
||||
|
||||
## The built-in template engine
|
||||
|
||||
Template mode renders with a small, dependency-free engine, also exported as `render` if you want to call it directly:
|
||||
|
||||
```typescript
|
||||
import { render } from '@green-tea/core';
|
||||
|
||||
render('<h1>{{ name }}</h1>', { name: '<b>hi</b>' });
|
||||
// '<h1><b>hi</b></h1>' — {{ x }} HTML-escapes
|
||||
|
||||
render('{{{ html }}}', { html: '<b>hi</b>' });
|
||||
// '<b>hi</b>' — {{{ x }}} is raw, unescaped
|
||||
|
||||
render('{{ user.name }} / {{ nope }}', { user: { name: 'Diego' } });
|
||||
// 'Diego / ' — {{ a.b }} walks nested keys; a missing key renders empty
|
||||
```
|
||||
|
||||
That's the whole engine: interpolation, escaped or raw, with dotted-key lookup. No loops, conditionals, or partials — reach for `viewEngine` below if you need those.
|
||||
|
||||
## Bring your own engine — `viewEngine`
|
||||
|
||||
`createApp({ viewEngine })` swaps in any `(source, data) => string` function for template mode — EJS, Handlebars, or your own:
|
||||
|
||||
```typescript
|
||||
import ejs from 'ejs';
|
||||
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
views: 'templates',
|
||||
viewEngine: (source, data) => ejs.render(source, data as object),
|
||||
});
|
||||
```
|
||||
|
||||
`viewEngine` only affects `@Html(..., { template: true })`; string and plain file modes are unaffected.
|
||||
|
||||
## Static files — `createApp({ static })`
|
||||
|
||||
`static` serves a directory as a GET/HEAD fallback, tried after your declared routes and before a `404`:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], static: true }); // ./public, relative to cwd
|
||||
const app2 = createApp({ modules: [ApiModule], static: 'assets' }); // ./assets, relative to cwd
|
||||
const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolute, used as-is
|
||||
```
|
||||
|
||||
- Files are served at their URL path; content-type is inferred from the extension.
|
||||
- `/` (and any directory-shaped path) resolves to `index.html`.
|
||||
- Only `GET` and `HEAD` are handled — other methods fall through.
|
||||
- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`.
|
||||
- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root.
|
||||
|
||||
Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/docs/guides/runtimes/).
|
||||
|
||||
## The boot rule
|
||||
|
||||
`@Html` only supports **buffered `GET`/`POST`** routes. Boot fails fast rather than misbehaving at request time:
|
||||
|
||||
```typescript
|
||||
@Sse('/ticks')
|
||||
@Html
|
||||
ticks() { /* ... */ }
|
||||
// throws at createApp(): "@Html on GET /ticks is not allowed —
|
||||
// @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)"
|
||||
```
|
||||
|
||||
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
|
||||
|
||||
```typescript
|
||||
@Get('/g')
|
||||
@Html
|
||||
@Transformer(myTransformer)
|
||||
g() { /* ... */ }
|
||||
// throws at createApp(): "@Html and @Transformer on /g conflict — use one"
|
||||
```
|
||||
|
||||
Both checks run once, at boot, alongside the rest of the route validation — never per-request.
|
||||
@@ -1,55 +0,0 @@
|
||||
---
|
||||
title: Graph introspection
|
||||
description: "explain, graph, toMermaid, and the graph endpoint."
|
||||
---
|
||||
|
||||
Because the request/boot pipeline is an explicit [dependency graph](/docs/concepts/the-graph/),
|
||||
you can inspect it directly — visualize the whole thing, or explain exactly which nodes a
|
||||
single route runs.
|
||||
|
||||
## Visualize with Mermaid
|
||||
|
||||
`app.toMermaid()` renders a flowchart of every node and route. `app.toDOT()` produces the
|
||||
same graph as Graphviz DOT.
|
||||
|
||||
```typescript
|
||||
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
||||
```
|
||||
|
||||
Enable a live `GET /__graph__` endpoint — it renders an HTML viewer with Mermaid, or the
|
||||
raw Mermaid source with `Accept: text/plain`:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devGraph: true });
|
||||
// GET /__graph__ → HTML viewer
|
||||
// GET /__graph__ (text/plain) → raw Mermaid source
|
||||
```
|
||||
|
||||
:::caution
|
||||
`devGraph` exposes your graph structure over HTTP. Keep it on in development; leave it off
|
||||
in production.
|
||||
:::
|
||||
|
||||
## Explain a route
|
||||
|
||||
`app.explain(route)` returns the exact execution chain for one route — the ordered nodes,
|
||||
each with its kind, origin, and declared `needs`/`provides`:
|
||||
|
||||
```typescript
|
||||
const e = app.explain('/api/users/:id');
|
||||
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
|
||||
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
|
||||
// → ['provider:db', 'step:user', 'handler:getUser']
|
||||
```
|
||||
|
||||
The chain is the transitive closure of the handler's `@needs` — the same set the framework
|
||||
actually runs for that route, and nothing more.
|
||||
|
||||
`app.graph()` returns the underlying graph structure programmatically if you'd rather walk
|
||||
it yourself than render it.
|
||||
|
||||
## Degraded optional providers
|
||||
|
||||
`app.degraded()` returns the names of optional providers that are running in a **degraded**
|
||||
state — for example, an optional dependency that failed to initialize but didn't abort boot.
|
||||
Use it as a health signal to surface partial availability.
|
||||
@@ -1,145 +0,0 @@
|
||||
---
|
||||
title: Mesh (alpha)
|
||||
description: "Distributed dependency injection over a secret-gated WebSocket control channel."
|
||||
---
|
||||
|
||||
:::caution[Alpha]
|
||||
Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.**
|
||||
:::
|
||||
|
||||
A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/docs/concepts/the-graph/), and some nodes happen to live elsewhere.
|
||||
|
||||
Exports are opt-in (`export: true`) and the control channel is gated by a shared secret.
|
||||
|
||||
## What runs where
|
||||
|
||||
Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime.
|
||||
|
||||
**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide.
|
||||
|
||||
You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route:
|
||||
|
||||
```typescript
|
||||
serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade
|
||||
serveBun(teacup, { port: 3003 }); // teapots connected on the first request
|
||||
```
|
||||
|
||||
## Node A — teapot (exposes `config`, `auth`, and a route)
|
||||
|
||||
```typescript
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
|
||||
|
||||
@Route('/svc')
|
||||
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
|
||||
class TeapotModule {}
|
||||
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
|
||||
await teapot.listen(3002);
|
||||
```
|
||||
|
||||
## Node B — teacup (uses `config` + `auth` with no local providers)
|
||||
|
||||
```typescript
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth }; // both resolved by RPC to the teapot
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
|
||||
});
|
||||
await teacup.listen(3003);
|
||||
// GET B:3003/api/local/who (x-token: abc)
|
||||
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
|
||||
```
|
||||
|
||||
## How it resolves
|
||||
|
||||
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its **manifest** on connect. Scope determines the RPC cost:
|
||||
|
||||
- A **provider** export is **app-scope** — resolved once and cached.
|
||||
- A **step** export is **request-scope** — one RPC per request, carrying the request envelope.
|
||||
|
||||
Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once.
|
||||
|
||||
## Inspecting a mesh graph
|
||||
|
||||
`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it:
|
||||
|
||||
```typescript
|
||||
await app.ready(); // connects the teapots; a no-op on a non-mesh app
|
||||
app.graph(); // now includes the remote scopes
|
||||
```
|
||||
|
||||
Write those two lines and your code works against either kind of app without knowing which it got. `ready()` deliberately does **not** boot providers — resolving the graph and being ready to serve are different things, and drawing a diagram should not open your database connections. Serving (`fetch`/`upgrade`/`listen`) boots them too and shares the same memoized step, so calling both never resolves the graph twice.
|
||||
|
||||
The dev routes (`/__graph__`, `/__openapi__`) need none of this: a request boots the app before the route runs.
|
||||
|
||||
## Buffered routes only
|
||||
|
||||
Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today.
|
||||
|
||||
## One teapot per route
|
||||
|
||||
A route must be exported by exactly **one** teapot. If two export the same method and effective match shape — including patterns that differ only by parameter name, such as `/:id` and `/:name` — boot **fails**, naming both patterns and both teapots:
|
||||
|
||||
```
|
||||
mesh: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
|
||||
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
|
||||
across teapots is not implemented yet, so green-tea will not choose one for you.
|
||||
```
|
||||
|
||||
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
|
||||
|
||||
**Local routes win.** If you declare a route locally *and* import the same effective method/shape from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
|
||||
|
||||
```
|
||||
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
|
||||
declared locally — the local route takes precedence and the remote one will not be
|
||||
reached. Remove one if that is not what you meant.
|
||||
```
|
||||
|
||||
## When a teapot goes away
|
||||
|
||||
A dead upstream is not a broken service, and the status says which:
|
||||
|
||||
| What happened | Status |
|
||||
| --- | --- |
|
||||
| The link is down (closed, or the heartbeat gave up) | **503** Service Unavailable |
|
||||
| The link is up but the teapot didn't answer in `timeoutMs` | **504** Gateway Timeout |
|
||||
| The teapot answered with an error | whatever it said |
|
||||
|
||||
503 arrives **immediately** — a closed socket cannot deliver the frame, so waiting `timeoutMs` (30s by default) would just make the caller pay for a verdict already known.
|
||||
|
||||
Each teacup pings its teapots every `heartbeatMs` (15s by default) and closes a link after two unanswered rounds. This is what catches a **half-open** connection — a dropped route, a killed container, a NAT that timed out — where the socket still looks open with nobody home. Without it, a teacup only finds out on the next request, which pays the full timeout first.
|
||||
|
||||
```typescript
|
||||
mesh: { teapots: [...], heartbeatMs: 5000 } // notice sooner, chatter more
|
||||
```
|
||||
|
||||
Ping and pong are ordinary mesh frames rather than WebSocket protocol pings, because the platform `WebSocket` on Deno and Bun does not expose `ws.ping()` — a protocol-level heartbeat could not work on every runtime mesh supports.
|
||||
|
||||
**An app-scope export survives its teapot.** It is resolved once and memoised, so a provider keeps answering from cache after the link drops — with a value that can go stale. Reconnect reconciliation is a known gap.
|
||||
|
||||
## Protocol version
|
||||
|
||||
Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug.
|
||||
|
||||
Bump the version and old peers refuse the connection loudly instead of misreading a frame.
|
||||
|
||||
:::note[Skeleton limitations (by design)]
|
||||
No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`.
|
||||
:::
|
||||
@@ -1,43 +0,0 @@
|
||||
---
|
||||
title: OpenAPI
|
||||
description: "Generate a structural OpenAPI 3.1 document from the route graph."
|
||||
---
|
||||
|
||||
Because the request pipeline is [data you can read](/docs/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/docs/guides/introspection/), it emits **OpenAPI**.
|
||||
|
||||
## `app.openapi()`
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
const spec = app.openapi({ title: 'My API', version: '1.0.0' });
|
||||
// → OpenAPI 3.1 document
|
||||
```
|
||||
|
||||
It reads the routes and handler signatures and produces, for each route:
|
||||
|
||||
- the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
|
||||
- the **explicitly declared method**, including `@Head` and `@Options`;
|
||||
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
||||
- a **request body** entry for routes that read `@body()`;
|
||||
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
||||
|
||||
WebSocket routes are omitted (they aren't request/response).
|
||||
|
||||
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
|
||||
|
||||
## Serve it — `devOpenapi`
|
||||
|
||||
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devOpenapi: true });
|
||||
// GET /__openapi__ → application/json
|
||||
```
|
||||
|
||||
## What's structural (and what isn't yet)
|
||||
|
||||
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
|
||||
|
||||
- **Request/response body schemas.** [Standard Schema](/docs/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
|
||||
|
||||
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
title: Plugins & observability
|
||||
description: "Extending the app safely via bus.on and scope.add."
|
||||
---
|
||||
|
||||
A plugin is a function that receives the app's API at boot. It gets exactly two
|
||||
capabilities: **observe** the running system through `bus.on(...)`, and **extend its own
|
||||
scope** through `scope.add(...)`. That's the whole surface — and it's deliberately narrow.
|
||||
|
||||
```typescript
|
||||
const logger = (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
|
||||
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
|
||||
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
|
||||
};
|
||||
|
||||
const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
```
|
||||
|
||||
## Isolation is structural
|
||||
|
||||
A plugin can add steps and providers to **its own scope** via `scope.add(...)`. It
|
||||
**cannot** reorder or delete another scope's steps. The graph — not a policy check —
|
||||
enforces this: each scope owns its nodes, and a plugin has no handle on anyone else's.
|
||||
There's no ordering hook to abuse and no step registry to mutate. If you want a plugin to
|
||||
influence execution, it does so by contributing a node with declared `needs`/`provides`,
|
||||
and the framework computes where that node lands.
|
||||
|
||||
:::note
|
||||
Because execution is per-route (a route runs only the transitive closure of its handler's
|
||||
`@needs`), a plugin step that should run on **every** route must produce nothing — add it
|
||||
with `provides: []`. A step that produces no token has nothing to gate on, so the framework
|
||||
runs it unconditionally. See [The graph](/docs/concepts/the-graph/) for how the closure is
|
||||
computed.
|
||||
:::
|
||||
|
||||
## Lifecycle & request events
|
||||
|
||||
Subscribe to events on the `Bus` to observe boot, per-request execution, streaming, and
|
||||
mesh activity without touching the pipeline itself:
|
||||
|
||||
```typescript
|
||||
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
|
||||
api.bus.on('request:step:enter', (p: any) => { /* ... */ });
|
||||
api.bus.on('request:step:leave', (p: any) => { /* ... */ });
|
||||
```
|
||||
|
||||
The full event vocabulary:
|
||||
|
||||
- `boot:provider:*` — provider lifecycle during boot
|
||||
- `request:step:*` — a step entering/exiting during a request
|
||||
- `stream:open | stream:close | stream:error` — SSE/WS stream lifecycle
|
||||
- `mesh:connect | mesh:disconnect | mesh:rpc:error` — mesh link and RPC activity
|
||||
- `plugin:mounted` — a plugin finished mounting
|
||||
|
||||
Observation is read-only: handlers see the event payload but can't alter control flow. To
|
||||
change behavior, contribute a node to your scope — see
|
||||
[Dependency injection](/docs/guides/dependency-injection/).
|
||||
@@ -1,74 +0,0 @@
|
||||
---
|
||||
title: Routing
|
||||
description: "Route constraints, specificity, HEAD and OPTIONS semantics, and path validation."
|
||||
---
|
||||
|
||||
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
|
||||
|
||||
## Method decorators
|
||||
|
||||
| Decorator | Method / transport |
|
||||
|---|---|
|
||||
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
|
||||
| `@Sse` | server-sent events (`text/event-stream`) |
|
||||
| `@Ws` | WebSocket duplex |
|
||||
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
|
||||
|
||||
```typescript
|
||||
@Route('/users')
|
||||
class Users {
|
||||
@Get('/:id') get(@param('id') id: string) { /* ... */ }
|
||||
@Post('/') create(@body() data: unknown) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
The path a route matches is `joinPath(module.mountpoint, route.path)` — a controller under `@Module({ mountpoint: '/api' })` with `@Route('/users')` + `@Get('/:id')` serves `/api/users/:id`.
|
||||
|
||||
## Pattern segments
|
||||
|
||||
- **Static** — `users` matches exactly.
|
||||
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
|
||||
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
|
||||
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
|
||||
|
||||
```typescript
|
||||
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
|
||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||
```
|
||||
|
||||
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
|
||||
|
||||
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
|
||||
|
||||
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
|
||||
|
||||
## Precedence
|
||||
|
||||
When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
|
||||
|
||||
```typescript
|
||||
@Get('/a/b') // wins for /a/b
|
||||
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
|
||||
@Get('/a/:id') // wins for /a/x
|
||||
@Get('/a/:rest*') // wins for /a/x/y
|
||||
```
|
||||
|
||||
Two routes under the same method cannot have the same effective shape: `/users/:id` and `/users/:name` are ambiguous and make boot fail with both declarations named. The same rule applies after mesh routes join. Different methods may reuse a shape.
|
||||
|
||||
## HEAD and OPTIONS
|
||||
|
||||
An explicit `@Head` or `@Options` route always wins. Without an explicit HEAD route, HEAD falls back to a matching **buffered** GET handler, preserves its status and headers, and suppresses the body. Streaming GET routes do not become implicit HEAD routes.
|
||||
|
||||
Without an explicit OPTIONS route, OPTIONS on an existing path returns `204` with a canonical `Allow` header. GET implies HEAD, and any existing path implies OPTIONS, so a GET/POST path reports `GET, HEAD, POST, OPTIONS`. A CORS preflight (OPTIONS with `Access-Control-Request-Method`) is handled before explicit or automatic OPTIONS when CORS is configured.
|
||||
|
||||
## Path policy and 404 vs 405
|
||||
|
||||
`/path` and `/path/` are equivalent. Repeated slashes such as `/path//item` are rejected rather than collapsed, and malformed percent encoding is rejected; both return `400 Bad Request` with the configured security/CORS headers. Query strings do not participate in route matching.
|
||||
|
||||
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
|
||||
|
||||
## Matcher scale
|
||||
|
||||
Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
|
||||
|
||||
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
|
||||
@@ -1,141 +0,0 @@
|
||||
---
|
||||
title: Runtimes (Node, Deno, Bun, edge)
|
||||
description: "Run Green Tea anywhere with app.fetch — the Web-Standards handler."
|
||||
---
|
||||
|
||||
Green Tea exposes a Web-Standards handler, `app.fetch(request): Promise<Response>`, so the
|
||||
same app runs on any runtime that speaks the Fetch API — for **HTTP and SSE** today.
|
||||
|
||||
```ts
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
|
||||
// Node (native listener, TLS, timeouts)
|
||||
app.listen(3000);
|
||||
|
||||
// Deno
|
||||
Deno.serve(app.fetch);
|
||||
|
||||
// Bun
|
||||
Bun.serve({ fetch: app.fetch });
|
||||
|
||||
// Cloudflare / edge
|
||||
export default { fetch: app.fetch };
|
||||
```
|
||||
|
||||
**Node is the reference implementation.** A parity suite pins `app.fetch` to Node's native
|
||||
listener — identical status, headers, and body for the same request. The other runtimes drive
|
||||
that *same* `app.fetch` / `app.upgrade` core, so they inherit that behaviour rather than
|
||||
re-implementing it, and each carries its own smoke tests: Deno and Bun cover WebSocket and mesh,
|
||||
and edge runs against real workerd (Miniflare).
|
||||
|
||||
**All four runtimes now have full WebSocket support:** Node via `app.listen()`, Deno and Bun via
|
||||
`serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph,
|
||||
same `@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts
|
||||
remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha)
|
||||
runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge.
|
||||
|
||||
**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full
|
||||
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
|
||||
non-Node runtimes, also bound request size at the platform/runtime layer.
|
||||
|
||||
## WebSocket on Deno
|
||||
|
||||
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
|
||||
upgrade, so Deno gets a dedicated adapter at `@green-tea/core/deno`:
|
||||
|
||||
```ts
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { serveDeno } from '@green-tea/core/deno';
|
||||
|
||||
const app = createApp({ modules: [ChatModule] });
|
||||
|
||||
// HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket — one call:
|
||||
serveDeno(app, { port: 8000 });
|
||||
```
|
||||
|
||||
`serveDeno` routes normal requests through `app.fetch` and WebSocket upgrades through
|
||||
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
|
||||
run on Node. Behaviour matches the Node reference.
|
||||
|
||||
**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses.
|
||||
Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`,
|
||||
`close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the
|
||||
same primitive (see below).
|
||||
|
||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get
|
||||
`app.fetch` + `serveDeno`. [Mesh](/docs/guides/mesh/) works here: the control channel is
|
||||
served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`.
|
||||
|
||||
## WebSocket on Bun
|
||||
|
||||
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
|
||||
upgrade, so Bun gets a dedicated adapter at `@green-tea/core/bun`:
|
||||
|
||||
```ts
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { serveBun } from '@green-tea/core/bun';
|
||||
|
||||
const app = createApp({ modules: [ChatModule] });
|
||||
|
||||
// HTTP + SSE via app.fetch, WebSocket via Bun's server-level handler — one call:
|
||||
serveBun(app, { port: 8000 });
|
||||
```
|
||||
|
||||
`serveBun` routes normal requests through `app.fetch` and WebSocket upgrades through
|
||||
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
|
||||
run on Node and Deno. Behaviour matches the Node reference.
|
||||
|
||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get
|
||||
`app.fetch` + `serveBun`. [Mesh](/docs/guides/mesh/) works here too.
|
||||
|
||||
## Cloudflare Workers / edge
|
||||
|
||||
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
|
||||
upgrade, so Cloudflare Workers get a dedicated adapter at `@green-tea/core/edge`:
|
||||
|
||||
```ts
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { edgeHandler } from '@green-tea/core/edge';
|
||||
|
||||
const app = createApp({ modules: [ChatModule] });
|
||||
|
||||
export default { fetch: edgeHandler(app) };
|
||||
```
|
||||
|
||||
`edgeHandler` routes normal requests through `app.fetch` and WebSocket upgrades through
|
||||
`WebSocketPair` and `app.upgrade` — the same neutral primitive `serveDeno` and `serveBun`
|
||||
use. Same graph, same `@Ws` handlers, same rooms/channels as Node/Deno/Bun; behaviour
|
||||
matches the Node reference; validated on real workerd (Miniflare).
|
||||
|
||||
**Requirement:** the Worker must enable the `nodejs_compat` compatibility flag —
|
||||
`wrangler.toml`:
|
||||
|
||||
```toml
|
||||
compatibility_flags = ["nodejs_compat"]
|
||||
compatibility_date = "2024-09-23" # or later
|
||||
```
|
||||
|
||||
Green Tea's core statically imports Node built-ins that workerd only provides under
|
||||
this flag; without it, the Worker fails to load.
|
||||
|
||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/docs/guides/mesh/)
|
||||
is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s
|
||||
`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's
|
||||
Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts
|
||||
WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection
|
||||
open for its lifetime rather than hibernating between messages.
|
||||
|
||||
## Filesystem features — Node/Deno/Bun only
|
||||
|
||||
A few [HTML & views](/docs/guides/html/) features read from disk, so they need a runtime with
|
||||
a filesystem:
|
||||
|
||||
- `@Html('file.html')` — reads and caches the file at boot.
|
||||
- `@Html('file.html', { template: true })` — same, then renders it per request.
|
||||
- `createApp({ static })` — serves a directory of files.
|
||||
|
||||
All three throw at boot (`createApp()`/route-build time) on a runtime without a
|
||||
filesystem, rather than failing per-request. On the edge, use bare `@Html` returning a
|
||||
string instead — pair it with the exported `render` over a template string you `import`
|
||||
as a module (so it ships in the bundle, no disk read), and serve other assets (images,
|
||||
CSS, JS) from a CDN in front of the Worker.
|
||||
@@ -1,103 +0,0 @@
|
||||
---
|
||||
title: Transport security
|
||||
description: "TLS and wss, secure-by-default headers, CORS, and trustProxy."
|
||||
---
|
||||
|
||||
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
|
||||
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/docs/reference/createapp/)
|
||||
for the full option list.
|
||||
|
||||
## TLS (native https/wss)
|
||||
|
||||
```typescript
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const app = createApp({
|
||||
modules: [App],
|
||||
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
||||
});
|
||||
```
|
||||
|
||||
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
|
||||
port — no other changes.
|
||||
|
||||
## `trustProxy`
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [App], trustProxy: true });
|
||||
```
|
||||
|
||||
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
|
||||
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
|
||||
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
|
||||
unconditionally; there's no CIDR allowlist yet.
|
||||
|
||||
## CORS
|
||||
|
||||
Off unless `origins` is set.
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [App],
|
||||
cors: { origins: 'https://app.example.com', credentials: true },
|
||||
});
|
||||
```
|
||||
|
||||
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||
request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
|
||||
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
|
||||
route or the router's automatic `204` + `Allow` response.
|
||||
|
||||
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
|
||||
echoes the concrete allowed origin (or blocks the request).
|
||||
|
||||
:::caution[Reflect-any foot-gun]
|
||||
`origins: '*'` together with `credentials: true` reflects *any* origin with credentials
|
||||
attached. Only combine them if you truly intend an open credentialed API; prefer an explicit
|
||||
allowlist.
|
||||
:::
|
||||
|
||||
## `security` (headers, ON by default)
|
||||
|
||||
Applied to every HTTP response. Disable everything with `security: false`, or override
|
||||
individual headers with an options object.
|
||||
|
||||
| Header | Default |
|
||||
|---|---|
|
||||
| `X-Content-Type-Options` | `nosniff` |
|
||||
| `X-Frame-Options` | `SAMEORIGIN` |
|
||||
| `Referrer-Policy` | `no-referrer` |
|
||||
| `X-DNS-Prefetch-Control` | `off` |
|
||||
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
|
||||
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
|
||||
```
|
||||
|
||||
:::note[Scope caveat]
|
||||
`security` and `cors` headers apply to HTTP responses; they do **not** apply to the
|
||||
WebSocket handshake (101/upgrade) response.
|
||||
:::
|
||||
|
||||
:::caution[TLS + trustProxy]
|
||||
HSTS is emitted only when the connection is judged secure. With `trustProxy: true` that
|
||||
judgement trusts the incoming `X-Forwarded-Proto` header — so a client that spoofs
|
||||
`X-Forwarded-Proto: http` past a permissive proxy can make the server treat the request as
|
||||
insecure and **suppress the HSTS header**. Only enable `trustProxy` behind a proxy that
|
||||
strips and sets forwarded headers itself, and terminate TLS where you control that hop.
|
||||
:::
|
||||
|
||||
## Defaults
|
||||
|
||||
| Option | Default |
|
||||
|---|---|
|
||||
| `tls` | off (plain http/ws) |
|
||||
| `trustProxy` | off |
|
||||
| `cors` | off (same-origin only) |
|
||||
| `security` | ON (HSTS only when the connection is secure) |
|
||||
|
||||
## Related
|
||||
|
||||
- [`createApp` reference](/docs/reference/createapp/) — every construction option
|
||||
- [File uploads / multipart](/docs/guides/uploads/) — request-body handling
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
title: Streaming & real-time
|
||||
description: "SSE, ndjson, and WebSocket duplex from one AsyncIterable primitive."
|
||||
---
|
||||
|
||||
Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app.
|
||||
|
||||
green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
|
||||
|
||||
## One primitive, three modes
|
||||
|
||||
| Declare | Direction | Transport | Reach for it when |
|
||||
|---|---|---|---|
|
||||
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
||||
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
|
||||
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
|
||||
|
||||
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
|
||||
|
||||
- **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
|
||||
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
|
||||
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
|
||||
|
||||
:::note
|
||||
Streaming bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/docs/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`.
|
||||
:::
|
||||
|
||||
## Streaming — SSE
|
||||
|
||||
A route decorated `@Sse` streams — that's what triggers it, not the return value. It must return an `AsyncIterable`; the transport frames each value as an SSE event, handles backpressure, and cleans up on disconnect (the transformer is bypassed).
|
||||
|
||||
```typescript
|
||||
import { Route, Sse } from '@green-tea/core';
|
||||
|
||||
@Route('/feed')
|
||||
class FeedController {
|
||||
@Sse('/ticks')
|
||||
ticks() {
|
||||
return (async function* () {
|
||||
for (let n = 1; n <= 3; n++) yield { tick: n };
|
||||
})();
|
||||
}
|
||||
}
|
||||
// GET /feed/ticks (Accept: text/event-stream)
|
||||
// data: {"tick":1}
|
||||
// data: {"tick":2}
|
||||
// data: {"tick":3}
|
||||
```
|
||||
|
||||
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE, `Upgrade: websocket` → WS, else ndjson chunked).
|
||||
|
||||
## Streaming — WebSocket duplex
|
||||
|
||||
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step that consumes one channel and produces another.
|
||||
|
||||
```typescript
|
||||
import { Route, Ws, inbound, channel } from '@green-tea/core';
|
||||
|
||||
@Route('/chat')
|
||||
class ChatController {
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => {
|
||||
for await (const msg of incoming) out.push(`echo: ${msg}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
|
||||
|
||||
:::note[WebSocket needs the `ws` peer]
|
||||
`@Ws` (and mesh) require the optional [`ws`](https://github.com/websockets/ws) peer dependency — `npm i ws`. SSE, ndjson, and plain HTTP need nothing extra.
|
||||
:::
|
||||
|
||||
## Fan-out — `channel()` and `rooms`
|
||||
|
||||
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
|
||||
|
||||
```typescript
|
||||
@Route('/live')
|
||||
class Live {
|
||||
@Sse('/prices') // one iterable out — each yield is an event
|
||||
prices() {
|
||||
return (async function* () {
|
||||
while (true) { yield { btc: await getPrice() }; await sleep(1000); }
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/echo') // duplex — consume @inbound, return the outbound stream
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
||||
|
||||
`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/docs/guides/security/) for handshake authentication.
|
||||
|
||||
## Transport is declared, not inferred
|
||||
|
||||
A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never because a handler happened to return an `AsyncIterable`. In most frameworks the return type decides the wire format; in green-tea the decorator decides, and the return value is enforced against it:
|
||||
|
||||
| Declare | Handler must return | Otherwise |
|
||||
|---|---|---|
|
||||
| `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
||||
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
||||
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
||||
|
||||
This is the anti-Express guarantee: your wire contract is what you **declared**, never a surprise sprung by a return value. A buffered route can't accidentally start streaming because someone returned a generator; a streaming route can't silently downgrade to a buffered response because someone forgot a `yield`. Declare `@Sse` / `@Stream` / `@Ws` to stream — the return value never changes a route's transport.
|
||||
@@ -1,33 +0,0 @@
|
||||
---
|
||||
title: Testing
|
||||
description: "Swap any node with createApp overrides for fast, isolated tests."
|
||||
---
|
||||
|
||||
Any provider or step is addressable by its **token**, so you can swap it for a test double
|
||||
at construction time — no monkey-patching, no module rewiring.
|
||||
|
||||
## Override tokens in tests
|
||||
|
||||
Pass `overrides` to `createApp`. Each key is a token; each value is either a plain object
|
||||
(wrapped as `{ token: value }`) or a function runner:
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
overrides: {
|
||||
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
|
||||
user: () => ({ user: { id: 'stub' } }), // function runner
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Overrides replace **only** the named token's runner; the rest of the graph is untouched. The
|
||||
route still runs its full closure — you've just substituted what one node produces.
|
||||
|
||||
:::note
|
||||
An override for an unknown token throws. The set of tokens is validated against the real
|
||||
graph, so a typo'd or stale override is a construction-time error, not a silent no-op.
|
||||
:::
|
||||
|
||||
This pairs well with [`app.explain(route)`](/docs/guides/introspection/) — explain the chain to
|
||||
see which tokens a route actually depends on, then override exactly those.
|
||||
@@ -1,71 +0,0 @@
|
||||
---
|
||||
title: File uploads
|
||||
description: "multipart parsing via the optional busboy peer dependency."
|
||||
---
|
||||
|
||||
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` instead of a plain object.
|
||||
|
||||
:::caution[multipart needs the optional `busboy` peer]
|
||||
Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns **`501`**. (JSON and urlencoded need nothing extra.)
|
||||
:::
|
||||
|
||||
```typescript
|
||||
import { Route, Post, body } from '@green-tea/core';
|
||||
import type { MultipartBody } from '@green-tea/core';
|
||||
|
||||
@Route('/profile')
|
||||
class ProfileController {
|
||||
@Post('/avatar')
|
||||
upload(@body() form: MultipartBody) {
|
||||
const name = form.fields.name; // string | string[]
|
||||
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
|
||||
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
|
||||
|
||||
:::note[Access asymmetry]
|
||||
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/docs/guides/arguments/) for how `@body()` behaves across content types.
|
||||
:::
|
||||
|
||||
## Repeated fields — `bodyDuplicates`
|
||||
|
||||
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded). Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead — this applies to **both** urlencoded and multipart text fields:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
|
||||
```
|
||||
|
||||
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of `bodyDuplicates`.
|
||||
|
||||
## Per-endpoint override
|
||||
|
||||
```typescript
|
||||
@Post('/upload', { duplicates: 'array' })
|
||||
upload(@body() form: MultipartBody) { /* ... */ }
|
||||
```
|
||||
|
||||
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
|
||||
|
||||
## Limits
|
||||
|
||||
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any other request body (over the limit → **413**). `maxParts` (default `1000`) caps the number of multipart parts per request:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||
```
|
||||
|
||||
Both limits can be overridden **per route** — an upload endpoint can allow a larger body than the rest of the API:
|
||||
|
||||
```typescript
|
||||
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 })
|
||||
uploadAvatar(@body() form: MultipartBody) { /* ... */ }
|
||||
```
|
||||
|
||||
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
|
||||
|
||||
:::note
|
||||
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/docs/guides/validation/).
|
||||
:::
|
||||
@@ -1,84 +0,0 @@
|
||||
---
|
||||
title: Validation
|
||||
description: "Validate and coerce input with Standard Schema (zod, valibot, arktype)."
|
||||
---
|
||||
|
||||
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
|
||||
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
|
||||
and others). green-tea's core has **zero runtime dependency** on any of them — bring
|
||||
whichever validator you already use.
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
import { Route, Post, body } from '@green-tea/core';
|
||||
|
||||
const CreateUser = z.object({ email: z.string().email() });
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Post('/')
|
||||
create(@body(CreateUser) user: { email: string }) {
|
||||
return { created: user.email };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Parsed value replaces the argument; `ctx` stays raw
|
||||
|
||||
The value the handler receives is the schema's **parsed/coerced output**, not the raw
|
||||
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
|
||||
parsed. Query strings are always strings on the wire, so a schema is often the coercion
|
||||
point:
|
||||
|
||||
```typescript
|
||||
const ListQuery = z.object({ page: z.coerce.number() });
|
||||
|
||||
@Get('/list')
|
||||
list(@query(ListQuery) q: { page: number }) {
|
||||
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
|
||||
}
|
||||
```
|
||||
|
||||
## Where the schema goes (the one asymmetry)
|
||||
|
||||
:::note[Access shape]
|
||||
`@param('id', Schema)` takes the key in slot 1 and the schema in slot 2 — `@param` always
|
||||
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
|
||||
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
|
||||
object (all of `body`/`query`/`headers`).
|
||||
:::
|
||||
|
||||
See [Argument decorators](/docs/guides/arguments/) for the full slot semantics of each decorator.
|
||||
|
||||
## Failure: 422 with per-field issues
|
||||
|
||||
A failing schema short-circuits the request with **422**:
|
||||
|
||||
```json
|
||||
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
|
||||
```
|
||||
|
||||
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
|
||||
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
|
||||
|
||||
## Caveats
|
||||
|
||||
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
|
||||
the same handler are not checked in that request.
|
||||
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
|
||||
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
|
||||
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
|
||||
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
|
||||
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
|
||||
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
|
||||
|
||||
:::note[Not covered yet]
|
||||
Response/output validation, validating a `@Step`'s own inputs, and mesh remote-route
|
||||
validation are all out of scope for this feature.
|
||||
:::
|
||||
|
||||
## Related
|
||||
|
||||
- [Argument decorators](/docs/guides/arguments/) — every slot decorator and its parsing rules
|
||||
- [File uploads / multipart](/docs/guides/uploads/) — how multipart bodies are parsed before validation
|
||||
- [`createApp` reference](/docs/reference/createapp/) — app construction options
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user