Compare commits
185
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a16be6a832 | ||
|
|
b0a9f3bfc9 | ||
|
|
9a8677d5c2 | ||
|
|
8c95ae8bfb | ||
|
|
daf0fed8ab | ||
|
|
c5a8361c14 | ||
|
|
a57223cef9 | ||
|
|
9634ec73e8 | ||
|
|
cbeab73626 | ||
|
|
58ba18f9f8 | ||
|
|
a30c2cecb3 | ||
|
|
1364d54ab4 | ||
|
|
7a01ca3068 | ||
|
|
e0da6cee16 | ||
|
|
b3152aac45 | ||
|
|
3fc761ce16 | ||
|
|
80f3f532f2 | ||
|
|
e83d62cc1a | ||
|
|
73a4a9f6cd | ||
|
|
25f4144a38 | ||
|
|
6717b15ee9 | ||
|
|
0ce81b08f3 | ||
|
|
249fc00f80 | ||
|
|
6e050197b6 | ||
|
|
8ef7c3ee14 | ||
|
|
e69f604053 | ||
|
|
727987286b | ||
|
|
bff8778112 | ||
|
|
1bcaa463f2 | ||
|
|
f5d4d0cd74 | ||
|
|
03132b2048 | ||
|
|
9f5792c1c5 | ||
|
|
4e8aacb6b7 | ||
|
|
3b680480ab | ||
|
|
414b188792 | ||
|
|
6e66b05a41 | ||
|
|
55890442fe | ||
|
|
f6c05a0929 | ||
|
|
419ba092d4 | ||
|
|
85b6c703bb | ||
|
|
dfe71102ca | ||
|
|
cd4a9f65f6 | ||
|
|
aa15862f3b | ||
|
|
0c099c7266 | ||
|
|
c472d4c0de | ||
|
|
f18aa9a42a | ||
|
|
7ccb55d07a | ||
|
|
e61771077c | ||
|
|
9c78842684 | ||
|
|
8c5855c59e | ||
|
|
e7b1c462e6 | ||
|
|
a84960a46a | ||
|
|
86a0d9c91b | ||
|
|
7d39aebfab | ||
|
|
7b3fe57590 | ||
|
|
ccd329d12b | ||
|
|
b75158eddc | ||
|
|
0adab69466 | ||
|
|
1c4f3fb8cb | ||
|
|
1e76921d49 | ||
|
|
c00f714aa8 | ||
|
|
5294e62a5a | ||
|
|
3930804fb3 | ||
|
|
5d8363d225 | ||
|
|
0f2f62d8c1 | ||
|
|
4c9e606cfb | ||
|
|
f08956bea8 | ||
|
|
b8b3548f15 | ||
|
|
855e044d2a | ||
|
|
e5d5fb801a | ||
|
|
4896ee86d2 | ||
|
|
bb0b01cf26 | ||
|
|
d93037e2a0 | ||
|
|
ff94e55496 | ||
|
|
82e1678dea | ||
|
|
4b04421ddd | ||
|
|
0fad12688d | ||
|
|
ead71dc1b1 | ||
|
|
19fcc18899 | ||
|
|
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
|
||||
@@ -1,13 +1,30 @@
|
||||
name: Promote → GitHub
|
||||
|
||||
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
|
||||
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
|
||||
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
|
||||
# its release workflow (production publish).
|
||||
# Promotion. Runs on GITEA ONLY. Mirrors two branches to the public GitHub repo and nothing else:
|
||||
#
|
||||
# main → GitHub main the production mirror
|
||||
# develop → GitHub contrib what outside contributors fork from and target
|
||||
#
|
||||
# Feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
|
||||
# would expose every branch).
|
||||
#
|
||||
# Neither push is forced. For `contrib` that is the guard, not a limitation: the push is refused
|
||||
# exactly when `contrib` holds external merges that have not been carried into `develop` yet
|
||||
# (AGENTS.md, "External contributions"). Carry them and the next develop push fast-forwards.
|
||||
#
|
||||
# Tags are deliberately NOT mirrored. The same `v*` tag means two different things on the two
|
||||
# forges: on Gitea it stages to Verdaccio (`stage.yml`), on GitHub it publishes to npm and
|
||||
# JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
|
||||
# decision a person takes after reading the staging run, not a side effect of creating it:
|
||||
#
|
||||
# git push gh v<version>
|
||||
#
|
||||
# `--tags` is left off the branch push for the same reason. It used to ride along here, which
|
||||
# meant any tag sitting in the runner's clone could reach production as a side effect of
|
||||
# promoting `main` — a publish nobody chose, of a commit nobody was looking at.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
branches: [main, develop]
|
||||
|
||||
jobs:
|
||||
push-github:
|
||||
@@ -16,15 +33,18 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # full history + tags for a clean push
|
||||
- name: Push main + tags to GitHub
|
||||
fetch-depth: 0 # full history for a clean push
|
||||
- name: Push to GitHub
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
||||
run: |
|
||||
case "$GITHUB_REF_NAME" in
|
||||
main) target=main ;;
|
||||
develop) target=contrib ;;
|
||||
*) echo "::error::promote runs for main and develop only, got '$GITHUB_REF_NAME'"; exit 1 ;;
|
||||
esac
|
||||
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
git push github "refs/tags/${{ github.ref_name }}"
|
||||
else
|
||||
git push github "HEAD:refs/heads/main"
|
||||
git push github --tags
|
||||
if ! git push github "HEAD:refs/heads/${target}"; then
|
||||
echo "::error::GitHub ${target} has commits that ${GITHUB_REF_NAME} does not. For contrib that means external merges not yet carried into develop — carry them (AGENTS.md, External contributions); never force this push."
|
||||
exit 1
|
||||
fi
|
||||
@@ -12,9 +12,11 @@ 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
|
||||
contents: write # create the GitHub release for this tag
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
@@ -23,13 +25,95 @@ 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
|
||||
# A publish sets exactly one dist-tag, and it is the only npm write this workflow can make:
|
||||
# Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token
|
||||
# it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag
|
||||
# the publish gets has to be the one that matters most.
|
||||
#
|
||||
# While no stable release exists, `latest` and the channel tag mean the same thing — there is
|
||||
# nothing else to install — and `latest` takes it, because that is what a bare
|
||||
# `npm install @green-tea/core` resolves to. Leaving it behind on an older beta would hand the
|
||||
# default install an older build than the one just released. The channel tag is then moved by
|
||||
# hand; the step prints the command. Once a stable version exists it owns `latest` for good,
|
||||
# a later beta must not drag it backwards, and the channel tag becomes the automatic one again.
|
||||
- name: Publish to npmjs
|
||||
run: |
|
||||
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"
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
|
||||
# Read the list into a variable so a failed lookup fails the step, rather than passing for
|
||||
# "no stable exists" and pointing `latest` at a prerelease that should not have it.
|
||||
VERSIONS=$(npm view "$PKG" versions --json)
|
||||
if [ "$CHANNEL" != latest ] \
|
||||
&& ! node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
|
||||
TAG=latest
|
||||
else
|
||||
TAG=$CHANNEL
|
||||
fi
|
||||
echo "$VERSION under dist-tag: $TAG"
|
||||
# Skip rather than fail when the version is already up, so a re-run after a later failure
|
||||
# can finish the remaining work instead of dying on a duplicate npm rejects anyway.
|
||||
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
|
||||
echo "npm already has $VERSION"
|
||||
else
|
||||
npm publish --access public --tag "$TAG"
|
||||
fi
|
||||
if [ "$TAG" != "$CHANNEL" ]; then
|
||||
echo "::notice::Move the channel tag by hand: npm dist-tag add $PKG@$VERSION $CHANNEL"
|
||||
fi
|
||||
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
|
||||
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
|
||||
# failure *after* it would cost a version number permanently. Version and entry points come
|
||||
# from deno.json, which `test/package-metadata.test.ts` pins to package.json — JSR has no
|
||||
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
|
||||
# id-token npm just used; the package is linked to this repository on jsr.io.
|
||||
- name: Publish to JSR
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
PKG=${PKG#@}
|
||||
# 404 until the version exists, and also for a package with no versions at all — which is
|
||||
# what this one was until v26.8.0-beta.1 — so the guard must not read a 404 as an error.
|
||||
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
|
||||
echo "JSR already has $VERSION"
|
||||
else
|
||||
deno publish
|
||||
fi
|
||||
|
||||
# The release page is where people who do not read a changelog find out what changed, and a
|
||||
# repository with tags and no releases reads as abandoned. Notes come from CHANGELOG.md rather
|
||||
# than from the commit range: the section was written for humans and already exists by the time
|
||||
# a tag is cut, and generated notes would restate merge subjects nobody chose.
|
||||
#
|
||||
# Idempotent like the publishes above, so a re-run after a later failure does not stop here.
|
||||
# `--verify-tag` refuses to invent a tag: the release attaches to the one that triggered this
|
||||
# run and can never move it. A prerelease is marked as such, which is what keeps GitHub's
|
||||
# "Latest" badge off a beta.
|
||||
- name: Create the GitHub release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG=${GITHUB_REF_NAME}
|
||||
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
echo "release $TAG already exists"; exit 0
|
||||
fi
|
||||
node scripts/changelog-section.mjs "$VERSION" "$TAG" > /tmp/notes.md
|
||||
case "$VERSION" in *-*) PRE=--prerelease ;; *) PRE= ;; esac
|
||||
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" \
|
||||
--notes-file /tmp/notes.md --verify-tag $PRE
|
||||
@@ -1,12 +1,18 @@
|
||||
name: Stage → Verdaccio
|
||||
|
||||
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
|
||||
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
|
||||
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
|
||||
# internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag.
|
||||
# Staging versions are intentionally mutable: an existing prerelease is removed before
|
||||
# publishing the updated release candidate under the same version.
|
||||
#
|
||||
# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path —
|
||||
# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we
|
||||
# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm
|
||||
# allows 72 hours to unpublish and JSR allows nothing at all.
|
||||
on:
|
||||
push:
|
||||
branches: ['release/**']
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
publish-stg:
|
||||
@@ -18,7 +24,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
|
||||
@@ -27,6 +38,11 @@ jobs:
|
||||
run: |
|
||||
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||
VER=$(node -p "require('./package.json').version")
|
||||
# Staging overwrites the version it publishes, and a stable number that changes
|
||||
# under an internal consumer is worse than no staging at all. This will need
|
||||
# revisiting at the first stable release, which is exactly the one most worth
|
||||
# staging: the answer is probably to stage it under a suffixed version rather
|
||||
# than to drop the guard.
|
||||
case "$VER" in
|
||||
*-*) ;;
|
||||
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
||||
|
||||
+14
-3
@@ -1,6 +1,13 @@
|
||||
# Local specs & plans — not committed
|
||||
.specs/
|
||||
|
||||
# Per-developer agent state: local settings and tool locks, one directory per assistant. Nothing
|
||||
# here is shared configuration — `.serena/` even ships its own .gitignore. A repository-wide
|
||||
# `.claude/settings.json` is a real convention and would need a `!` line here to be committable;
|
||||
# none exists today, so this stays a blanket ignore rather than a rule for a file nobody wrote.
|
||||
.claude/
|
||||
.serena/
|
||||
|
||||
# Node
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -11,9 +18,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,142 @@
|
||||
# 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 `develop` automatically — `develop` under the name `contrib` — and release tags only by hand.
|
||||
|
||||
```
|
||||
feature/* → develop → main → [promote.yml] → GitHub main
|
||||
│ │
|
||||
└─[promote.yml]┼──→ GitHub contrib ← external PRs
|
||||
↑ │ │
|
||||
└── carried back by hand ─┘ (a PR into develop)
|
||||
│
|
||||
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
|
||||
└─── GitHub (pushed by hand): [release.yml] → npm + JSR
|
||||
```
|
||||
|
||||
- **Gitea `develop`** — active development.
|
||||
- **Gitea `main`** — staging. Merging here publishes nothing. A `v*` tag here publishes to the internal Verdaccio, never to a public registry.
|
||||
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
|
||||
- **GitHub `contrib`** — mirror of `develop`, pushed by `promote.yml` on every develop merge, and where outside contributions land. GitHub only: there is no Gitea `contrib`.
|
||||
|
||||
`develop` and `main` on Gitea have direct push disabled with an empty whitelist, so nobody can push to them, admins included. Advance them by opening a PR and merging it.
|
||||
|
||||
## 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.
|
||||
|
||||
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
|
||||
|
||||
```bash
|
||||
git branch -d <branch> && git push origin --delete <branch>
|
||||
```
|
||||
|
||||
On 2026-09-22 this repository carried 36 branches on Gitea and 29 locally, every one but a single stale docs branch already merged into `develop`, some of them since July. At that size the branch list stops describing the work in flight and becomes something a release has to audit commit by commit — which is both when it costs the most and when nobody has the patience for it. `git branch -r --merged origin/develop` is the check. A branch whose commits were rebased on the way in will not appear there even though its content did land, so confirm that case by content (`git diff <branch> develop -- <file>`) rather than by the flag. Never `develop`, `main`, or a `release/*` that has not shipped yet.
|
||||
|
||||
**Diagnosing "this branch is ahead of main".** Usually it is pre-rebase duplication, not unmerged work: the same content under different SHAs, because contributions are rebased on their way into `develop`. Confirm before acting:
|
||||
|
||||
```bash
|
||||
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, fetch GitHub `contrib` into a branch on Gitea, then open a pull request from it into `develop` and merge it. The next develop push mirrors back to `contrib`, and fast-forwards because `develop` now contains everything `contrib` had. Merge rather than rebase: because promotions are fast-forward-only, `develop` and `main` are the same commit, so there is no main-only history for a merge to drag in. Rebasing would rewrite the contributor's SHAs for no gain and leave `contrib` with commits `develop` does not have, so the mirror push is refused until someone forces it. Merging keeps their commits reaching `main` under their own name and hash.
|
||||
|
||||
The exception is a `hotfix/*`, which lands on `main` without passing through `develop` and leaves the two out of step. Back-merge before taking a contribution through, or rebase that one and accept the force-push. If you do rebase, take the commit range from the pull request itself and never "everything since main": if a second contributor branched from `contrib` after the first one merged, the broad range sweeps up work that isn't theirs.
|
||||
|
||||
**Nothing to reset after a promotion.** `contrib` follows `develop` through the mirror, and there is no Gitea `contrib` to keep in step. The one thing the mirror will not do is push over external merges that were never carried in: that push is refused, the promote job fails, and the fix is to carry them as above — never to force.
|
||||
|
||||
A conflict against `develop` is visible to the contributor through `contrib`, so it can be theirs to resolve: ask them to rebase onto the current `contrib`. Only a conflict against a feature branch that has not merged yet is the maintainer's alone, because that code they cannot see.
|
||||
|
||||
## Releasing
|
||||
|
||||
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
|
||||
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
|
||||
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
|
||||
nowhere is worse than no heading at all, because the next reader believes it.
|
||||
|
||||
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
|
||||
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
|
||||
two contradictory things — that beta.1 was released, and that everything in it was not.
|
||||
|
||||
So the order is: everything merged and promoted → **close the section with the release date** → tag →
|
||||
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
|
||||
number feels.
|
||||
|
||||
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
|
||||
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
||||
A version number is a plan; a changelog heading is a receipt.
|
||||
|
||||
**A tag is created twice, on purpose.** Pushing `v*` to Gitea stages that exact commit to
|
||||
Verdaccio through the real publish path; pushing the same tag to GitHub publishes it to npm and
|
||||
JSR. Nothing promotes the tag for you — `promote.yml` mirrors `main` and only `main`, so the
|
||||
second push is a decision made after reading the first run:
|
||||
|
||||
```bash
|
||||
git push origin v<version> # Gitea → Verdaccio, reversible
|
||||
git push gh v<version> # GitHub → npm + JSR, permanent on JSR
|
||||
```
|
||||
|
||||
The split exists because a mistake caught on Verdaccio costs a re-tag, and the same mistake
|
||||
caught on JSR costs the version number forever.
|
||||
|
||||
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
|
||||
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
|
||||
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
|
||||
on `v26.8.0-beta.1`). While there is no stable release the publish spends that one tag on `latest`,
|
||||
since that is what a bare `npm install @green-tea/core` resolves to, and the workflow prints the
|
||||
command for the rest:
|
||||
|
||||
```bash
|
||||
npm dist-tag add @green-tea/core@<version> beta
|
||||
```
|
||||
|
||||
Once a stable version exists this stops being a chore: `latest` belongs to the stable release, the
|
||||
publish gives a beta its channel tag directly, and there is nothing left to move.
|
||||
|
||||
## CI
|
||||
|
||||
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
|
||||
|
||||
**The forges disagree about where workflows come from.** GitHub reads `pull_request` workflows from the base branch, so a workflow fix cannot validate itself and must reach the base before it gates anything. Gitea reads from the head. Likewise, `continue-on-error` steps report as `success` on GitHub, hiding the advisory in the log, but as `failure` with the job still green on Gitea.
|
||||
|
||||
GitHub does not run workflows on fork pull requests until a maintainer approves them. A contributor's first push may sit with no checks at all.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Conventional Commits, focused on the *why*. Every commit signed off (`git commit -s`) — the project uses a DCO, and unsigned commits are rejected. No AI co-authoring attribution.
|
||||
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
|
||||
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
|
||||
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
|
||||
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
|
||||
+214
-37
@@ -4,14 +4,14 @@
|
||||
|
||||
## Environment
|
||||
|
||||
- **Date**: 2026-07-07
|
||||
- **Commit**: fe1831a
|
||||
- **Date**: 2026-09-22
|
||||
- **Commit**: daf0fed
|
||||
- **Node**: v22.22.2
|
||||
- **OS**: darwin
|
||||
- **CPU**: Apple M4 Max (16 cores)
|
||||
- **RAM**: 69 GB
|
||||
- **OS**: linux
|
||||
- **CPU**: AMD Ryzen 7 3700X 8-Core Processor (16 cores)
|
||||
- **RAM**: 67 GB
|
||||
- **Core-pinned**: no
|
||||
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
|
||||
- **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
|
||||
|
||||
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
|
||||
> loopback on the same machine, sharing the same cores as the server processes they measured. That
|
||||
@@ -29,64 +29,74 @@
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
|
||||
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
|
||||
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
|
||||
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
|
||||
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
|
||||
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
|
||||
| raw-http | 41,631 | 2.00 | 3.00 | 4.00 | 0.6% | 41,343–41,974 |
|
||||
| nestjs-fastify | 32,419 | 3.00 | 4.00 | 6.00 | 0.5% | 32,103–32,583 |
|
||||
| fastify | 32,170 | 3.00 | 3.00 | 5.00 | 1.3% | 31,236–32,356 |
|
||||
| green-tea | 29,777 | 3.00 | 6.00 | 7.00 | 0.4% | 29,557–29,873 |
|
||||
| express | 10,546 | 8.00 | 13.00 | 18.00 | 0.4% | 10,480–10,625 |
|
||||
| nestjs-express | 9,680 | 9.00 | 15.00 | 21.00 | 0.6% | 9,567–9,739 |
|
||||
|
||||
### Route param
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
|
||||
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
|
||||
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
|
||||
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
|
||||
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
|
||||
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
|
||||
| raw-http | 41,756 | 2.00 | 3.00 | 4.00 | 1.1% | 40,953–42,017 |
|
||||
| fastify | 31,708 | 3.00 | 4.00 | 5.00 | 0.5% | 31,359–31,847 |
|
||||
| nestjs-fastify | 29,880 | 3.00 | 4.00 | 6.00 | 0.3% | 29,745–29,961 |
|
||||
| green-tea | 28,706 | 3.00 | 6.00 | 7.00 | 0.6% | 28,562–29,051 |
|
||||
| express | 10,376 | 9.00 | 12.00 | 17.00 | 0.4% | 10,364–10,453 |
|
||||
| nestjs-express | 9,257 | 10.00 | 15.00 | 21.00 | 0.2% | 9,244–9,285 |
|
||||
|
||||
### Pipeline (3 steps) (approximation)
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
|
||||
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
|
||||
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
|
||||
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
|
||||
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
|
||||
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
|
||||
| raw-http | 39,897 | 2.00 | 3.00 | 5.00 | 0.6% | 39,847–40,441 |
|
||||
| fastify | 31,436 | 3.00 | 4.00 | 6.00 | 0.6% | 31,079–31,563 |
|
||||
| nestjs-fastify | 29,403 | 3.00 | 4.00 | 6.00 | 0.6% | 29,151–29,689 |
|
||||
| green-tea | 26,839 | 3.00 | 6.00 | 8.00 | 0.1% | 26,783–26,872 |
|
||||
| express | 10,365 | 9.00 | 12.00 | 18.00 | 1.3% | 10,171–10,542 |
|
||||
| nestjs-express | 9,256 | 10.00 | 15.00 | 22.00 | 0.5% | 9,187–9,302 |
|
||||
|
||||
### POST JSON + validation
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
|
||||
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
|
||||
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
|
||||
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
|
||||
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
|
||||
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
|
||||
| raw-http | 31,783 | 3.00 | 5.00 | 6.00 | 0.4% | 31,517–31,825 |
|
||||
| green-tea | 22,005 | 4.00 | 7.00 | 9.00 | 0.7% | 21,736–22,187 |
|
||||
| fastify | 20,430 | 4.00 | 8.00 | 9.00 | 0.4% | 20,398–20,601 |
|
||||
| nestjs-fastify | 18,597 | 4.00 | 8.00 | 11.00 | 0.2% | 18,540–18,658 |
|
||||
| express | 8,440 | 11.00 | 16.00 | 24.00 | 0.3% | 8,408–8,492 |
|
||||
| nestjs-express | 7,666 | 12.00 | 18.00 | 26.00 | 0.3% | 7,645–7,703 |
|
||||
|
||||
## Step-scaling (green-tea)
|
||||
|
||||
| Path | Steps | req/s |
|
||||
| --- | --- | --- |
|
||||
| /steps/0 | 0 | 92,282 |
|
||||
| /steps/3 | 3 | 81,530 |
|
||||
| /steps/5 | 5 | 71,994 |
|
||||
| /steps/0 | 0 | 29,196 |
|
||||
| /steps/3 | 3 | 26,564 |
|
||||
| /steps/5 | 5 | 25,314 |
|
||||
|
||||
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
|
||||
Each additional pipeline step costs roughly 776 req/s (-13.3% over 5 steps), on this box.
|
||||
|
||||
## green-tea across runtimes
|
||||
|
||||
| Scenario | node | deno | bun |
|
||||
| --- | --- | --- | --- |
|
||||
| JSON hello (overhead) | 30,379 | 51,888 | 46,300 |
|
||||
| Route param | 29,204 | 51,786 | 42,788 |
|
||||
| Pipeline (3 steps) | 27,208 | 50,692 | 39,644 |
|
||||
| POST JSON + validation | 22,609 | 35,743 | 31,960 |
|
||||
|
||||
Same application, same built bundle, same box — only the runtime differs. Read across a row, never against the cross-framework tables above: those measure other frameworks on Node, and nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.
|
||||
## Cost of secure-by-default (green-tea)
|
||||
|
||||
| Label | req/s |
|
||||
| --- | --- |
|
||||
| security:false (parity) | 98,093 |
|
||||
| security:true (default) | 92,998 |
|
||||
| security:false (parity) | 29,777 |
|
||||
| security:true (default) | 28,919 |
|
||||
|
||||
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
|
||||
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~2.9% req/s on this box.
|
||||
|
||||
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
|
||||
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
|
||||
@@ -116,3 +126,170 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
|
||||
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
|
||||
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
|
||||
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
|
||||
|
||||
<!-- keep-below: hand-written, survives `npm run bench` -->
|
||||
|
||||
## What moved between releases
|
||||
|
||||
These figures were measured per function and never per version. Every change on the request path
|
||||
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
|
||||
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
|
||||
`npm run bench:compare` exist to close.
|
||||
|
||||
### The release gate: `26.9.0-beta.1` → `26.9.0-beta.2`
|
||||
|
||||
Ten cases, both trees on one box in one sitting, alternating which side ran first each round, sharing
|
||||
one `node_modules` — the two revisions differ by a version string and nothing else in `package.json`,
|
||||
so the only thing that moved between the sides is green-tea. Medians of three rounds:
|
||||
|
||||
| Scenario | 26.9.0-beta.1 | 26.9.0-beta.2 | Δ | |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| hello | 90,615 | 89,853 | −0.8% | overlaps |
|
||||
| param | 86,956 | 87,572 | +0.7% | overlaps |
|
||||
| pipeline (3 steps) | 80,061 | 81,504 | +1.8% | overlaps |
|
||||
| steps5 | 75,436 | 75,238 | −0.3% | overlaps |
|
||||
| validate (POST) | 70,240 | 73,568 | +4.7% | overlaps |
|
||||
| hello + security | 83,738 | 84,890 | +1.4% | overlaps |
|
||||
| hello + cors predicate | 82,237 | 82,528 | +0.4% | overlaps |
|
||||
| preflight + cors predicate | 111,223 | 114,220 | +2.7% | overlaps |
|
||||
| param, 50 routes | 83,505 | 87,078 | +4.3% | **flagged** |
|
||||
| param, 200 routes | 73,289 | 73,335 | +0.1% | overlaps |
|
||||
|
||||
Nine rows overlap and therefore say nothing, which is the result this gate exists to produce. The
|
||||
release is a breaking one — `Plugin` became `{ name, mount }`, `serveDeno()` and `serveBun()` became
|
||||
async, `@Provider({ export: true })` stopped being a thing a teapot can do, and an `HttpError` is now
|
||||
recognised by a brand rather than by `instanceof` — but all of that is boot-time or error-path work.
|
||||
None of it sits on the per-request path these cases walk, and the table agrees.
|
||||
|
||||
The tenth row is why "flagged" is not a synonym for "found something". `param, 50 routes` came out
|
||||
+4.3% with separated ranges, in green-tea's favour, and it did not survive being asked twice: re-run
|
||||
alone at seven rounds it is **+0.5% and overlapping**, with both sides swinging between 80,794 and
|
||||
88,259 req/s. The reason to doubt it before re-running was that it had no mechanism — the matcher
|
||||
work that could produce it would have to show at 200 routes too, and that row had already said
|
||||
+0.1%. Treat a flagged row as an instruction to measure again, whichever direction it points; a win
|
||||
nobody can explain is a measurement problem more often than it is a win.
|
||||
|
||||
The cross-framework tables above moved to a quiet box for this release, which is why their absolute
|
||||
numbers are roughly a third of the previous run's: an idle 2019 desktop Ryzen against a laptop M4
|
||||
Max. Two attempts on that laptop were discarded first, and the reason is worth recording. Each
|
||||
framework's delta against its own previous number tracked its position in the run order rather than
|
||||
anything in its code — the one measured second lost 7%, the ones measured last gained — while a
|
||||
browser and the window server held around 60% of the machine throughout. That run would have read
|
||||
as green-tea overtaking Fastify, which is the most flattering available reading of a broken
|
||||
measurement and exactly the kind this file exists to refuse. The gate table above survives the same
|
||||
contention, because both sides pay it and the order alternates; an absolute cross-framework number
|
||||
does not.
|
||||
|
||||
What survived the move is the shape, and that is the part worth trusting. On both machines green-tea
|
||||
is behind Fastify on `hello`, `param` and `pipeline` and ahead of it on `validate`, and roughly
|
||||
2.8× ahead of Express throughout. The *size* of the gap did not survive: against Fastify it is
|
||||
2-8% on the M4 and 7-15% here. A percentage quoted without the hardware it was measured on is not a
|
||||
fact about the framework.
|
||||
|
||||
### The release gate: `26.8.0-beta.1` → `26.9.0-beta.1`
|
||||
|
||||
Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
|
||||
one `node_modules` and one byte-identical server file. Medians of five rounds:
|
||||
|
||||
| Scenario | 26.8.0-beta.1 | 26.9.0-beta.1 | Δ |
|
||||
| --- | --- | --- | --- |
|
||||
| hello | 91,343 | 90,371 | −1.1% |
|
||||
| param | 88,113 | 87,921 | −0.2% |
|
||||
| pipeline (3 steps) | 80,934 | 80,893 | −0.1% |
|
||||
| validate (POST) | 72,340 | 72,241 | −0.1% |
|
||||
| hello + security | 85,967 | 86,426 | +0.5% |
|
||||
| hello + cors predicate | 82,609 | 83,401 | +1.0% |
|
||||
| preflight + cors predicate | 112,055 | 115,069 | **+2.7%** |
|
||||
|
||||
Every row but the last overlaps between the two sides and is noise. The preflight row does not: the
|
||||
new tree wins all three rounds, which is where a `cors.origins` predicate stopped being evaluated
|
||||
three times per request.
|
||||
|
||||
That change is a call count, not a rate, and the benchmark's predicate is a `Set` lookup — so the
|
||||
saving is invisible in req/s here and would be two or three network round trips in the lookup the
|
||||
option exists for:
|
||||
|
||||
| | per cross-origin GET | per preflight |
|
||||
| --- | --- | --- |
|
||||
| 26.8.0-beta.1 | 2 | 3 |
|
||||
| 26.9.0-beta.1 | **1** | **1** |
|
||||
|
||||
### Against `26.7`, and why it is not a regression
|
||||
|
||||
The table this file carried until today was measured at `fe1831a`, before `26.8.0-beta.1`
|
||||
shipped. Re-running
|
||||
that tree today, under the same toolchain and dependencies, gives 94,403 req/s on `hello` and
|
||||
93,361 on `param` against 89,527 and 85,839 for the current tree — roughly −5% and −8%. Against
|
||||
`fastify` as a control, which moved +1.2% to +1.8% across the same scenarios, green-tea's ratio to
|
||||
it fell 6.6% to 11.7%.
|
||||
|
||||
**That number is real and it is not a regression, because it is not the same program.** July matched
|
||||
routes by splitting the path and comparing segments, returning on the first hit, in one flat file.
|
||||
It had no route constraints, no specificity ranking, no per-request correlation, no lifecycle
|
||||
stream, and one adapter. It was fast the way something is fast before it does anything.
|
||||
|
||||
What the interval bought, in the order it costs: a runtime-neutral request and response boundary,
|
||||
which is what serves Deno, Bun and workerd from one core rather than one adapter; constraint and
|
||||
specificity matching; a correlated event stream; and per-request identity.
|
||||
|
||||
The first of those is now measurable, because the runtimes table above did not exist either. The
|
||||
same boundary that costs on Node is what puts the same application on Deno at 153,408 req/s and Bun
|
||||
at 131,674 against Node's 90,976 — and above the 119,357 that Node's own `http` module manages with
|
||||
no framework at all. Whether the trade is worth it is the reader's call. This file's job is to say
|
||||
what it cost and what it bought.
|
||||
|
||||
### Figures recorded when each change landed
|
||||
|
||||
Measured at the time, in the code, against a microbenchmark rather than this harness:
|
||||
|
||||
| Where | Finding |
|
||||
| --- | --- |
|
||||
| `src/http/core.ts:63` | a per-request derivation that reached **45% of a whole request** before it was fixed |
|
||||
| `src/http/core.ts:89` | six request-id generators compared; `crypto.randomUUID` at 76 ns was the fastest cross-runtime option, and the only alternatives that beat it are Node-only |
|
||||
| `src/http/core.ts:229` | wrapping `dispatch` in a second async frame: 0.43 µs per request |
|
||||
| `src/bus.ts:173` | spreading request identity into an event payload: ~197 ns on a two-step pipeline |
|
||||
| `src/pipeline.ts:58` | one timestamp per step boundary instead of two: 25.2 ns against 45.3 ns per step |
|
||||
| `src/http/headers.ts:30` | 146.4 ns against 55.9 ns for the same header answer |
|
||||
| `src/http/body.ts:39` | 250 ns per request for a closure and the error context it captured |
|
||||
| `src/http/router.ts:232` | per-segment decoding on a path nobody decodes: 95.8 ns for `/hello`, 342.7 ns for six segments |
|
||||
|
||||
**These do not add up to the release delta, and cannot.** They cite different baselines — 4.4 µs,
|
||||
4.5 µs, 10.19 µs — because each was taken against whatever a request cost on the day. A dozen
|
||||
findings in nanoseconds against inconsistent references is a discussion, not a total. A version-level
|
||||
number measured against a fixed baseline is what was missing, not rigour.
|
||||
|
||||
### What is still unattributed
|
||||
|
||||
Three candidates for the `26.7` → `26.9` interval were measured and none of them account for it:
|
||||
|
||||
- **`crypto.randomUUID` per request** — removing it entirely lands within noise on every scenario,
|
||||
and one row moves the wrong way. At 76 ns against a ~11 µs request it is ~0.7%, below what a load
|
||||
test at this CV can resolve.
|
||||
- **Specificity ranking in the matcher** — replacing it with July's first-match-wins is noise on all
|
||||
four rows at this route-table size.
|
||||
- **The bundle versus the TypeScript source** — every row overlaps, so the form the table loads does
|
||||
not explain it either.
|
||||
|
||||
No single culprit was found. The remaining candidates are the neutral request and response objects
|
||||
and the several small per-request allocations around them, which is a shape that resists a single
|
||||
measurement.
|
||||
|
||||
## What this file does not measure
|
||||
|
||||
- **Route-table width was invisible until `26.9`.** Every matcher cost scales with how many
|
||||
candidates a request walks past, and the cross-framework tables use six routes — so any matcher
|
||||
change measures as noise there regardless of its size. `npm run bench:compare` carries 50- and
|
||||
200-route cases for this reason. Settling route ranking when the table is built rather than per
|
||||
request is worth nothing at six routes, +3.4% at fifty, and **+12% to +14.9% at two hundred**,
|
||||
across twelve rounds without a crossing sample.
|
||||
- **Boot time is absent.** Independent providers began booting concurrently in `26.9`: three
|
||||
providers with no edges and 200 ms of work each went from 616 ms to 210 ms. No table here shows it.
|
||||
- **Streaming is absent.** Every scenario is a buffered response. SSE framing, the encoder's
|
||||
per-item work, and the stream lifecycle events are not exercised.
|
||||
- **The cross-framework tables are Node-only**, and they load green-tea from `src/` through `tsx`
|
||||
while the other frameworks load their published JavaScript. Measured today, that difference is
|
||||
within noise — but it is a difference, and the runtimes table above avoids it by loading the built
|
||||
bundle on all three.
|
||||
- **The runtimes table compares each runtime's HTTP server, not its JavaScript engine.** `Deno.serve`
|
||||
and `Bun.serve` are native stacks; Node's `http` is JavaScript. "green-tea on this runtime" is the
|
||||
claim, and it is the one an application actually experiences.
|
||||
+496
-5
@@ -6,11 +6,497 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||
npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
## [26.9.0-beta.2] - 2026-09-22
|
||||
|
||||
### Breaking
|
||||
|
||||
- **`serveDeno()` and `serveBun()` are async**, returning `Promise<DenoServer>` and
|
||||
`Promise<BunServeResult>`. They now boot the app before they bind, which is what `listen()` has
|
||||
always done.
|
||||
|
||||
They did not, and the documented fix was to remember to `await app.boot()` first. That made the
|
||||
correct use of a core helper depend on reading a README, in a framework whose argument is that
|
||||
order should not be something you have to get right. Forget it and a missing signing key is not a
|
||||
failed deploy: the boot memo keeps the rejection, so the port binds, every request gets a 500 from
|
||||
the runtime, and none of them reach `onError`. The server looks healthy to anything that only
|
||||
checks whether it is listening.
|
||||
|
||||
Migration is one keyword, and the value is unchanged:
|
||||
|
||||
```diff
|
||||
- const server = serveDeno(app, { port });
|
||||
+ const server = await serveDeno(app, { port });
|
||||
```
|
||||
|
||||
Both runtimes support top-level `await`, so a module that serves at import time needs nothing
|
||||
else. `edgeHandler` is deliberately untouched: on workerd there is no startup outside a request,
|
||||
so there is no earlier moment to move the failure to.
|
||||
|
||||
- **A plugin is a named object.** `Plugin` is now `{ name, mount(api) }`; it was `(api) => void`.
|
||||
The name that `plugin:mounted` reports came from `fn.name`, which is `""` for an arrow returned
|
||||
straight from a factory, `"plugin"` for a `const`, and whatever a minifier leaves behind — so the
|
||||
event that exists to report which plugins mounted reported none of them by name. The name is now
|
||||
the author's word, a failed `mount` is reported as `plugin "<name>" failed to mount: …` with the
|
||||
original error as its `cause`, and two plugins sharing a name fail `createApp`.
|
||||
|
||||
Migration is mechanical:
|
||||
|
||||
```diff
|
||||
- const jwt = (options) => ({ scope }) => { scope.add(node); };
|
||||
+ const jwt = (options) => ({
|
||||
+ name: options.provides ?? 'jwt',
|
||||
+ mount({ scope }) { scope.add(node); },
|
||||
+ });
|
||||
```
|
||||
|
||||
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
|
||||
the boot, with an error naming the provider and the replacement. A provider is a factory whose
|
||||
value *is* the object it builds — a pool, a client, a `db` — and an object is not what a JSON wire
|
||||
carries. What did cross was whatever half of it survived serialization, and it arrived as an
|
||||
app-scope binding: the teacup resolved it once at boot and then served that value for the life of
|
||||
the process, out of a cache the teapot no longer stood behind. Restarting the teapot, or changing
|
||||
what it built, changed nothing on the teacup until the teacup itself restarted.
|
||||
|
||||
Export a `@Step` instead. It runs on the teapot, per request, and only its result comes back —
|
||||
which is why the two entries below follow from this one: a remote export now holds nothing between
|
||||
requests. `invalidateRemoteBindings`, the `rebind` array and the `onReconnect` callback that drove
|
||||
them are gone with it. All three existed to throw away a cached app-scope value when a link came
|
||||
back; there is no longer a cached value, so a reconnected link is simply usable again on the next
|
||||
RPC. Internal, so nothing importable changed.
|
||||
|
||||
**A teapot that boots today can stop booting**, and the replacement is mechanical: the exported
|
||||
`@Provider` becomes a `@Step` that returns what the provider's value carried.
|
||||
|
||||
- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now
|
||||
`{ steps: string[], routes }`. Every export is request-scope after the change above, so the
|
||||
lifetime field had one possible value left and told a reader nothing. A manifest step that is not
|
||||
a string is now rejected on arrival, rather than trusted because a peer sent it.
|
||||
|
||||
`MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both
|
||||
peers ship from this repository, and there is no deployed pair of versions for a bump to protect —
|
||||
it would spend the number on nobody. A stable wire would not get that option; alpha is exactly
|
||||
what the word buys, and this is the last comfortable moment to use it.
|
||||
|
||||
### Added
|
||||
|
||||
- **`app.boot()`** runs the provider factories now instead of on the first request. `listen()`,
|
||||
`serveDeno()` and `serveBun()` all call it for you (see Breaking, below). Call it by hand when you
|
||||
drive `app.fetch` / `app.upgrade` from your own server: those boot lazily, and the boot memo keeps
|
||||
a rejection, so a bad key answers 500 on *every* request, from the runtime, without reaching
|
||||
`onError`. On workerd there is no startup outside a request, so calling it moves nothing.
|
||||
- **Errors are recognised by brand.** `HttpError` and `ValidationError` now carry
|
||||
`Symbol.for('green-tea.http-error')` and `Symbol.for('green-tea.validation-error')`, and
|
||||
`isHttpError` checks the brand instead of `instanceof`. An error thrown by code holding a
|
||||
different copy of core — a plugin package, an app that installed from npm and JSR both — now
|
||||
renders with its own status instead of a 500. The exported `HttpErrorLike` type and the
|
||||
`isValidationError` guard come with it. The string is the public protocol: code that imports only
|
||||
types writes `Symbol.for('green-tea.http-error')` itself.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** Blocking was never
|
||||
caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later
|
||||
to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the
|
||||
container is thirty seconds behind" and "the teapot does not exist" look identical for the first
|
||||
thirty seconds; exhausting it now warns and starts without that teapot.
|
||||
|
||||
What that buys is narrower than it sounds, and worth stating exactly. A teapot that never
|
||||
connected sent no manifest, so the teacup learned nothing about it — no step runners, no routes,
|
||||
a graph identical to the one it would have had if that teapot were never configured. Its routes
|
||||
therefore **404**, through the ordinary unmatched-route path, because nothing was ever registered
|
||||
to match. And any local step or handler that needs one of its tokens **still fails the boot**,
|
||||
naming the teapot that did not connect. `503` is what a teapot that connected and *later* died
|
||||
answers: that link exists, its steps and routes are registered, and the dead link is what returns
|
||||
the status. Never reachable and reachable-then-gone are different situations, and they read
|
||||
differently on purpose.
|
||||
|
||||
So the change is for the teacup that does *not* depend on that teapot: it starts, rather than
|
||||
refusing over a dependency it never had. It is not graceful degradation of the dependency, and
|
||||
cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have
|
||||
exported, and only a declaration can say. That declaration is the `expects` list in
|
||||
`docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are
|
||||
unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot
|
||||
without spending the grace, because it is the teapot's decision rather than the network's and will
|
||||
be the same decision in thirty seconds; and the missing-token error, which now says "local or
|
||||
connected mesh" rather than "local or mesh", the old wording having claimed a search that never
|
||||
happened.
|
||||
|
||||
## [26.9.0-beta.1] - 2026-09-04
|
||||
|
||||
### Added
|
||||
|
||||
- **A request budget, not just a connection cap.** `createApp({ limits: { maxConcurrentRequests } })`
|
||||
bounds how many handlers run at once, per server and per Fetch adapter instance; over the budget a
|
||||
request gets `503` with `Retry-After: 1` instead of queueing behind the ones already running. It is
|
||||
opt-in and unlimited by default, and it counts *executing handlers* rather than open connections —
|
||||
the slot is released when routing and the handler finish, so a long-lived SSE stream or a WebSocket
|
||||
upgrade does not hold one for its lifetime. On Node a client disconnect releases the slot early. A
|
||||
handler that never returns keeps its slot, which is the honest behaviour for a budget of this shape.
|
||||
Contributed by @hgshreyas.
|
||||
|
||||
Node's connection cap also stopped being silent: reaching `maxConnections` now logs a warning
|
||||
naming the dropped peer, rate-limited to one a minute. Until now the socket was destroyed with no
|
||||
HTTP response and nothing said so, which reads from the outside like a network fault.
|
||||
|
||||
- **`createApp({ handleSignals: true })` registers `SIGINT`/`SIGTERM` to close and exit.** Off by
|
||||
default, and that is the design rather than caution: a library that installs process-wide handlers
|
||||
behind your back is worse than one that installs none, because when the process exits is the
|
||||
application's call. Both halves are supported — keep the handler, or hand it over. What is not
|
||||
optional either way is that *something* calls `close()`; the teardown registry only runs from
|
||||
there, so a container `SIGKILL`ed after its grace period skips every `dispose()` and reports
|
||||
nothing.
|
||||
|
||||
Declared once and wired per runtime by whichever boot call runs — `listen()`, `serveDeno()` and
|
||||
`serveBun()` each attach it to the closer that drains *their* server, so `process.on` on Node and
|
||||
Bun and `Deno.addSignalListener` on Deno stop being the application's problem. `close()`
|
||||
unregisters, which means a *second* signal falls through to the platform default and ends the
|
||||
process at once: Ctrl-C twice is the way out of a teardown that is stuck.
|
||||
|
||||
- **The extension-point types are exported, not just the extension points.** `TransformerFn` — the
|
||||
type of `@Transformer`'s only argument — could not be imported, so a custom transformer was
|
||||
attached with its shape redeclared inline or borrowed off a value as `typeof JsonTransformer`.
|
||||
Checking the barrel for the same oversight turned up four more, all now exported: `PluginApi`,
|
||||
`ScopeApi` and `ScopeNode`, the chain reached through `api.scope.add`, without which a plugin split
|
||||
into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only —
|
||||
nothing at runtime moved and no existing export changed.
|
||||
|
||||
- **The lifecycle stream has a contract now, not just events.** `request:end` is documented as
|
||||
terminal and universal — it fires for every request shape and is the only one carrying the status
|
||||
the client received, which makes it the request counter. `request:failed` means *handler code
|
||||
threw*, which no status expresses on its own since a rendered `422` is also a throw, and
|
||||
`route:unmatched` means *no route ran*. Both are **additional** to `request:end`, not alternatives
|
||||
to it: one failing request emits three events and a 404 emits two, all sharing a `requestId`, and
|
||||
an exporter that treats them as separate outcomes counts the same request twice. Silently — the
|
||||
metrics just come out wrong.
|
||||
|
||||
`request:failed` now carries `status`, so an error counter can break down by status without
|
||||
joining back through `requestId` for something the emitter already had. It is absent in exactly
|
||||
one case: a custom `onError` that threw while producing it, where the framework does not know what
|
||||
was sent and will not guess.
|
||||
|
||||
- **`@needs('events')` reaches the read-only half of the bus** — `{ on }`, the same narrowing
|
||||
plugins already get, exported as the `Events` type. `app.bus` was public and a plugin could
|
||||
subscribe, but the bus was not a graph token, so `@needs('bus')` failed at boot and nothing said
|
||||
why. It still is not one, and that is the design: handing `emit` to every node turns a one-way
|
||||
observation channel into something anything can forge events on. `@needs('bus')` now fails saying
|
||||
exactly that, and pointing at the two things that do work.
|
||||
|
||||
A plugin remains the right home for observation, because it gets `on` and `onShutdown` *together*.
|
||||
This token gives the subscribe half alone — `on()` returns its own unsubscribe for a `@Provider`
|
||||
to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request
|
||||
and would add a listener each time.
|
||||
|
||||
- **`@Sse` can emit an `id:`, so an `EventSource` reconnect has something to resume from.**
|
||||
`sse(data, { id, event, retry })` tags a stream item and the encoder writes the fields ahead of
|
||||
`data:`; an app that never calls it produces byte-identical output. Until now the encoder wrote one
|
||||
field, so the browser had nothing to put in `Last-Event-ID` and every automatic reconnect — the
|
||||
reason to choose SSE over a raw WebSocket — rebuilt the route's iterable from its start and lost
|
||||
the gap in silence. The other half already worked: the request envelope has always carried every
|
||||
header, so a handler could already read `@header('last-event-id')`; it simply always arrived empty.
|
||||
`event:` and `retry:` come along because the same envelope carries them, and neither was reachable
|
||||
before.
|
||||
|
||||
**green-tea stores nothing** — no buffer, no retention window, no replay. It carries the marker in
|
||||
both directions and the handler decides what the gap means, because only the source knows: a paged
|
||||
log re-reads from an offset, a live sensor has no past worth delivering. An `id` containing a
|
||||
newline is rejected rather than stripped, since the SSE format is line-based and an id is exactly
|
||||
the value most likely to be built from a request — a cursor, a page token — so one newline would
|
||||
let a caller append fields to somebody else's stream. On an `ndjson` or `negotiate`-to-ndjson route
|
||||
the payload is unwrapped and the fields dropped. New exports: `sse`, `isSseEvent`, `SseEvent`,
|
||||
`SseFields`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A request's security and CORS headers are computed once.** They were derived twice per request
|
||||
and three times for a preflight — once in the adapter, to seed the headers a response written
|
||||
before routing still has to carry, and again during dispatch. Nothing was incorrect, but
|
||||
`cors.origins` is a predicate precisely so it can be a lookup: an allowlist in Redis, a tenant
|
||||
query. Running it two or three times charged the caller's latency budget and their backend for an
|
||||
answer whose inputs had not changed in between, and made a predicate with a counter in it count
|
||||
double.
|
||||
|
||||
- **Every `request:end` is now preceded by a `request:start` carrying the same `requestId`.** The
|
||||
pairing held by accident until `maxConcurrentRequests` arrived: `request:start` had a single
|
||||
emitter, so nothing could break it, and a shed request emitted only the `request:end`. A consumer
|
||||
that opens per-request state on the first and closes it on the second — an in-flight gauge, most
|
||||
obviously — would have drifted under shedding, which is when an operator is reading it, and would
|
||||
have done so by producing a plausible wrong number rather than an error. It is a guarantee now,
|
||||
written next to `LifecycleEvent` and enforced by a test that enumerates every response shape.
|
||||
|
||||
- **An unmatched request carries a bounded `route`.** `route:unmatched` was the one terminal request
|
||||
event with no `route`, so the only subject a consumer could reach was `name` — which on that event
|
||||
is the concrete, caller-controlled path. A matched path is bounded by the route table; an
|
||||
unmatched one is bounded by nothing, and a scanner walking `/aaa`, `/aab`, `/aac` is a memory leak
|
||||
with a metrics backend attached. It and the `request:end` that follows now carry
|
||||
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE`. Written down alongside it: `name` is
|
||||
caller-controlled and must never be a metric label.
|
||||
|
||||
- **Framework token names are reserved.** `logger`, `rooms`, `events` and `bus` cannot be declared
|
||||
by a module, plugin or mesh export; taking one is a boot error naming it. Built-ins used to be
|
||||
registered only if the name was free, so a provider called `logger` silently replaced the
|
||||
framework's own and every `@needs('logger')` in the app got something that was not the logger core
|
||||
writes to — a divergence discovered from a log line that never appeared. `bus` is reserved without
|
||||
being provided, so `@needs('bus')` cannot resolve to whatever a user happened to call `bus`.
|
||||
|
||||
**This can fail an app that boots today**, which is the point of it, and the fix is to rename.
|
||||
|
||||
- **No per-request bookkeeping when no request budget is set.** Every request registered a `close`
|
||||
listener and set a flag for `maxConcurrentRequests`, which is opt-in and unlimited by default — so
|
||||
most applications paid a closure and an `EventEmitter` registration per request, on the hot path,
|
||||
for a feature that was off. Unchanged where a budget *is* configured: the listener is what
|
||||
releases a slot when a client disconnects mid-handler.
|
||||
|
||||
- **Route ranking is settled when the route table is built, not on every request.** Matching scanned
|
||||
every route registered under the request's method and ranked the candidates as it went, deriving
|
||||
each pattern's specificity from its source string per comparison. Both the scan and the ranking
|
||||
scale with the size of the route table, and neither can produce a different answer between two
|
||||
requests — the table is assembled once, after the graph is prepared, and handed to the adapter
|
||||
unchanged. Routes are now compiled, bucketed by method and ordered most-specific-first once, and
|
||||
matching returns at the first route that matches.
|
||||
|
||||
Nothing about which route answers changes. Equal specificity still keeps registration order, which
|
||||
the ordering carries through a stable sort rather than through a scan that declined to replace its
|
||||
best on a tie. Two smaller savings ride along on the same path: a path segment holding no `%` skips
|
||||
`decodeURIComponent` entirely, and decoding is memoized per request rather than repeated for every
|
||||
candidate route that reaches the same parameter position.
|
||||
|
||||
Worth nothing on a small route table and worth a great deal on a large one, which is the shape of
|
||||
the saving rather than a caveat on it: **no measurable change at 6 routes, +3.4% at 50, and +12% to
|
||||
+14.9% at 200**. That is also why it went unnoticed for two releases — the benchmark had no
|
||||
route-table-width dimension until this one, so every matcher change measured as noise regardless of
|
||||
its size.
|
||||
|
||||
- **Independent providers boot concurrently.** Boot walked the topological order one node at a time,
|
||||
so an application paid the *sum* of its providers' latencies rather than its longest chain — three
|
||||
providers with no edges between them and 200ms of work each took 616ms for a graph whose critical
|
||||
path is 200ms; it now takes 210ms. The graph already proved which nodes cannot constrain each
|
||||
other, and flattening the sort was the only thing throwing that away: the ordered list is grouped
|
||||
back into dependency levels and each level runs together, with level *N* fully registered and
|
||||
warmed before *N+1* starts. Nothing the graph derives changes, and this is the second thing users
|
||||
get for declaring `needs`/`provides` rather than ordering calls by hand — pruning was the first,
|
||||
and neither is available to a middleware chain, where nothing declares what is independent.
|
||||
|
||||
Two consequences worth knowing. Teardown still runs in the exact reverse of boot: registration
|
||||
follows level order rather than completion order, which is what keeps that a guarantee instead of
|
||||
a race. And a required provider that fails no longer prevents its independent siblings from
|
||||
starting — they are already in flight — so whatever they opened is registered for teardown before
|
||||
the boot is aborted. On the bus, `boot:provider:start` no longer strictly alternates with `:ok`; a
|
||||
level emits its starts together and then its results.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on
|
||||
the request path, above the region where errors convert to a response, so a throw became a rejected
|
||||
promise nobody awaited — and Node's default for that is to exit. One cross-origin request was
|
||||
enough, `onError` never saw it, and the trigger is a browser: the predicate is only reached when an
|
||||
`Origin` header is present, so no test that forgets the header can catch it. A predicate that throws
|
||||
now **denies** the origin and the failure is logged. A lookup that failed has not said yes, and a
|
||||
broken allowlist must never widen into an open one.
|
||||
|
||||
- **The JSR package works.** JSR serves `src/` rather than the tsup build, and the ESM build's
|
||||
`createRequire` banner therefore never existed there — so every lazy `require()` in the source had
|
||||
nothing to resolve. `@Html('file')` and template mode died at boot on Deno with `ReferenceError:
|
||||
require is not defined`. Two other sites were worse than the crash because they answered
|
||||
confidently and wrongly: `static` reported *"needs a filesystem and is unavailable on this runtime
|
||||
(edge)"* while running on Deno, which has one, and multipart reported `busboy` as not installed
|
||||
while it sat in `node_modules`. Both blamed the runtime for a packaging problem, and both named a
|
||||
runtime the reader was not on.
|
||||
|
||||
Every call site now resolves through one helper that prefers the ambient `require` — so both npm
|
||||
builds behave exactly as before — and otherwise rebuilds one from
|
||||
`process.getBuiltinModule('node:module')`, which Node, Deno and Bun all expose synchronously. On
|
||||
workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem"
|
||||
story is finally the true one.
|
||||
|
||||
- **A custom `onError` that throws no longer takes the process down.** `createApp({ onError })` is
|
||||
the advertised way to render errors, it runs on the request path, and it ran with no boundary — a
|
||||
renderer that threw exited the process, exit code 1. It is the same shape as the CORS predicate
|
||||
crash above and easier to reach: not a cross-origin request, but *any* request that produces an
|
||||
error. The renderer produces the 404 too, so an app with a custom renderer and no matching route
|
||||
was one request away from exiting.
|
||||
|
||||
It was also the worst-timed crash there was, since the renderer only runs once something has
|
||||
already gone wrong: an error occurs, the code written to report it fails, and instead of a
|
||||
degraded report the server ends. A renderer that throws now falls back to the built-in rendering —
|
||||
which is exactly what the option overrides — so the original error still gets its response, and
|
||||
the renderer's own failure is logged separately, naming both.
|
||||
|
||||
- **A stream's lifecycle is reported on every runtime, and joins back to its request.** `stream:open`,
|
||||
`stream:close` and `stream:error` were emitted only by the Node adapter. Every Fetch runtime — Deno,
|
||||
Bun, workerd, and `app.fetch()` on Node — emitted none of them and broke the response with a
|
||||
transport error instead of writing the encoder's error frame. Both halves were silent: a consumer
|
||||
counting `stream:error` saw zero on three of the four runtimes while streams were failing normally,
|
||||
and the client got a truncated body indistinguishable from a clean end of stream. The Fetch path now
|
||||
emits all three and frames the error before closing cleanly, which is what the Node adapter always
|
||||
did and the better answer for the client — an SSE consumer that received an `error` event knows what
|
||||
happened, where a dropped connection tells it nothing.
|
||||
|
||||
All three events now also carry the opening request's `requestId` and `traceId`, plus a bounded
|
||||
`route`. `src/http/core.ts` had documented them as carrying the id since the stream landed; they
|
||||
never did. The split they exist for is deliberate — a route returning an `AsyncIterable` is done in
|
||||
milliseconds while its connection may live for hours, so `request:end` fires at the handler's return
|
||||
and hour-long connections stay out of the same latency distribution as 2ms replies — but it only
|
||||
works if the two can be *joined*, and without the id an exporter could not say which request opened
|
||||
the connection still holding a slot. A WebSocket upgrade correlates itself: it is an HTTP request
|
||||
with headers like any other, so it adopts a gateway's `x-request-id` rather than opening a second
|
||||
identity, and carries `transport: 'ws'`.
|
||||
|
||||
## [26.8.0-beta.1] - 2026-08-19
|
||||
|
||||
### 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 +516,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 +539,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 +575,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 +600,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 +620,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 +642,8 @@ change before the stable release.
|
||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||
|
||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
|
||||
[26.9.0-beta.2]: https://github.com/Expressive-Tea/green-tea/compare/v26.9.0-beta.1...v26.9.0-beta.2
|
||||
[26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1
|
||||
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||
@@ -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`, release tags, and `develop` — the last one under the name `contrib`. Which branch you target depends on where you are.
|
||||
|
||||
**From GitHub, if you are an outside contributor:** open your pull request against **`contrib`**. Not `main`. `main` on GitHub is a mirror of released code, and merging into it puts the two forges out of sync and breaks the next release push. A maintainer reviews on `contrib` and then carries your commits upstream into Gitea's `develop`, with your authorship and your sign-off intact. `contrib` is a mirror of `develop`, so you are working against the current code rather than the last release.
|
||||
|
||||
**From Gitea, if you have access:** follow the branch model below.
|
||||
|
||||
### 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` follows `develop`, so it moves whenever development does. If your branch has been open a while, rebase onto the current `contrib` before pushing again.
|
||||
|
||||
## Developer Certificate of Origin (DCO)
|
||||
|
||||
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. A mirror of `develop`, and where outside contributions land before a maintainer carries them into `develop`.
|
||||
|
||||
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
|
||||
|
||||
@@ -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>
|
||||
|
||||
---
|
||||
@@ -51,9 +56,35 @@ npm install busboy # multipart/form-data file uploads
|
||||
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
|
||||
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
|
||||
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`await app.listen()` → `await serveDeno()` / `await serveBun()` / `edgeHandler`) and nothing else — each one boots the app before it binds, so a provider that cannot start fails the deploy instead of answering `500`s from a port that looks healthy. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) 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 is `{ name, mount(api) }`. It gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
|
||||
## Who does the work?
|
||||
|
||||
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,11 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **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.
|
||||
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
|
||||
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
||||
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
||||
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||
|
||||
@@ -118,7 +153,9 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
||||
|
||||
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
|
||||
|
||||
On that harness, **green-tea handled more requests per second than every other framework in 3 of 4 scenarios** (JSON response, routing, and body-parsing-plus-validation), behind only raw `http` with no framework at all. In the fourth (a multi-step pipeline) it lands even with Fastify.
|
||||
On that harness green-tea is in the same class as Fastify and NestJS-on-Fastify, roughly 2.8× ahead of Express, and behind raw `http` with no framework at all. Within that class the shape reproduces on two very different machines: green-tea is **behind** Fastify on the JSON, routing and pipeline scenarios, and **ahead** of it on POST-plus-validation. How far behind is a property of the box rather than a constant — 2-8% on a laptop M4 Max, 7-15% on an idle desktop Ryzen — which is why the table carries its hardware and its date, and why a percentage quoted without them says little. Read [BENCHMARKS.md](./BENCHMARKS.md) rather than a sentence here: a ranking written into prose once is a claim nobody re-measures.
|
||||
|
||||
The question a release actually has to pass is the other one — *did the last N commits cost anything* — and comparing today's numbers against a table generated weeks ago answers it with two machines in a mood rather than two versions. `npm run bench:compare` runs both trees on one box in one sitting, alternating sides; `26.9.0-beta.1 → 26.9.0-beta.2` came out flat on every case.
|
||||
|
||||
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
|
||||
|
||||
@@ -243,26 +280,48 @@ 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 a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built.
|
||||
|
||||
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
|
||||
|
||||
## Docs & development
|
||||
|
||||
- **[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 +329,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.
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Compares green-tea against an earlier green-tea, on one box, in one sitting.
|
||||
*
|
||||
* `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release
|
||||
* actually has to pass: **did the last N commits cost anything.** It is a different measurement and
|
||||
* it needs a different setup, because comparing today's numbers against a table generated weeks ago
|
||||
* compares two machines-in-a-mood, not two versions.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* git worktree add /tmp/base v26.8.0-beta.1
|
||||
* ln -s "$PWD/node_modules" /tmp/base/node_modules
|
||||
* AB_BASE=/tmp/base npm run bench:compare
|
||||
*
|
||||
* The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has
|
||||
* not moved between the two revisions — check that first, or the comparison is measuring a
|
||||
* dependency bump.
|
||||
*
|
||||
* Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100),
|
||||
* `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json).
|
||||
*/
|
||||
import autocannon from 'autocannon';
|
||||
import { spawn } from 'child_process';
|
||||
import { writeFileSync } from 'fs';
|
||||
|
||||
const DURATION = Number(process.env.AB_DURATION ?? 10);
|
||||
const ROUNDS = Number(process.env.AB_ROUNDS ?? 3);
|
||||
const CONNS = Number(process.env.AB_CONNS ?? 100);
|
||||
|
||||
const HEAD = process.cwd();
|
||||
// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables.
|
||||
const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare';
|
||||
const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare';
|
||||
|
||||
function requireBase(): string {
|
||||
const base = process.env.AB_BASE;
|
||||
if (base) return base;
|
||||
console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const BASE = requireBase();
|
||||
|
||||
interface Case {
|
||||
name: string;
|
||||
path: string;
|
||||
method?: 'GET' | 'POST' | 'OPTIONS';
|
||||
body?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
|
||||
const ORIGIN = { origin: 'http://bench.example' };
|
||||
|
||||
const CASES: Case[] = [
|
||||
{ name: 'hello', path: '/hello' },
|
||||
{ name: 'param', path: '/users/42' },
|
||||
{ name: 'pipeline (3 steps)', path: '/pipeline' },
|
||||
{ name: 'steps5', path: '/steps/5' },
|
||||
{ name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } },
|
||||
{ name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } },
|
||||
// The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets
|
||||
// the header measures the path around it rather than the path through it.
|
||||
{ name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN },
|
||||
{
|
||||
name: 'preflight + cors predicate',
|
||||
path: '/hello',
|
||||
method: 'OPTIONS',
|
||||
env: { GT_CORS: '1' },
|
||||
headers: { ...ORIGIN, 'access-control-request-method': 'GET' },
|
||||
},
|
||||
// Route-table width. Every matcher cost scales with the number of candidates a request walks
|
||||
// past, and the cross-framework table has six routes — so a change that saves work per candidate
|
||||
// measures as noise there no matter how real it is. `/users/:id` is registered last and is not
|
||||
// all-static, so it takes the full scan rather than the early exit a literal path gets.
|
||||
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
|
||||
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
|
||||
];
|
||||
|
||||
const ONLY = process.env.AB_ONLY;
|
||||
const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES;
|
||||
|
||||
function log(m: string): void {
|
||||
process.stderr.write(`[compare] ${m}\n`);
|
||||
}
|
||||
|
||||
async function boot(cwd: string, env: Record<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], {
|
||||
cwd,
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env },
|
||||
});
|
||||
let stderr = '';
|
||||
child.stderr.on('data', (d) => (stderr += d));
|
||||
const port = await new Promise<number>((resolve, reject) => {
|
||||
const t = setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
reject(new Error(`no READY in 15s:\n${stderr}`));
|
||||
}, 15000);
|
||||
let buf = '';
|
||||
child.stdout.on('data', (d) => {
|
||||
buf += d;
|
||||
const m = /READY (\d+)/.exec(buf);
|
||||
if (m) {
|
||||
clearTimeout(t);
|
||||
resolve(Number(m[1]));
|
||||
}
|
||||
});
|
||||
child.on('exit', (c) => {
|
||||
clearTimeout(t);
|
||||
reject(new Error(`exited ${c}:\n${stderr}`));
|
||||
});
|
||||
});
|
||||
const kill = (): Promise<void> =>
|
||||
new Promise<void>((r) => {
|
||||
child.on('exit', () => r());
|
||||
child.kill('SIGTERM');
|
||||
setTimeout(() => {
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
/* already dead */
|
||||
}
|
||||
}, 2000);
|
||||
});
|
||||
return { port, kill };
|
||||
}
|
||||
|
||||
async function hit(port: number, c: Case, warmup = false): Promise<number> {
|
||||
const r = (await autocannon({
|
||||
url: `http://127.0.0.1:${port}${c.path}`,
|
||||
connections: CONNS,
|
||||
duration: DURATION,
|
||||
pipelining: 1,
|
||||
method: (c.method ?? 'GET') as 'GET',
|
||||
headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers },
|
||||
body: c.body ? JSON.stringify(c.body) : undefined,
|
||||
})) as unknown as {
|
||||
requests: { average: number };
|
||||
non2xx?: number;
|
||||
errors?: number;
|
||||
timeouts?: number;
|
||||
};
|
||||
|
||||
// A case whose route 404s still posts a req/s number, and a run whose connections all errored
|
||||
// posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this
|
||||
// case claims to send before believing any of it.
|
||||
// Not on the warmup: a cold server drops a handful of connections from the opening burst, and
|
||||
// absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise
|
||||
// it exists to discard.
|
||||
if (!warmup) {
|
||||
const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0);
|
||||
if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`);
|
||||
if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`);
|
||||
}
|
||||
|
||||
return r.requests.average;
|
||||
}
|
||||
|
||||
const median = (xs: number[]): number => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* True when the two sides' sample ranges do not overlap at all.
|
||||
*
|
||||
* A weak signal on its own and stated as such: with three samples a pair of overlapping
|
||||
* distributions separates by chance often enough to fool you, which it did the first time this was
|
||||
* run. Treat a flagged row as "measure it again with more rounds", never as a result.
|
||||
*/
|
||||
const separated = (a: number[], b: number[]): boolean => {
|
||||
const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)];
|
||||
return x[0] > y[y.length - 1] || y[0] > x[x.length - 1];
|
||||
};
|
||||
|
||||
/**
|
||||
* Counts `cors.origins` invocations for one cross-origin GET and one preflight.
|
||||
*
|
||||
* Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved
|
||||
* are invisible in req/s — but the option takes a function so it can be a lookup, and there the
|
||||
* same saving is a network round trip.
|
||||
*/
|
||||
async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> {
|
||||
const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server);
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
// The read carries no `Origin`, so asking cannot change the answer.
|
||||
const read = async (): Promise<number> => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls;
|
||||
|
||||
try {
|
||||
const before = await read();
|
||||
await fetch(`${base}/hello`, { headers: ORIGIN });
|
||||
const afterGet = await read();
|
||||
await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } });
|
||||
const afterPreflight = await read();
|
||||
return { get: afterGet - before, preflight: afterPreflight - afterGet };
|
||||
} finally {
|
||||
await kill();
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const samples: Record<string, { base: number[]; head: number[] }> = {};
|
||||
for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] };
|
||||
|
||||
for (let round = 0; round < ROUNDS; round++) {
|
||||
// Alternate which side goes first. Thermal drift and background load over a half-hour run are
|
||||
// real; alternating spreads them across both sides instead of charging them to whichever went
|
||||
// second.
|
||||
const order: Array<['base' | 'head', string]> =
|
||||
round % 2 === 0
|
||||
? [
|
||||
['base', BASE],
|
||||
['head', HEAD],
|
||||
]
|
||||
: [
|
||||
['head', HEAD],
|
||||
['base', BASE],
|
||||
];
|
||||
|
||||
for (const [side, cwd] of order) {
|
||||
for (const c of RUN_CASES) {
|
||||
const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER);
|
||||
try {
|
||||
await hit(port, c, true); // warmup, discarded
|
||||
const v = await hit(port, c);
|
||||
samples[c.name][side].push(v);
|
||||
log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`);
|
||||
} finally {
|
||||
await kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rows = RUN_CASES.map((c) => {
|
||||
const b = median(samples[c.name].base);
|
||||
const h = median(samples[c.name].head);
|
||||
return {
|
||||
name: c.name,
|
||||
base: b,
|
||||
head: h,
|
||||
delta: ((h - b) / b) * 100,
|
||||
separated: separated(samples[c.name].base, samples[c.name].head),
|
||||
samples: samples[c.name],
|
||||
};
|
||||
});
|
||||
|
||||
const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) };
|
||||
|
||||
writeFileSync(
|
||||
process.env.AB_OUT ?? 'bench/compare-results.json',
|
||||
JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2),
|
||||
);
|
||||
|
||||
const f = (n: number): string => Math.round(n).toLocaleString();
|
||||
console.log('\n| Scenario | base | head | Δ | |');
|
||||
console.log('| --- | --- | --- | --- | --- |');
|
||||
for (const r of rows) {
|
||||
const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps';
|
||||
console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`);
|
||||
}
|
||||
console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`);
|
||||
console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
+31
-1
@@ -37,6 +37,8 @@ export interface RenderData {
|
||||
scenarios: ScenarioBlock[];
|
||||
stepScaling: { path: string; steps: number; reqSec: number }[];
|
||||
secureCost: { label: string; reqSec: number }[];
|
||||
/** Optional: results captured before the runtime matrix existed still render. */
|
||||
runtimes?: { runtime: string; scenario: string; reqSec: number }[];
|
||||
}
|
||||
|
||||
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
|
||||
@@ -124,6 +126,33 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
|
||||
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
|
||||
}
|
||||
|
||||
/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */
|
||||
function renderRuntimes(runtimes: RenderData['runtimes']): string {
|
||||
if (!runtimes?.length) return '';
|
||||
|
||||
const names = [...new Set(runtimes.map((row) => row.runtime))];
|
||||
const scenarios = [...new Set(runtimes.map((row) => row.scenario))];
|
||||
const at = (runtime: string, scenario: string): number | undefined =>
|
||||
runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec;
|
||||
|
||||
const header = `| Scenario | ${names.join(' | ')} |`;
|
||||
const divider = `| --- | ${names.map(() => '---').join(' | ')} |`;
|
||||
const lines = scenarios.map((scenario) => {
|
||||
const cells = names.map((runtime) => {
|
||||
const value = at(runtime, scenario);
|
||||
return value === undefined ? '—' : fmtInt(value);
|
||||
});
|
||||
return `| ${scenario} | ${cells.join(' | ')} |`;
|
||||
});
|
||||
|
||||
const note =
|
||||
'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' +
|
||||
'never against the cross-framework tables above: those measure other frameworks on Node, and ' +
|
||||
'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.';
|
||||
|
||||
return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n');
|
||||
}
|
||||
|
||||
function renderSecureCost(secureCost: RenderData['secureCost']): string {
|
||||
const header = '| Label | req/s |';
|
||||
const divider = '| --- | --- |';
|
||||
@@ -196,7 +225,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
|
||||
}
|
||||
|
||||
export function renderMarkdown(data: RenderData): string {
|
||||
const { env, config, scenarios, stepScaling, secureCost } = data;
|
||||
const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
|
||||
|
||||
return [
|
||||
renderLeaderboard(scenarios),
|
||||
@@ -208,6 +237,7 @@ export function renderMarkdown(data: RenderData): string {
|
||||
'',
|
||||
renderScenarios(scenarios),
|
||||
renderStepScaling(stepScaling),
|
||||
renderRuntimes(runtimes),
|
||||
renderSecureCost(secureCost),
|
||||
renderMethodology(),
|
||||
].join('\n');
|
||||
|
||||
+266
-204
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"env": {
|
||||
"date": "2026-07-07",
|
||||
"commit": "fe1831a",
|
||||
"date": "2026-09-22",
|
||||
"commit": "daf0fed",
|
||||
"node": "v22.22.2",
|
||||
"os": "darwin",
|
||||
"cpu": "Apple M4 Max (16 cores)",
|
||||
"ram": "69 GB",
|
||||
"os": "linux",
|
||||
"cpu": "AMD Ryzen 7 3700X 8-Core Processor (16 cores)",
|
||||
"ram": "67 GB",
|
||||
"pinned": false
|
||||
},
|
||||
"config": {
|
||||
"conns": 100,
|
||||
"duration": 5,
|
||||
"runs": 3,
|
||||
"duration": 10,
|
||||
"runs": 5,
|
||||
"warmup": 1,
|
||||
"pipelining": 1
|
||||
},
|
||||
@@ -23,80 +23,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 115398.4,
|
||||
"min": 114822.4,
|
||||
"max": 115539.2,
|
||||
"stddev": 310.09010876768724,
|
||||
"cv": 0.0026905088104554075
|
||||
"median": 41630.55,
|
||||
"min": 41342.55,
|
||||
"max": 41973.82,
|
||||
"stddev": 232.79156158245826,
|
||||
"cv": 0.0055977118567263305
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 86764.8,
|
||||
"min": 86496,
|
||||
"max": 87123.2,
|
||||
"stddev": 256.9227813090051,
|
||||
"cv": 0.002960121758353106
|
||||
"median": 32170.19,
|
||||
"min": 31235.64,
|
||||
"max": 32355.64,
|
||||
"stddev": 403.36620390905324,
|
||||
"cv": 0.012593571579786219
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 24366.4,
|
||||
"min": 24283.2,
|
||||
"max": 24417.6,
|
||||
"stddev": 55.38455460585383,
|
||||
"cv": 0.002273984274990166
|
||||
"median": 10545.82,
|
||||
"min": 10480.37,
|
||||
"max": 10625.1,
|
||||
"stddev": 47.02831087759791,
|
||||
"cv": 0.004456044641032285
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
"p50": 8,
|
||||
"p99": 13,
|
||||
"p999": 18
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 98092.8,
|
||||
"min": 98054.4,
|
||||
"max": 98668.8,
|
||||
"stddev": 281.0175795212842,
|
||||
"cv": 0.002859589501804015
|
||||
"median": 29776.73,
|
||||
"min": 29557.1,
|
||||
"max": 29872.73,
|
||||
"stddev": 120.92248317000461,
|
||||
"cv": 0.004066812850878315
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 7
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 21761.6,
|
||||
"min": 21697.6,
|
||||
"max": 21896,
|
||||
"stddev": 82.67870880032535,
|
||||
"cv": 0.0037952010918943873
|
||||
"median": 9679.64,
|
||||
"min": 9566.91,
|
||||
"max": 9738.55,
|
||||
"stddev": 58.2951632985104,
|
||||
"cv": 0.006025529205104781
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 10
|
||||
"p50": 9,
|
||||
"p99": 15,
|
||||
"p999": 21
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 95033.6,
|
||||
"min": 94240,
|
||||
"max": 95264,
|
||||
"stddev": 438.6166536839312,
|
||||
"cv": 0.00462452048886261
|
||||
"median": 32418.91,
|
||||
"min": 32103.28,
|
||||
"max": 32582.55,
|
||||
"stddev": 159.574135748874,
|
||||
"cv": 0.004929287112917938
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -107,80 +107,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 116332.8,
|
||||
"min": 115974.4,
|
||||
"max": 116409.6,
|
||||
"stddev": 189.66281191162406,
|
||||
"cv": 0.001631663389130871
|
||||
"median": 41755.64,
|
||||
"min": 40952.73,
|
||||
"max": 42017.46,
|
||||
"stddev": 439.72294183496837,
|
||||
"cv": 0.010587809774433589
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 86278.4,
|
||||
"min": 86137.6,
|
||||
"max": 86764.8,
|
||||
"stddev": 268.69839349476365,
|
||||
"cv": 0.003110165492522174
|
||||
"median": 31708.37,
|
||||
"min": 31359.28,
|
||||
"max": 31846.55,
|
||||
"stddev": 168.73300179869975,
|
||||
"cv": 0.005328784944282288
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 23835.2,
|
||||
"min": 23803.2,
|
||||
"max": 24046.4,
|
||||
"stddev": 107.89690552662897,
|
||||
"cv": 0.004515472130491916
|
||||
"median": 10375.64,
|
||||
"min": 10364,
|
||||
"max": 10452.73,
|
||||
"stddev": 37.668132419858544,
|
||||
"cv": 0.003621859193349617
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
"p50": 9,
|
||||
"p99": 12,
|
||||
"p999": 17
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 93433.6,
|
||||
"min": 93152,
|
||||
"max": 93612.8,
|
||||
"stddev": 189.6628119116206,
|
||||
"cv": 0.002030662686635119
|
||||
"median": 28706.19,
|
||||
"min": 28562.19,
|
||||
"max": 29050.91,
|
||||
"stddev": 166.92265315408858,
|
||||
"cv": 0.005803163694455583
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 7
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 20955.2,
|
||||
"min": 20948.8,
|
||||
"max": 21201.6,
|
||||
"stddev": 117.69157432317111,
|
||||
"cv": 0.005594982425799189
|
||||
"median": 9257.1,
|
||||
"min": 9244,
|
||||
"max": 9285.46,
|
||||
"stddev": 16.97885461390117,
|
||||
"cv": 0.0018327336012062287
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 11
|
||||
"p50": 10,
|
||||
"p99": 15,
|
||||
"p999": 21
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 89312,
|
||||
"min": 89235.2,
|
||||
"max": 89529.6,
|
||||
"stddev": 124.68598780759793,
|
||||
"cv": 0.001395338811201841
|
||||
"median": 29880,
|
||||
"min": 29744.73,
|
||||
"max": 29961.46,
|
||||
"stddev": 90.38256681462417,
|
||||
"cv": 0.003027383166346
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -192,80 +192,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 113491.2,
|
||||
"min": 112531.2,
|
||||
"max": 114809.6,
|
||||
"stddev": 933.9810324031724,
|
||||
"cv": 0.008220892102882115
|
||||
"median": 39896.73,
|
||||
"min": 39847.28,
|
||||
"max": 40440.73,
|
||||
"stddev": 235.6558649726337,
|
||||
"cv": 0.0058846766178520865
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 85024,
|
||||
"min": 84512,
|
||||
"max": 85177.6,
|
||||
"stddev": 284.55819947576623,
|
||||
"cv": 0.003351507726431956
|
||||
"median": 31436.37,
|
||||
"min": 31078.55,
|
||||
"max": 31562.91,
|
||||
"stddev": 185.21052212010017,
|
||||
"cv": 0.005909263441314207
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 23950.4,
|
||||
"min": 23902.4,
|
||||
"max": 24011.2,
|
||||
"stddev": 44.519758410046,
|
||||
"cv": 0.0018585004345727763
|
||||
"median": 10365.46,
|
||||
"min": 10170.55,
|
||||
"max": 10542.19,
|
||||
"stddev": 129.83340146510884,
|
||||
"cv": 0.01252603707960138
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
"p50": 9,
|
||||
"p99": 12,
|
||||
"p999": 18
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 84896,
|
||||
"min": 84243.2,
|
||||
"max": 85267.2,
|
||||
"stddev": 423.2825796347192,
|
||||
"cv": 0.004991414284012342
|
||||
"median": 26838.55,
|
||||
"min": 26783.28,
|
||||
"max": 26872,
|
||||
"stddev": 35.930271582608675,
|
||||
"cv": 0.0013390899572667937
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 8
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 20824,
|
||||
"min": 20804.8,
|
||||
"max": 20878.41,
|
||||
"stddev": 31.17605954717337,
|
||||
"cv": 0.001496278247605678
|
||||
"median": 9256.37,
|
||||
"min": 9187.28,
|
||||
"max": 9302.19,
|
||||
"stddev": 42.180541200890175,
|
||||
"cv": 0.0045584972844857205
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 11
|
||||
"p50": 10,
|
||||
"p99": 15,
|
||||
"p999": 22
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 87328,
|
||||
"min": 86867.2,
|
||||
"max": 87660.8,
|
||||
"stddev": 325.38753646827104,
|
||||
"cv": 0.0037278603866430907
|
||||
"median": 29402.91,
|
||||
"min": 29151.28,
|
||||
"max": 29689.46,
|
||||
"stddev": 189.99449229911926,
|
||||
"cv": 0.006460862473261261
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -276,80 +276,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 100140.8,
|
||||
"min": 99846.4,
|
||||
"max": 100294.4,
|
||||
"stddev": 185.88177843875883,
|
||||
"cv": 0.0018570746103533369
|
||||
"median": 31783.28,
|
||||
"min": 31517.1,
|
||||
"max": 31824.73,
|
||||
"stddev": 111.5598838292694,
|
||||
"cv": 0.003516116881358333
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 6
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 63721.6,
|
||||
"min": 63574.4,
|
||||
"max": 63760,
|
||||
"stddev": 79.99288857281053,
|
||||
"cv": 0.0012560645345785087
|
||||
"median": 20429.82,
|
||||
"min": 20397.82,
|
||||
"max": 20601.46,
|
||||
"stddev": 73.12471046096515,
|
||||
"cv": 0.0035727493036941836
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 3
|
||||
"p50": 4,
|
||||
"p99": 8,
|
||||
"p999": 9
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 20097.6,
|
||||
"min": 20056,
|
||||
"max": 20174.41,
|
||||
"stddev": 49.04789518646266,
|
||||
"cv": 0.0024390608203285337
|
||||
"median": 8440.37,
|
||||
"min": 8407.64,
|
||||
"max": 8492,
|
||||
"stddev": 29.52737333390846,
|
||||
"cv": 0.003496408589959768
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 12
|
||||
"p50": 11,
|
||||
"p99": 16,
|
||||
"p999": 24
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 77177.61,
|
||||
"min": 77126.4,
|
||||
"max": 77254.4,
|
||||
"stddev": 52.602458962379814,
|
||||
"cv": 0.0006815013839797027
|
||||
"median": 22005.1,
|
||||
"min": 21736,
|
||||
"max": 22186.91,
|
||||
"stddev": 149.1731413626461,
|
||||
"cv": 0.006790967759795645
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
"p50": 4,
|
||||
"p99": 7,
|
||||
"p999": 9
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 18856,
|
||||
"min": 18852.8,
|
||||
"max": 19067.2,
|
||||
"stddev": 100.32338821143516,
|
||||
"cv": 0.005301010367660728
|
||||
"median": 7666.37,
|
||||
"min": 7645.28,
|
||||
"max": 7703.46,
|
||||
"stddev": 20.418688106732038,
|
||||
"cv": 0.002662071942974812
|
||||
},
|
||||
"p50": 5,
|
||||
"p99": 7,
|
||||
"p999": 30
|
||||
"p50": 12,
|
||||
"p99": 18,
|
||||
"p999": 26
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 59145.6,
|
||||
"min": 59004.8,
|
||||
"max": 59376,
|
||||
"stddev": 153.00625985741647,
|
||||
"cv": 0.002585636725423652
|
||||
"median": 18596.8,
|
||||
"min": 18540.37,
|
||||
"max": 18658.19,
|
||||
"stddev": 37.943211988443956,
|
||||
"cv": 0.0020404741150848267
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 3,
|
||||
"p999": 3
|
||||
"p50": 4,
|
||||
"p99": 8,
|
||||
"p999": 11
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -358,27 +358,89 @@
|
||||
{
|
||||
"path": "/steps/0",
|
||||
"steps": 0,
|
||||
"reqSec": 92281.6
|
||||
"reqSec": 29196.37
|
||||
},
|
||||
{
|
||||
"path": "/steps/3",
|
||||
"steps": 3,
|
||||
"reqSec": 81529.61
|
||||
"reqSec": 26563.64
|
||||
},
|
||||
{
|
||||
"path": "/steps/5",
|
||||
"steps": 5,
|
||||
"reqSec": 71993.61
|
||||
"reqSec": 25314.19
|
||||
}
|
||||
],
|
||||
"secureCost": [
|
||||
{
|
||||
"label": "security:false (parity)",
|
||||
"reqSec": 98092.8
|
||||
"reqSec": 29776.73
|
||||
},
|
||||
{
|
||||
"label": "security:true (default)",
|
||||
"reqSec": 92998.4
|
||||
"reqSec": 28918.55
|
||||
}
|
||||
],
|
||||
"runtimes": [
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 30378.91
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 29203.64
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 27208
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 22608.73
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 51888
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 51785.6
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 50692.37
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 35742.55
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 46299.64
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 42788.37
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 39643.64
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 31960
|
||||
}
|
||||
]
|
||||
}
|
||||
+78
-4
@@ -1,17 +1,30 @@
|
||||
import autocannon from 'autocannon';
|
||||
import { spawn, execSync } from 'child_process';
|
||||
import os from 'os';
|
||||
import { writeFileSync } from 'fs';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
||||
import { aggregate } from './stats';
|
||||
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
||||
|
||||
/** Hand-written notes start here and are carried across regenerations verbatim. */
|
||||
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
|
||||
|
||||
const SMOKE = process.env.BENCH_SMOKE === '1';
|
||||
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
||||
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
||||
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
||||
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
||||
|
||||
/** Whether a runtime is on PATH. */
|
||||
function which(cmd: string): boolean {
|
||||
try {
|
||||
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function log(msg: string): void {
|
||||
process.stderr.write(`[bench] ${msg}\n`);
|
||||
}
|
||||
@@ -23,11 +36,25 @@ interface RunResult {
|
||||
p999: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
|
||||
* are handed to their own runtime, which is the whole point of measuring them.
|
||||
*/
|
||||
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
|
||||
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
|
||||
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
|
||||
// missing flag fails as a boot timeout that reads like a framework problem.
|
||||
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
|
||||
bun: (file) => ({ cmd: 'bun', args: [file] }),
|
||||
};
|
||||
|
||||
async function spawnServer(
|
||||
name: string,
|
||||
extraEnv: Record<string, string> = {},
|
||||
runtime: 'node' | 'deno' | 'bun' = 'node',
|
||||
): Promise<{ port: number; kill: () => Promise<void> }> {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
|
||||
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
|
||||
const child = spawn(cmd, args, {
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
||||
});
|
||||
let stderr = '';
|
||||
@@ -96,6 +123,7 @@ async function main(): Promise<void> {
|
||||
}));
|
||||
const stepScaling: RenderData['stepScaling'] = [];
|
||||
const secureCost: RenderData['secureCost'] = [];
|
||||
const runtimes: RenderData['runtimes'] = [];
|
||||
|
||||
for (const fw of frameworks) {
|
||||
log(`booting ${fw}`);
|
||||
@@ -145,10 +173,49 @@ async function main(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
|
||||
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
|
||||
// fastify-on-Node would read as a comparison nobody made.
|
||||
//
|
||||
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
|
||||
// runtime is not installed — a contributor without Bun should still get every other table.
|
||||
for (const { runtime, server } of [
|
||||
{ runtime: 'node', server: 'green-tea-node' },
|
||||
{ runtime: 'deno', server: 'green-tea-deno' },
|
||||
{ runtime: 'bun', server: 'green-tea-bun' },
|
||||
] as const) {
|
||||
if (runtime !== 'node' && !which(runtime)) {
|
||||
log(`skipping ${runtime}: not installed`);
|
||||
continue;
|
||||
}
|
||||
|
||||
log(`booting green-tea on ${runtime}`);
|
||||
|
||||
try {
|
||||
const { port, kill } = await spawnServer(server, {}, runtime);
|
||||
|
||||
try {
|
||||
for (const s of SCENARIOS) {
|
||||
const runs = await measure(port, s.path, s.method, s.body);
|
||||
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
||||
}
|
||||
} finally {
|
||||
await kill();
|
||||
}
|
||||
} catch (error) {
|
||||
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
|
||||
// of the run over.
|
||||
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
|
||||
}
|
||||
}
|
||||
|
||||
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
||||
const data: RenderData = {
|
||||
env: {
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
// Project time, not the runner's. A benchmark is often driven over ssh against a box that
|
||||
// keeps UTC, and a run made on the evening of the 22nd then dates itself the 23rd — which
|
||||
// reads as a day of drift against the commit and the changelog entry beside it.
|
||||
date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }),
|
||||
commit,
|
||||
node: process.version,
|
||||
os: os.platform(),
|
||||
@@ -160,8 +227,15 @@ async function main(): Promise<void> {
|
||||
scenarios: scenarioBlocks,
|
||||
stepScaling,
|
||||
secureCost,
|
||||
runtimes,
|
||||
};
|
||||
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
|
||||
// Everything below the marker is written by hand and survives a re-run. The generated tables
|
||||
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
|
||||
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
|
||||
// history this file exists to keep gets lost a second time.
|
||||
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
|
||||
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
|
||||
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
|
||||
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
||||
log('wrote BENCHMARKS.md + bench/results.json');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
|
||||
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
|
||||
// secure-by-default headers, and a `cors.origins` predicate.
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
|
||||
// change what it reports.
|
||||
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
|
||||
// one this release stopped evaluating two and three times per request.
|
||||
const ALLOWED = new Set(['http://bench.example']);
|
||||
let corsCalls = 0;
|
||||
const cors =
|
||||
process.env.GT_CORS === '1'
|
||||
? {
|
||||
origins: (o: string) => {
|
||||
corsCalls++;
|
||||
return ALLOWED.has(o);
|
||||
},
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const app = createApp({
|
||||
modules: [BenchModule],
|
||||
security: process.env.GT_SECURE === '1',
|
||||
...(cors ? { cors } : {}),
|
||||
});
|
||||
|
||||
async function main() {
|
||||
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
|
||||
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
|
||||
const server = await app.listen(0);
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,84 @@
|
||||
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
|
||||
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
|
||||
// secure-by-default headers, and a `cors.origins` predicate.
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
|
||||
|
||||
type Ctor = new (...args: any[]) => any;
|
||||
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
|
||||
// change what it reports.
|
||||
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
|
||||
}
|
||||
|
||||
// Filler routes, so the width of the route table becomes a dimension the harness can see.
|
||||
//
|
||||
// Every matcher cost discussed for this file — the specificity scan, the per-candidate
|
||||
// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate
|
||||
// routes a request has to walk past. At the six routes the cross-framework table uses, all of them
|
||||
// measure as noise, which says nothing about them and everything about the instrument. `/users/:id`
|
||||
// is declared last so a request for it pays the full scan.
|
||||
function fillerRoutes(count: number): Ctor[] {
|
||||
return Array.from({ length: count }, (_, i) => {
|
||||
@Route(`/filler${i}`)
|
||||
class Filler {
|
||||
@Get('/:a/:b') ab(@param('a') a: string) {
|
||||
return { a };
|
||||
}
|
||||
}
|
||||
return Filler as Ctor;
|
||||
});
|
||||
}
|
||||
|
||||
const EXTRA = Number(process.env.GT_ROUTES ?? 0);
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
|
||||
// one this release stopped evaluating two and three times per request.
|
||||
const ALLOWED = new Set(['http://bench.example']);
|
||||
let corsCalls = 0;
|
||||
const cors =
|
||||
process.env.GT_CORS === '1'
|
||||
? {
|
||||
origins: (o: string) => {
|
||||
corsCalls++;
|
||||
return ALLOWED.has(o);
|
||||
},
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const app = createApp({
|
||||
modules: [BenchModule],
|
||||
security: process.env.GT_SECURE === '1',
|
||||
...(cors ? { cors } : {}),
|
||||
});
|
||||
|
||||
async function main() {
|
||||
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
|
||||
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
|
||||
const server = await app.listen(0);
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -30,5 +30,5 @@ class Bench {
|
||||
class BenchModule {}
|
||||
|
||||
const app = createApp({ modules: [BenchModule], security: false });
|
||||
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' });
|
||||
const server = await serveBun(app, { port: 0, hostname: '0.0.0.0' });
|
||||
console.log(`READY ${server.port}`);
|
||||
@@ -30,4 +30,4 @@ class Bench {
|
||||
class BenchModule {}
|
||||
|
||||
const app = createApp({ modules: [BenchModule], security: false });
|
||||
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
|
||||
await serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
|
||||
|
||||
// Same BenchModule as green-tea.ts, but loaded from `dist/` rather than `src/`.
|
||||
//
|
||||
// The runtimes table exists to vary the runtime. The Deno and Bun servers import the built bundle
|
||||
// because that is the only form those runtimes can load here, so a Node row reading `src/` through
|
||||
// tsx would vary the load form at the same time and the table would answer neither question.
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/0') steps0() { return { hello: 'world' }; }
|
||||
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
const app = createApp({ modules: [BenchModule], security: false });
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const server = await app.listen(0);
|
||||
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
|
||||
console.log(`READY ${(server.address() as { port: number }).port}`);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
+10
-1
@@ -1,5 +1,14 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true },
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"noEmit": true,
|
||||
// The bench servers are ES modules, run by tsx, Deno and Bun rather than by the CommonJS build
|
||||
// the root config describes. `serveDeno`/`serveBun` became async in 26.9.0-beta.2, so two of
|
||||
// them now open with a top-level `await`, which `module: commonjs` rejects outright.
|
||||
"module": "es2022",
|
||||
"moduleResolution": "bundler"
|
||||
},
|
||||
"include": ["."]
|
||||
}
|
||||
@@ -1,4 +1,19 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.9.0-beta.2",
|
||||
"license": "MIT",
|
||||
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
|
||||
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
|
||||
// `@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,89 @@
|
||||
# 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.
|
||||
|
||||
**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the
|
||||
`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped
|
||||
exporting providers — with nothing cached between requests, there is nothing left to invalidate.
|
||||
This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the
|
||||
*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the
|
||||
seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
|
||||
`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,108 @@
|
||||
# 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.
|
||||
|
||||
**Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the
|
||||
remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the
|
||||
`onReconnect` callback went with that — there is no cached value left to invalidate, so a
|
||||
reconnected link is simply usable again on the next RPC. The rest of this plan shipped as
|
||||
written; only this step has no counterpart in the code.
|
||||
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
|
||||
Reconnect defaults **on**. Validate at boot like the other mesh options.
|
||||
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
|
||||
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.
|
||||
@@ -0,0 +1,710 @@
|
||||
# A mesh that exports steps, not providers
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or
|
||||
> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking.
|
||||
|
||||
**Status:** planned, 2026-09-06
|
||||
**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`,
|
||||
mesh tests on all runtimes, `README.md`, `CHANGELOG.md`
|
||||
**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a
|
||||
protocol bump because of it.
|
||||
|
||||
**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error,
|
||||
and a teapot that is unreachable at boot no longer stops the teacup from starting.
|
||||
|
||||
## The problem
|
||||
|
||||
`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot
|
||||
cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses
|
||||
any class instance, so an exported provider can only ever return plain data. What survives is the
|
||||
worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope**
|
||||
binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the
|
||||
process. It is a cache the teapot no longer stands behind, wearing the word "provider".
|
||||
|
||||
A step is the shape that actually works across the mesh. It runs per request, the teacup sends the
|
||||
envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to
|
||||
the token. Transparent to the caller, and nothing is held.
|
||||
|
||||
Two things follow from that, and they are the whole of this plan:
|
||||
|
||||
1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative
|
||||
already exists and is spelled `@Step({ export: true })`.
|
||||
2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value
|
||||
has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is
|
||||
away costs a `503` on the requests that need it, and the app starts.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a
|
||||
warning would leave a running app whose token resolves locally and looks exported. The error names
|
||||
the replacement, so the message is a fix and not a complaint.
|
||||
|
||||
**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in
|
||||
`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`,
|
||||
both peers ship from this repo, and a bump would spend the number on a version nobody deployed.
|
||||
`MESH_PROTOCOL_VERSION` stays `1`.
|
||||
|
||||
**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the
|
||||
design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The
|
||||
loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the
|
||||
manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots
|
||||
into a graph with no `authorization` node, which is strictly worse than today. So the budget stays;
|
||||
exhausting it now warns and contributes nothing, instead of failing the boot.
|
||||
|
||||
**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a
|
||||
protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and
|
||||
they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at
|
||||
3am that says nothing about a secret. Only *unreachable* becomes non-fatal.
|
||||
|
||||
**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away
|
||||
and a local step declares `needs: ['authorization']`, `topoSort` throws
|
||||
`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to
|
||||
remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and
|
||||
`503` forever. The message gains the teapots that did not connect, so the cause is on the screen.
|
||||
|
||||
**D6 — The `expects` / degrade plan survives; its D6 does not.**
|
||||
`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may
|
||||
legitimately be absent", and it is already steps-only. But its D6 reuses
|
||||
`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded
|
||||
step swaps a runner, not a container binding. Note it there rather than leave a dangling reference.
|
||||
|
||||
## File structure
|
||||
|
||||
| File | Change |
|
||||
| --- | --- |
|
||||
| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row |
|
||||
| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` |
|
||||
| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` |
|
||||
| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error |
|
||||
| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal |
|
||||
| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` |
|
||||
| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 |
|
||||
|
||||
## A note on the line numbers
|
||||
|
||||
Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol —
|
||||
`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph`
|
||||
— and treat the numbers as hints.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Forbid exporting a provider
|
||||
|
||||
The prohibition lands first and alone, because every later task assumes it. Nothing on the wire
|
||||
changes yet.
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:440` (`collectProviders`)
|
||||
- Test: `test/mesh/failure.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```ts
|
||||
// test/mesh/failure.test.ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Module } from '../../src/index';
|
||||
|
||||
describe('provider export', () => {
|
||||
it('refuses to boot when a provider is exported over the mesh', async () => {
|
||||
@Provider({ provides: 'db', needs: [], export: true } as any)
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { query: () => [] } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db] })
|
||||
class AppModule {}
|
||||
|
||||
expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow(
|
||||
/provider 'db' cannot be exported/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run it and watch it fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
|
||||
```
|
||||
|
||||
Expected: FAIL — no error is thrown, the app builds.
|
||||
|
||||
- [ ] **Step 3: Throw in `collectProviders`**
|
||||
|
||||
Replace `src/app/index.ts:440`:
|
||||
|
||||
```ts
|
||||
if (meta.export) registry.exportedProviders.push(meta.provides);
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```ts
|
||||
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
|
||||
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
|
||||
// resolved once and cached for the life of the process. A step is the shape that travels:
|
||||
// it runs per request, on the teapot, and only its result comes back.
|
||||
if (meta.export)
|
||||
throw new Error(
|
||||
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
|
||||
'is the object itself, and the mesh transports data, not objects. ' +
|
||||
'Export a @Step instead, which runs on the teapot per request and returns its result.',
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run it and watch it pass**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Fix every test that exported a provider**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`.
|
||||
Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`,
|
||||
`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts test/
|
||||
git commit -m "feat(mesh)!: refuse to export a provider
|
||||
|
||||
A provider's value is the object it builds, which cannot cross a JSON wire.
|
||||
What did cross became an app-scope binding the teacup resolved once at boot
|
||||
and served from a cache the teapot no longer stood behind. A step is the
|
||||
shape that travels; the error says so."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: A manifest of steps and routes
|
||||
|
||||
**Files**
|
||||
- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`)
|
||||
- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent)
|
||||
- Modify: `src/mesh/teacup.ts` (`buildRemote`)
|
||||
- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison)
|
||||
- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts`
|
||||
|
||||
**Interfaces**
|
||||
- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }`
|
||||
- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest`
|
||||
- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }`
|
||||
- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```ts
|
||||
// test/mesh/protocol.test.ts
|
||||
it('encodes a manifest of step names', () => {
|
||||
const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }));
|
||||
expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] });
|
||||
});
|
||||
|
||||
it('rejects a manifest whose steps are not an array', () => {
|
||||
expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow(
|
||||
/steps and routes must be arrays/,
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// test/mesh/teapot.test.ts
|
||||
it('builds a manifest from step tokens and routes', () => {
|
||||
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
|
||||
steps: ['auth'],
|
||||
routes: [{ method: 'GET', pattern: '/u/:id' }],
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// test/mesh/teacup.test.ts
|
||||
it('turns every manifest step into a lazy remote node', async () => {
|
||||
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
|
||||
const { steps, routes } = buildRemote(link);
|
||||
|
||||
expect(routes).toEqual([]);
|
||||
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
|
||||
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them and watch them fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`.
|
||||
|
||||
- [ ] **Step 3: Change the protocol**
|
||||
|
||||
In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* A mesh server's advertised steps and routes.
|
||||
*
|
||||
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
|
||||
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
|
||||
* lazy — the token exists in the teacup's graph, and running it is an RPC.
|
||||
*/
|
||||
export interface Manifest {
|
||||
steps: string[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
```
|
||||
|
||||
In the `Frame` union, replace the `manifest` member:
|
||||
|
||||
```ts
|
||||
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
|
||||
```
|
||||
|
||||
And its `SHAPE` row:
|
||||
|
||||
```ts
|
||||
manifest: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
|
||||
},
|
||||
```
|
||||
|
||||
Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still
|
||||
carry a `Date` or a `Map`.
|
||||
|
||||
- [ ] **Step 4: Change `buildManifest`**
|
||||
|
||||
In `src/mesh/teapot.ts`, replace the function at `:43-56`:
|
||||
|
||||
```ts
|
||||
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||
return { steps: [...args.steps], routes: args.routes };
|
||||
}
|
||||
```
|
||||
|
||||
Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends
|
||||
`steps: manifest.steps` in place of `scopes: manifest.scopes`.
|
||||
|
||||
The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3
|
||||
— a task must leave the tree typechecking, and splitting a signature from its only call site across
|
||||
two commits leaves a broken commit in history:
|
||||
|
||||
```ts
|
||||
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
|
||||
```
|
||||
|
||||
`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field.
|
||||
|
||||
- [ ] **Step 5: Change `buildRemote`**
|
||||
|
||||
In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`):
|
||||
|
||||
```ts
|
||||
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
|
||||
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
|
||||
name: token,
|
||||
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
|
||||
}));
|
||||
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
|
||||
return { steps, routes };
|
||||
}
|
||||
```
|
||||
|
||||
The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and
|
||||
`resolveScope` on the teapot side resolves both the same way.
|
||||
|
||||
- [ ] **Step 6: Update the refuse policy in `link.ts`**
|
||||
|
||||
Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it:
|
||||
a returned manifest must still contain every step token the link contributed at boot, and every
|
||||
route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect
|
||||
plan).
|
||||
|
||||
- [ ] **Step 7: Typecheck, then run the mesh suite**
|
||||
|
||||
```bash
|
||||
npm run typecheck && npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl`
|
||||
call site was missed.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add src/mesh/ test/mesh/
|
||||
git commit -m "refactor(mesh)!: a manifest carries step names, not scoped tokens
|
||||
|
||||
Every exported token is request-scope now, so the lifetime field had one
|
||||
value and told a reader nothing. No protocol bump: mesh is alpha, both
|
||||
peers ship from this repo, and the number should mean incompatibility
|
||||
between deployed versions."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: The teacup stops splicing providers
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`)
|
||||
- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`)
|
||||
- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`)
|
||||
- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`)
|
||||
- Test: `test/mesh/integration.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })`
|
||||
(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made
|
||||
that fixture fail at boot, so converting it is not optional — and converting it is the regression
|
||||
guard, because a step re-runs where the provider was cached:
|
||||
|
||||
```ts
|
||||
// test/mesh/integration.test.ts — replaces the @Provider fixture at :6
|
||||
let configCalls = 0;
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
run() {
|
||||
configCalls += 1;
|
||||
return { config: { region: 'mx', call: configCalls } };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
and add, alongside the existing `/local/who` assertion:
|
||||
|
||||
```ts
|
||||
it('re-runs the RPC on every request rather than caching a boot value', async () => {
|
||||
// same teapot/teacup pair the '/local/who' test stands up
|
||||
expect((await hit('/api/local/who')).config.call).toBe(1);
|
||||
expect((await hit('/api/local/who')).config.call).toBe(2);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run it — it should already pass, and that is the point**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC'
|
||||
```
|
||||
|
||||
Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable
|
||||
through provider export, which Task 1 made impossible — once `config` is a step it lands in the
|
||||
request-scope bucket and already re-runs. The guard exists so that removing the splice in the next
|
||||
steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it.
|
||||
|
||||
- [ ] **Step 3: Delete `exportedProviders`**
|
||||
|
||||
Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In
|
||||
`buildMeshControl` (`:1078-1088`):
|
||||
|
||||
```ts
|
||||
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
|
||||
const hasExports = exportedSteps.length || exportedRoutes.length;
|
||||
// ...
|
||||
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Delete the remote-provider splice**
|
||||
|
||||
In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls
|
||||
`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block
|
||||
(`:846-856`). Destructure only what is left:
|
||||
|
||||
```ts
|
||||
const { steps, routes } = buildRemote(link);
|
||||
```
|
||||
|
||||
Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter
|
||||
from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and
|
||||
nowhere else in the function.
|
||||
|
||||
The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between
|
||||
requests, so a reconnected link is simply usable again on the next RPC.
|
||||
|
||||
- [ ] **Step 5: Run the full suite and the typechecker**
|
||||
|
||||
```bash
|
||||
npm run typecheck && npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Expected: PASS, and no unused-symbol errors.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts test/mesh/
|
||||
git commit -m "refactor(mesh): drop the remote app-scope binding and its rebind seam
|
||||
|
||||
A remote provider was registered app-scope, resolved once, and cached for
|
||||
the process lifetime; invalidateRemoteBindings existed only to un-cache it
|
||||
on reconnect. With providers gone from the manifest, both go, and a remote
|
||||
step needs nothing on reconnect because it holds nothing between requests."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: An unreachable teapot does not stop the boot
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`)
|
||||
- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`)
|
||||
- Modify: `src/graph.ts:54` (the missing-dependency message)
|
||||
- Test: `test/mesh/boot-retry.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```ts
|
||||
// test/mesh/boot-retry.test.ts
|
||||
it('boots when a teapot is unreachable and nothing local needs it', async () => {
|
||||
const app = createApp({
|
||||
modules: [LocalOnlyModule], // declares no needs on a remote token
|
||||
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
|
||||
});
|
||||
|
||||
await expect(app.ready()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
|
||||
const app = createApp({
|
||||
modules: [NeedsAuthModule], // a step with needs: ['auth']
|
||||
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
|
||||
});
|
||||
|
||||
await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
|
||||
});
|
||||
|
||||
it('still fails the boot when the teapot refuses the secret', async () => {
|
||||
// stand up a teapot with secret 'right', connect with 'wrong'
|
||||
await expect(app.ready()).rejects.toThrow(/refused/i);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them and watch the first two fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/boot-retry.test.ts
|
||||
```
|
||||
|
||||
Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message
|
||||
(it says `missing dependency: auth` with no mention of the teapot), the third passes already.
|
||||
|
||||
- [ ] **Step 3: Make budget exhaustion non-fatal**
|
||||
|
||||
In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the
|
||||
permanent-refusal `throw` (D4). Change the return type to `Promise<Link | undefined>` and replace
|
||||
the exhaustion branch:
|
||||
|
||||
```ts
|
||||
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
|
||||
// proxied route now, so an absent teapot costs a 503 on the requests that need it — and a
|
||||
// teacup that refuses to start takes down the half of itself that never needed the teapot.
|
||||
if (remaining <= 0) {
|
||||
logger.warn(
|
||||
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
|
||||
`(${(error as Error).message}) — starting without it; its steps and routes will 503`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
```
|
||||
|
||||
In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url:
|
||||
|
||||
```ts
|
||||
const link = await connectUntilDeadline(/* … */);
|
||||
if (!link) {
|
||||
absent.push(teapot.url);
|
||||
continue;
|
||||
}
|
||||
```
|
||||
|
||||
Return `absent` alongside `remoteRoutes` and `meshLinks`.
|
||||
|
||||
- [ ] **Step 4: Name the absent teapots in the missing-dependency error**
|
||||
|
||||
`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note
|
||||
instead of mesh knowledge — note the capital S, and that `seedKeys` stays second:
|
||||
|
||||
```ts
|
||||
// src/graph.ts:46
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] {
|
||||
```
|
||||
|
||||
and at the throw (`src/graph.ts:54`):
|
||||
|
||||
```ts
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`);
|
||||
```
|
||||
|
||||
The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its
|
||||
signature rather than reaching for a module-level variable:
|
||||
|
||||
```ts
|
||||
// src/app/index.ts:654 — finalizeGraph gains a trailing optional param
|
||||
function finalizeGraph(
|
||||
registry: Registry,
|
||||
logger: Logger,
|
||||
warnDepth: number | false = DEEP_GRAPH_WARN,
|
||||
missingNote?: (key: string) => string,
|
||||
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
||||
const { providerNodes, stepNodes, routePlans } = registry;
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
|
||||
```
|
||||
|
||||
`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`:
|
||||
|
||||
```ts
|
||||
// Without this the error is `missing dependency: auth needed by getUser` and says nothing about
|
||||
// the teapot that was away — which is the actual cause every time it is the cause.
|
||||
const meshNote = absent.length
|
||||
? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}`
|
||||
: undefined;
|
||||
```
|
||||
|
||||
The note is unconditional on the key rather than per-token on purpose: the teacup does not know
|
||||
which teapot *would* have owned a token it never received a manifest for, and guessing would put a
|
||||
wrong url in an error. Listing the ones that were away is true and enough.
|
||||
|
||||
- [ ] **Step 5: Run them and watch them pass**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/boot-retry.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS, all three.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts
|
||||
git commit -m "feat(mesh): an unreachable teapot no longer stops the teacup from booting
|
||||
|
||||
Blocking existed for app-scope exports, which have to resolve at boot
|
||||
because there is no later. Steps and proxied routes are all later. The
|
||||
grace budget stays -- a co-deploy still waits -- but exhausting it now
|
||||
warns instead of throwing. A missing token still fails the boot, and the
|
||||
error now names the teapots that were away."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: The other runtimes
|
||||
|
||||
`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and
|
||||
`src/app/index.ts` — exactly the code AGENTS.md says to run them for.
|
||||
|
||||
**Files**
|
||||
- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`,
|
||||
`test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts`
|
||||
- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`
|
||||
|
||||
- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step**
|
||||
|
||||
```bash
|
||||
grep -rn "export: true" test/deno test/bun test/interop test/edge
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run each runtime suite**
|
||||
|
||||
```bash
|
||||
npm run test:deno
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a
|
||||
mismatch here means one side was missed.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add test/
|
||||
git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Say it in the docs
|
||||
|
||||
**Files**
|
||||
- Modify: `README.md` (mesh section)
|
||||
- Modify: `CHANGELOG.md` (`[Unreleased]`)
|
||||
- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6)
|
||||
|
||||
- [ ] **Step 1: README**
|
||||
|
||||
In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails
|
||||
at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`;
|
||||
a missing token still fails the boot, and that is deliberate.
|
||||
|
||||
- [ ] **Step 2: CHANGELOG**
|
||||
|
||||
Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag
|
||||
ships, never earlier.
|
||||
|
||||
```markdown
|
||||
### Changed
|
||||
|
||||
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
|
||||
at boot. A provider's value is the object it builds, which cannot cross a JSON wire; what did
|
||||
cross became an app-scope binding the teacup resolved once and cached for the life of the
|
||||
process. Export a `@Step` instead — it runs on the teapot per request and returns its result.
|
||||
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The
|
||||
`bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without
|
||||
that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still
|
||||
fails the boot, and the error names the teapots that did not connect.
|
||||
- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump,
|
||||
which alpha permits and a stable version would not.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Note the broken seam in the degrade plan**
|
||||
|
||||
Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a
|
||||
runner, not a container binding.
|
||||
|
||||
- [ ] **Step 4: The full gate**
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check
|
||||
npm run test:deno && npm run test:bun && npm run test:edge
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add README.md CHANGELOG.md docs/plans/
|
||||
git commit -m "docs(mesh): steps and routes are what a teapot exports"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Size
|
||||
|
||||
Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new
|
||||
subsystem, no new configuration, no background loop. The risk is not in the code but in the wire —
|
||||
both peers change at once, which alpha allows and which the runtime suites are there to prove.
|
||||
|
||||
## Branch
|
||||
|
||||
From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes.
|
||||
|
||||
```bash
|
||||
git fetch origin && git checkout -b feat/mesh-steps-only origin/develop
|
||||
```
|
||||
@@ -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' },
|
||||
},
|
||||
);
|
||||
+9
-6
@@ -31,8 +31,11 @@ class UserController {
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
|
||||
const logger: Plugin = (api) => {
|
||||
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
|
||||
const logger: Plugin = {
|
||||
name: 'step-logger',
|
||||
mount(api) {
|
||||
api.bus.on('request:step:enter', (p) => console.log(`-> ${p.name}`));
|
||||
},
|
||||
};
|
||||
|
||||
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
@@ -75,9 +78,9 @@ if (require.main === module) {
|
||||
|
||||
// ── Mesh Demo (teapot / teacup) ───────────────────────────────────────────
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class ConfigProvider {
|
||||
provide() {
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class ConfigStep {
|
||||
run() {
|
||||
return { config: { env: 'demo' } };
|
||||
}
|
||||
}
|
||||
@@ -98,7 +101,7 @@ class PingController {
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
|
||||
@Module({ mountpoint: '/mesh', steps: [ConfigStep, AuthStep], controllers: [PingController] })
|
||||
class TeapotModule {}
|
||||
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
|
||||
|
||||
Generated
+5
-5
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.8.0-beta.0",
|
||||
"version": "26.9.0-beta.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.8.0-beta.0",
|
||||
"version": "26.9.0-beta.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"reflect-metadata": "0.2.2"
|
||||
@@ -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": [
|
||||
{
|
||||
|
||||
+7
-6
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.8.0-beta.0",
|
||||
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.",
|
||||
"version": "26.9.0-beta.2",
|
||||
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
||||
"license": "MIT",
|
||||
"author": "green-tea contributors",
|
||||
"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,18 +91,18 @@
|
||||
"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",
|
||||
"bench": "tsx bench/run.ts",
|
||||
"bench:compare": "tsx bench/compare.ts",
|
||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env node
|
||||
// Prints one version's section of CHANGELOG.md, for a GitHub release body.
|
||||
//
|
||||
// Reads the current file rather than the tag's copy on purpose: the changelog is the record, so a
|
||||
// correction to an old entry should reach the release that describes it.
|
||||
//
|
||||
// Usage: node scripts/changelog-section.mjs <version> [tag]
|
||||
// The optional tag makes relative links absolute — a release body resolves them against the release
|
||||
// page, not the repository, and pinning to the tag keeps the link on the file as that version had it.
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const REPO = 'Expressive-Tea/green-tea';
|
||||
const [version, tag] = process.argv.slice(2);
|
||||
if (!version) {
|
||||
console.error('usage: changelog-section.mjs <version> [tag]');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const lines = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8').split('\n');
|
||||
const isHeading = (l) => l.startsWith('## [');
|
||||
// The `[label]: url` block at the bottom of the file belongs to no section. Without this the last
|
||||
// section swallows it, since nothing else comes after.
|
||||
const isLinkRef = (l) => /^\[[^\]]+\]:\s+\S/.test(l);
|
||||
|
||||
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
|
||||
if (start === -1) {
|
||||
console.error(`no section for ${version}. Headings in CHANGELOG.md:\n${lines.filter(isHeading).join('\n')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const rest = lines.slice(start + 1);
|
||||
const stop = rest.findIndex((l) => isHeading(l) || isLinkRef(l));
|
||||
const body = (stop === -1 ? rest : rest.slice(0, stop)).join('\n').trim();
|
||||
|
||||
const absolute = tag
|
||||
? body.replace(/\]\(\.\/([^)\s]+)\)/g, `](https://github.com/${REPO}/blob/${tag}/$1)`)
|
||||
: body;
|
||||
|
||||
console.log(absolute);
|
||||
+643
-84
File diff suppressed because it is too large.
Load diff
+83
-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,16 @@ 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>;
|
||||
/**
|
||||
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
|
||||
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
|
||||
*
|
||||
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
|
||||
* their server, which is why the option is declared once on `createApp` and works on all three.
|
||||
* Call it yourself only if you serve the app some other way.
|
||||
*/
|
||||
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
|
||||
/**
|
||||
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
|
||||
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
|
||||
@@ -48,6 +59,22 @@ export interface App {
|
||||
* shares this same memoized step — calling both never resolves the graph twice.
|
||||
*/
|
||||
ready(): Promise<void>;
|
||||
/**
|
||||
* Boots the providers now, instead of on the first request.
|
||||
*
|
||||
* The three serving helpers call it for you: `listen()` before it accepts a connection,
|
||||
* `serveDeno()` and `serveBun()` before they bind. Calling it by hand is for the paths that have
|
||||
* no startup of their own — `app.fetch` and `app.upgrade` driven by your own server, where a
|
||||
* provider that throws fails *every* request, answered by the runtime with a 500 that never
|
||||
* reaches `onError`, because the boot memo keeps the rejection. Calling this first turns that into
|
||||
* a startup failure, which is where a bad key or an unreachable database belongs.
|
||||
*
|
||||
* Idempotent, and shares its memo with `listen()` and `fetch()`: calling both boots once. Unlike
|
||||
* `ready()`, it does run provider factories.
|
||||
*
|
||||
* On workerd there is no startup outside a request, so calling it moves nothing.
|
||||
*/
|
||||
boot(): Promise<void>;
|
||||
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
|
||||
fetch(request: Request): Promise<Response>;
|
||||
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
|
||||
@@ -62,6 +89,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 +128,53 @@ 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. When the deadline
|
||||
* passes the teacup warns and starts anyway: every export is a step or a proxied route, so
|
||||
* nothing needed that link resolved by boot.
|
||||
*
|
||||
* Starting is not degrading, though. A teapot that never connected sent no manifest, so none of
|
||||
* its steps or routes are registered: its routes 404 rather than 503, and a local node that needs
|
||||
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
|
||||
* protocol mismatch — fails at once without spending the grace.
|
||||
*
|
||||
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
|
||||
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
|
||||
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
|
||||
*/
|
||||
bootTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
+58
-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,23 @@ 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.
|
||||
*
|
||||
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
|
||||
*/
|
||||
export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||
return Bun.serve({
|
||||
export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
|
||||
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
|
||||
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
|
||||
// failure rather than a 500 on every request.
|
||||
//
|
||||
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
|
||||
// the first request would fix the failure in place and the runtime would answer from it forever,
|
||||
// without ever reaching `onError`. This was documented as something the caller should remember to
|
||||
// do, which made the correct use of a core helper depend on reading a README.
|
||||
await app.boot();
|
||||
|
||||
const server = Bun.serve({
|
||||
...options,
|
||||
fetch(request, server) {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
@@ -95,4 +125,29 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
|
||||
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
|
||||
return Object.assign(server, {
|
||||
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
|
||||
// runtime's own signal API — and so the close it returns takes the handlers back off, which
|
||||
// Deno requires to exit at all.
|
||||
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.stop(false).then(() => app.close()),
|
||||
() => void server.stop(true),
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
|
||||
timeoutMs: ms,
|
||||
runtime: 'bun',
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
+149
-3
@@ -1,4 +1,28 @@
|
||||
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
|
||||
/**
|
||||
* Names of every lifecycle event the framework emits over the {@link Bus}.
|
||||
*
|
||||
* ### The request pair is a guarantee
|
||||
*
|
||||
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
|
||||
* consumer may open per-request state on the first and close it on the second without checking
|
||||
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
|
||||
* does.
|
||||
*
|
||||
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
|
||||
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
|
||||
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
|
||||
* every response shape so that the next one cannot break it quietly. The alternative — documenting
|
||||
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
|
||||
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
|
||||
* exactly when an operator is reading it.
|
||||
*
|
||||
* ### `request:end` is terminal and universal; the others are additional
|
||||
*
|
||||
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
|
||||
* the only one of these carrying the real status. **Count it, and nothing else.**
|
||||
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
|
||||
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
|
||||
*/
|
||||
export type LifecycleEvent =
|
||||
| 'boot:provider:start'
|
||||
| 'boot:provider:ok'
|
||||
@@ -6,20 +30,127 @@ export type LifecycleEvent =
|
||||
| 'request:step:enter'
|
||||
| 'request:step:leave'
|
||||
| 'request:step:error'
|
||||
// A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately
|
||||
// *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its
|
||||
// connection may live for hours, so `request:end` fires at the handler's return and these three
|
||||
// describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is
|
||||
// what lets a consumer join the two rather than watch them as unrelated streams of events.
|
||||
| 'stream:open'
|
||||
| 'stream:close'
|
||||
| 'stream:error'
|
||||
| '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'
|
||||
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
|
||||
// request arrived, not that it routed.
|
||||
| 'request:start'
|
||||
| 'request:end'
|
||||
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
|
||||
// also a throw, which is a thing a status alone cannot express.
|
||||
| 'request:failed'
|
||||
| 'route:matched'
|
||||
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
|
||||
// misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
|
||||
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
|
||||
// no route either, and answers 200. Read the status from the `request:end` that follows.
|
||||
| 'route:unmatched';
|
||||
|
||||
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */
|
||||
/**
|
||||
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
|
||||
* the fields that say which request it belongs to.
|
||||
*
|
||||
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
|
||||
* name, and requiring a shape they cannot fill would only mean inventing values for it.
|
||||
*
|
||||
* ### One failed request produces three events
|
||||
*
|
||||
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
|
||||
* All three carry the same `requestId`, and the first implementation anyone writes counts the
|
||||
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
|
||||
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
|
||||
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
|
||||
* outcome.
|
||||
*
|
||||
* The division of labour, which is the thing to build against:
|
||||
*
|
||||
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
|
||||
* received. This is the request counter and the latency histogram.
|
||||
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
|
||||
* rendered `422` is also a throw. This is a separate error counter, not a second request
|
||||
* counter.
|
||||
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
|
||||
*
|
||||
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
|
||||
* the outcome from `request:end` and only the message from `request:failed`.
|
||||
*/
|
||||
export interface EventPayload {
|
||||
/**
|
||||
* What the event is about, for a human reading a log line.
|
||||
*
|
||||
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
|
||||
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
|
||||
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
|
||||
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
|
||||
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
|
||||
* which is bounded by construction.
|
||||
*/
|
||||
name: string;
|
||||
scope?: string;
|
||||
error?: unknown;
|
||||
durationMs?: number;
|
||||
/** Correlates every event of one request. Adopted from `x-request-id` when a gateway sent one. */
|
||||
requestId?: string;
|
||||
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
|
||||
traceId?: string;
|
||||
/**
|
||||
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
|
||||
*
|
||||
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
|
||||
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
|
||||
* that follows it: a single series for every path that was never a route, instead of a fallback
|
||||
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
|
||||
* starts with `/`.
|
||||
*/
|
||||
route?: string;
|
||||
method?: string;
|
||||
transport?: string;
|
||||
/**
|
||||
* The status the client received. Present on `request:end` always, and on `request:failed`
|
||||
* except when a custom `onError` renderer threw while producing it — the one case where the
|
||||
* framework does not know what was sent, and will not guess.
|
||||
*/
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of {@link EventPayload} that identifies a request, spread into each of its events.
|
||||
*
|
||||
* `route` carries the matched pattern rather than the URL that arrived, and that is load-bearing
|
||||
* rather than cosmetic: a metrics consumer that labels a counter with a concrete path gets one
|
||||
* label per distinct URL, and unbounded label cardinality takes down the metrics backend rather
|
||||
* than the application. Handing anyone that shape by default would be the framework's fault.
|
||||
*/
|
||||
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
|
||||
|
||||
/**
|
||||
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
|
||||
*
|
||||
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
|
||||
* and the framework's own events would stop being trustworthy the moment a node could forge one.
|
||||
* Plugins get exactly this same narrowing.
|
||||
*
|
||||
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
|
||||
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
|
||||
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
|
||||
* token exists to point at rather than replace.
|
||||
*/
|
||||
export interface Events {
|
||||
on: Bus['on'];
|
||||
}
|
||||
|
||||
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||
@@ -34,6 +165,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) ?? []) {
|
||||
|
||||
+74
-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,29 @@ 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.
|
||||
*
|
||||
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
|
||||
*/
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||
return Deno.serve(options ?? {}, (request, info) => {
|
||||
export async function serveDeno(app: App, options?: DenoServeOptions): Promise<DenoServer> {
|
||||
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
|
||||
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
|
||||
// failure rather than a 500 on every request.
|
||||
//
|
||||
// Leaving it to `app.fetch` is not the lazier equivalent. The boot memo keeps a *rejection*, so
|
||||
// the first request would fix the failure in place and the runtime would answer from it forever,
|
||||
// without ever reaching `onError`. This was documented as something the caller should remember to
|
||||
// do, which made the correct use of a core helper depend on reading a README.
|
||||
await app.boot();
|
||||
|
||||
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to
|
||||
// own one to offer a deadline at all. A caller-supplied signal still works and still aborts the
|
||||
// server — it is chained into ours rather than replaced, so neither party loses its control.
|
||||
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 +84,38 @@ 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, {
|
||||
// Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
|
||||
// runtime's own signal API — and so the close it returns takes the handlers back off, which
|
||||
// Deno requires to exit at all.
|
||||
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.shutdown().then(() => app.close()),
|
||||
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
|
||||
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
|
||||
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
||||
// surfaces uncaught — not catchable at this call site, and fatal under `deno test`.
|
||||
// Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot
|
||||
// escalate from graceful to forced the way Node's closeAllConnections() and Bun's
|
||||
// stop(true) can, and the deadline here bounds how long `close()` waits, not when the
|
||||
// connections die. Exiting the process after `close()` resolves is what ends them.
|
||||
() => {},
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(
|
||||
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
|
||||
'a server that is already draining, so remaining connections end when the process does.',
|
||||
{ timeoutMs: ms, runtime: 'deno' },
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
+100
-2
@@ -11,10 +11,106 @@ export interface StreamEncoder {
|
||||
|
||||
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
||||
|
||||
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
|
||||
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
|
||||
// being recognised across them would silently degrade back to an id-less `data:` frame.
|
||||
const SSE_EVENT = Symbol.for('green-tea.sse-event');
|
||||
|
||||
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
|
||||
export interface SseFields {
|
||||
/**
|
||||
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
|
||||
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
|
||||
* `@header('last-event-id')` and resume from there.
|
||||
*/
|
||||
id?: string;
|
||||
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
|
||||
event?: string;
|
||||
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
|
||||
retry?: number;
|
||||
}
|
||||
|
||||
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
|
||||
export interface SseEvent<T = unknown> extends SseFields {
|
||||
readonly [SSE_EVENT]: true;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/** Type guard: true when a stream item was built by {@link sse}. */
|
||||
export function isSseEvent(item: unknown): item is SseEvent {
|
||||
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
|
||||
}
|
||||
|
||||
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
|
||||
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
|
||||
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
|
||||
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
|
||||
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
|
||||
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
|
||||
function assertFieldSafe(field: string, value: string): void {
|
||||
if (!/[\r\n\0]/.test(value)) return;
|
||||
|
||||
throw new Error(
|
||||
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
|
||||
'one would end the field and let the rest of the value be read as further SSE fields. ' +
|
||||
`Received ${JSON.stringify(value)}.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
|
||||
* instead of a bare `data:` frame.
|
||||
*
|
||||
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
|
||||
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
|
||||
* marker in both directions and stores nothing — a source that can resume, resumes; one that
|
||||
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
|
||||
*
|
||||
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
|
||||
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* @Sse('/feed')
|
||||
* feed(@header('last-event-id') from: string) {
|
||||
* return (async function* () {
|
||||
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
|
||||
* })();
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
|
||||
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
|
||||
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
|
||||
|
||||
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
|
||||
// reconnection delay at the default rather than at the value the app asked for.
|
||||
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
|
||||
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
|
||||
}
|
||||
|
||||
return { [SSE_EVENT]: true, data, ...fields };
|
||||
}
|
||||
|
||||
/**
|
||||
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
|
||||
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
|
||||
*/
|
||||
function sseFrame(item: unknown): string {
|
||||
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
|
||||
let frame = '';
|
||||
|
||||
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
|
||||
if (item.event !== undefined) frame += `event: ${item.event}\n`;
|
||||
if (item.id !== undefined) frame += `id: ${item.id}\n`;
|
||||
|
||||
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
|
||||
}
|
||||
|
||||
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
|
||||
export const sseEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
||||
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
|
||||
encode: sseFrame,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
||||
ping: () => ': ping\n\n',
|
||||
};
|
||||
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
|
||||
/** Newline-delimited JSON encoder: one JSON object per line. */
|
||||
export const ndjsonEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'application/x-ndjson' },
|
||||
encode: (item) => `${JSON.stringify(item)}\n`,
|
||||
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
|
||||
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
|
||||
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
||||
};
|
||||
+31
-2
@@ -43,7 +43,7 @@ export interface GraphNode {
|
||||
}
|
||||
|
||||
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
||||
|
||||
@@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
for (const node of nodes) {
|
||||
for (const key of node.needs) {
|
||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}`);
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
return ordered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups an already topo-sorted list into dependency levels: nothing in a level can constrain
|
||||
* anything else in it, and a level depends only on the levels before it — so a level can run
|
||||
* concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain
|
||||
* nothing and are ignored.
|
||||
*/
|
||||
export function topoLevels(ordered: GraphNode[]): GraphNode[][] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
||||
const depthOf = new Map<GraphNode, number>();
|
||||
const levels: GraphNode[][] = [];
|
||||
|
||||
// One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's
|
||||
// needs already has its depth by the time the node is reached.
|
||||
for (const node of ordered) {
|
||||
let depth = 0;
|
||||
|
||||
for (const key of node.needs) {
|
||||
const producer = producedBy.get(key);
|
||||
if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1);
|
||||
}
|
||||
|
||||
depthOf.set(node, depth);
|
||||
(levels[depth] ??= []).push(node);
|
||||
}
|
||||
|
||||
return levels;
|
||||
}
|
||||
|
||||
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
|
||||
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
|
||||
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
|
||||
// the caller as a {@link BodyReader}.
|
||||
import { HttpError, isHttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import type { MatchedRoute, HttpOptions } from './types';
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
export interface BodyFailure {
|
||||
fail: { status: number; headers: Record<string, string>; body: string };
|
||||
}
|
||||
|
||||
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
|
||||
export type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
|
||||
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
return value instanceof Promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the raw request body, enforcing `limit`.
|
||||
*
|
||||
* The adapter owns this and nothing else about the body, because enforcement is the one place the
|
||||
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
|
||||
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
|
||||
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
|
||||
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
|
||||
* without bound first.
|
||||
*
|
||||
* The failure branch is opaque on purpose: Node answers an over-limit request with
|
||||
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
|
||||
* That header means nothing on the fetch side, and is a forbidden response header on some
|
||||
* runtimes, so the adapter that needs it is the one that attaches it.
|
||||
*
|
||||
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
|
||||
* reader can be built **once per server** instead of once per request: a closure capturing the
|
||||
* request measured at 250 ns per request together with the error-context object it captured —
|
||||
* more than the duplicate route resolution this whole indirection removes.
|
||||
*/
|
||||
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
export async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
|
||||
*
|
||||
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
|
||||
* character for character, because each adapter had to route the request itself in order to know
|
||||
* whether to read a body — and so ended up owning every policy that depends on the matched route.
|
||||
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
|
||||
* runtimes quietly disagree about limits.
|
||||
*/
|
||||
export function acquireBody(
|
||||
read: BodyReader,
|
||||
source: unknown,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const acquired = read(source, limit);
|
||||
|
||||
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
|
||||
// this whole path without a single promise, and an `async` wrapper here would allocate one
|
||||
// regardless. Same reason `handle()` is not async.
|
||||
return isPromise(acquired)
|
||||
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
|
||||
: parseAcquired(acquired, matched, opts, req);
|
||||
}
|
||||
|
||||
function parseAcquired(
|
||||
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
if ('fail' in acquired) return acquired;
|
||||
|
||||
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
|
||||
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
|
||||
// off the promise path entirely.
|
||||
if (acquired.bytes === undefined) return { body: undefined };
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
|
||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
||||
'error' in parsed
|
||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
|
||||
: { body: parsed.body },
|
||||
);
|
||||
}
|
||||
+286
-12
@@ -5,23 +5,111 @@ 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';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
|
||||
/**
|
||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
||||
*
|
||||
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
|
||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
||||
*
|
||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
||||
* why that job is pinned to the floor rather than to the current release.
|
||||
*
|
||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
|
||||
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
|
||||
* every distribution of this package and not just the bundled ones.
|
||||
*/
|
||||
const randomUUID: () => string = (() => {
|
||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||
|
||||
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
|
||||
})();
|
||||
|
||||
/**
|
||||
* A runtime-neutral inbound request.
|
||||
*
|
||||
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
|
||||
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
|
||||
* body, it first had to route the request itself — a body is only read for a request that reaches
|
||||
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
|
||||
* a four-route app walked its table two and a half times per request. Handing over the *ability*
|
||||
* to read instead of the result moves that decision here, where the route is known anyway.
|
||||
*/
|
||||
export interface NeutralRequest {
|
||||
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 {
|
||||
@@ -45,7 +133,7 @@ export function computeInjected(
|
||||
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
|
||||
): Record<string, string> {
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
|
||||
return injected;
|
||||
}
|
||||
|
||||
@@ -56,7 +144,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, opts?.logger);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
@@ -104,17 +192,151 @@ async function unmatchedOutcome(
|
||||
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||
}
|
||||
|
||||
/**
|
||||
* The `route` reported for a request no route matched.
|
||||
*
|
||||
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
|
||||
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
|
||||
* single series where the concrete path would produce one per distinct URL.
|
||||
*/
|
||||
export const UNMATCHED_ROUTE = '<unmatched>';
|
||||
|
||||
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
||||
interface Trace {
|
||||
route?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
injected?: Record<string, string>,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const injected = computeInjected(opts, req);
|
||||
const bus = opts?.bus;
|
||||
|
||||
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
|
||||
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
|
||||
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
|
||||
if (
|
||||
bus === undefined ||
|
||||
!(
|
||||
bus.hasListeners('request:start') ||
|
||||
bus.hasListeners('request:end') ||
|
||||
bus.hasListeners('route:matched') ||
|
||||
bus.hasListeners('route:unmatched')
|
||||
)
|
||||
) {
|
||||
return dispatch(routes, opts, req, undefined, undefined, injected);
|
||||
}
|
||||
|
||||
return observedDispatch(routes, opts, req, bus, injected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether anything is listening for the request pair — the one check both adapters need before
|
||||
* paying for a `performance.now()` on a request they are about to refuse.
|
||||
*/
|
||||
export function watchingRequests(bus: Bus | undefined): bus is Bus {
|
||||
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits the lifecycle pair for a request shed before routing.
|
||||
*
|
||||
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
|
||||
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
|
||||
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
|
||||
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
|
||||
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
|
||||
* time a server sheds — under load, which is when it can least afford them.
|
||||
*
|
||||
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
|
||||
* costs nothing for a subscriber of one.
|
||||
*/
|
||||
export function emitShedPair(
|
||||
bus: Bus,
|
||||
req: { method: string; url: string; requestId?: string; traceId?: string },
|
||||
startedAt: number,
|
||||
): void {
|
||||
const name = `${req.method} ${req.url}`;
|
||||
|
||||
if (bus.hasListeners('request:start'))
|
||||
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
|
||||
|
||||
if (bus.hasListeners('request:end'))
|
||||
bus.emit('request:end', {
|
||||
name,
|
||||
method: req.method,
|
||||
status: 503,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
async function observedDispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus,
|
||||
injected?: Record<string, string>,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const watchingEnd = bus.hasListeners('request:end');
|
||||
const startedAt = watchingEnd ? performance.now() : 0;
|
||||
const trace: Trace = {};
|
||||
|
||||
if (bus.hasListeners('request:start'))
|
||||
bus.emit('request:start', {
|
||||
name: `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
const result = await dispatch(routes, opts, req, bus, trace, injected);
|
||||
|
||||
if (watchingEnd) {
|
||||
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
||||
// by the time anything is piped.
|
||||
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
|
||||
bus.emit('request:end', {
|
||||
name: trace.route ?? `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
route: trace.route,
|
||||
status,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function dispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus | undefined,
|
||||
trace: Trace | undefined,
|
||||
precomputed?: Record<string, string>,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
// Both adapters compute this before routing, because a response written above `handle()` — a
|
||||
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
|
||||
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
|
||||
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
|
||||
const injected = precomputed ?? computeInjected(opts, req);
|
||||
let path: string;
|
||||
|
||||
try {
|
||||
@@ -124,12 +346,53 @@ export async function handle(
|
||||
}
|
||||
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
|
||||
}
|
||||
|
||||
const matched = resolveRoute(routes, req.method, path);
|
||||
|
||||
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
if (!matched) {
|
||||
// `name` here is the path that arrived, and it is the one value in this payload that must never
|
||||
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
|
||||
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
|
||||
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
|
||||
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
|
||||
// and some of them to get it wrong.
|
||||
if (trace) trace.route = UNMATCHED_ROUTE;
|
||||
|
||||
if (bus?.hasListeners('route:unmatched'))
|
||||
bus.emit('route:unmatched', {
|
||||
name: `${req.method} ${path}`,
|
||||
route: UNMATCHED_ROUTE,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
}
|
||||
|
||||
if (trace) trace.route = matched.def.pattern;
|
||||
|
||||
if (bus?.hasListeners('route:matched'))
|
||||
bus.emit('route:matched', {
|
||||
name: matched.def.pattern,
|
||||
route: matched.def.pattern,
|
||||
method: req.method,
|
||||
transport: matched.def.transport,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
|
||||
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
|
||||
// object per request bought nothing.
|
||||
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
|
||||
|
||||
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
|
||||
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
|
||||
// caller merges `injected` into it exactly as it does for every other outcome.
|
||||
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
|
||||
|
||||
let result: PipelineResult;
|
||||
|
||||
@@ -140,17 +403,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, opts?.logger);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Per-server/adapter request budget.
|
||||
*
|
||||
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
|
||||
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
|
||||
*/
|
||||
export interface RequestGate {
|
||||
/**
|
||||
* Whether a budget is actually configured.
|
||||
*
|
||||
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
|
||||
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
|
||||
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
|
||||
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
|
||||
* per-request cost behind it should be skipped entirely.
|
||||
*/
|
||||
limited: boolean;
|
||||
acquire(): boolean;
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
|
||||
export function createRequestGate(limit: number | undefined): RequestGate {
|
||||
let active = 0;
|
||||
const limited = limit !== undefined && limit > 0;
|
||||
|
||||
return {
|
||||
limited,
|
||||
|
||||
acquire(): boolean {
|
||||
if (limit === undefined || limit <= 0) return true;
|
||||
if (active >= limit) return false;
|
||||
|
||||
active++;
|
||||
return true;
|
||||
},
|
||||
|
||||
release(): void {
|
||||
if (limit === undefined || limit <= 0) return;
|
||||
if (active > 0) active--;
|
||||
},
|
||||
};
|
||||
}
|
||||
+175
-28
@@ -163,27 +163,117 @@ export function compilePattern(pattern: string): CompiledPattern {
|
||||
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;
|
||||
}
|
||||
|
||||
function decodeSegment(value: string): string {
|
||||
return decodeURIComponent(value);
|
||||
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
|
||||
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
|
||||
// runs for every param segment of every candidate route the scan reaches.
|
||||
return value.includes('%') ? decodeURIComponent(value) : value;
|
||||
}
|
||||
|
||||
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
|
||||
const pathSegs = path.split('/').filter(Boolean);
|
||||
/**
|
||||
* Splits a request path into its non-empty segments.
|
||||
*
|
||||
* Called once per request by the scanning functions below, not once per candidate route. It used to
|
||||
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
|
||||
* registered route on every request, always producing the same array.
|
||||
*/
|
||||
function splitPath(path: string): string[] {
|
||||
return path.split('/').filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches one compiled pattern against a request's segments.
|
||||
*
|
||||
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
|
||||
* several routes decoded the same string once per route. Position is all decoding depends on, so one
|
||||
* array shared across the scan is the same answer for less work.
|
||||
*/
|
||||
function matchCompiled(
|
||||
compiled: CompiledPattern,
|
||||
pathSegs: string[],
|
||||
decoded?: Array<string | undefined>,
|
||||
): Record<string, string> | undefined {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let index = 0; index < compiled.segments.length; index++) {
|
||||
@@ -201,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, path: string): Record<string,
|
||||
continue;
|
||||
}
|
||||
|
||||
const value = decodeSegment(pathSegs[index]);
|
||||
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
|
||||
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||
params[segment.name] = value;
|
||||
}
|
||||
@@ -211,13 +301,18 @@ 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. */
|
||||
function moreSpecific(a: string, b: string): number {
|
||||
const scoreA = compilePattern(a);
|
||||
const scoreB = compilePattern(b);
|
||||
/**
|
||||
* Orders patterns by exactness, then static/constrained/plain segment specificity.
|
||||
*
|
||||
* Takes compiled patterns rather than their source strings: it used to re-derive both through
|
||||
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
|
||||
*/
|
||||
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
||||
const scoreA = a;
|
||||
const scoreB = b;
|
||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||
|
||||
@@ -230,23 +325,65 @@ function moreSpecific(a: string, b: string): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
let best: MatchedRoute | undefined;
|
||||
let bestPattern = '';
|
||||
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
|
||||
interface IndexedRoute {
|
||||
def: RouteDef;
|
||||
compiled: CompiledPattern;
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.method !== method) continue;
|
||||
const params = matchPattern(route.pattern, path);
|
||||
if (!params) continue;
|
||||
/**
|
||||
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
|
||||
* they were built from.
|
||||
*
|
||||
* A server hands the same array to every request, so this is built once and collected with the
|
||||
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
|
||||
* different array and gets its own index, so nothing has to remember to invalidate anything.
|
||||
*/
|
||||
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
|
||||
|
||||
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||
best = { params, def: route };
|
||||
bestPattern = route.pattern;
|
||||
}
|
||||
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
|
||||
const cached = routeIndexCache.get(routes);
|
||||
if (cached) return cached;
|
||||
|
||||
const byMethod = new Map<string, IndexedRoute[]>();
|
||||
|
||||
for (const def of routes) {
|
||||
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
|
||||
const bucket = byMethod.get(def.method);
|
||||
if (bucket) bucket.push(entry);
|
||||
else byMethod.set(def.method, [entry]);
|
||||
}
|
||||
|
||||
return best;
|
||||
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
|
||||
// keep registration order — which is exactly what the old scan did by refusing to replace its
|
||||
// best on a tie.
|
||||
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
||||
|
||||
routeIndexCache.set(routes, byMethod);
|
||||
return byMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the most specific route matching both method and path; ties keep registration order.
|
||||
*
|
||||
* The ranking is settled when the table is built, not per request: the answer cannot change between
|
||||
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
|
||||
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
|
||||
* table. What is left here is a walk that stops at the first match.
|
||||
*/
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
const candidates = routeIndex(routes).get(method);
|
||||
if (!candidates) return undefined;
|
||||
|
||||
const pathSegs = splitPath(path);
|
||||
const decoded: Array<string | undefined> = new Array(pathSegs.length);
|
||||
|
||||
for (const { def, compiled } of candidates) {
|
||||
const params = matchCompiled(compiled, pathSegs, decoded);
|
||||
if (params) return { params, def };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||
@@ -271,10 +408,11 @@ const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'
|
||||
|
||||
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||
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 +429,15 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
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;
|
||||
|
||||
+131
-125
@@ -1,29 +1,32 @@
|
||||
import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { createRequestGate } from './request-gate';
|
||||
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,
|
||||
computeInjected,
|
||||
emitShedPair,
|
||||
watchingRequests,
|
||||
type HandleResult,
|
||||
type Preflight,
|
||||
} from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
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,21 +47,34 @@ 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().
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodeHttp = require('http') as typeof import('http');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodeHttps = require('https') as typeof import('https');
|
||||
const nodeHttp = nodeRequire<typeof import('http')>('http');
|
||||
const nodeHttps = nodeRequire<typeof import('https')>('https');
|
||||
|
||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||
const server: http.Server = (opts?.tls
|
||||
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: nodeHttp.createServer(handler)) as unknown as http.Server;
|
||||
const maxConnections = opts?.limits?.maxConnections ?? 1000;
|
||||
|
||||
if (maxConnections > 0) {
|
||||
server.maxConnections = maxConnections;
|
||||
let lastDropWarn = 0;
|
||||
server.on('drop', ({ remoteAddress, remotePort }) => {
|
||||
const now = Date.now();
|
||||
if (now - lastDropWarn < 60_000) return;
|
||||
lastDropWarn = now;
|
||||
opts?.logger?.warn(
|
||||
`maxConnections (${maxConnections}) reached \u2014 dropped connection from ${remoteAddress ?? 'unknown'}:${remotePort ?? 'unknown'}`,
|
||||
{ maxConnections, remoteAddress, remotePort },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
@@ -68,61 +84,92 @@ 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);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
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);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(req.headers);
|
||||
// One computation for the whole request: this object is patched into every response below, and
|
||||
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
|
||||
// `cors.origins` may be a predicate with a network call in it.
|
||||
const injected = computeInjected(opts, { secure, headers: req.headers });
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
|
||||
// by reference at writeHead time, so keys added here still land on every response.
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
|
||||
// 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>;
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
const watching = watchingRequests(bus);
|
||||
const startedAt = watching ? performance.now() : 0;
|
||||
|
||||
try {
|
||||
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
|
||||
} catch {
|
||||
matched = undefined; // handle() owns the standard 400 envelope and injected headers
|
||||
}
|
||||
if (!gate.acquire()) {
|
||||
if (watching)
|
||||
emitShedPair(
|
||||
bus,
|
||||
{
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
requestId: correlation.requestId,
|
||||
traceId: correlation.traceId,
|
||||
},
|
||||
startedAt,
|
||||
);
|
||||
|
||||
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);
|
||||
res.writeHead(503, {
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
connection: 'close',
|
||||
});
|
||||
res.end(JSON.stringify({ error: 'Service Unavailable' }));
|
||||
return;
|
||||
}
|
||||
|
||||
body = acquired.body;
|
||||
}
|
||||
// Both the flag and the listener are skipped when no budget is configured, which is most
|
||||
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
|
||||
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
|
||||
// with nothing on the other side of it.
|
||||
if (gate.limited) {
|
||||
acquired = true;
|
||||
res.once('close', () => {
|
||||
if (!acquired) return;
|
||||
acquired = false;
|
||||
gate.release();
|
||||
});
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
method,
|
||||
url,
|
||||
headers: req.headers,
|
||||
body,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
result = await handle(
|
||||
routes,
|
||||
opts,
|
||||
{
|
||||
...correlation,
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
},
|
||||
injected,
|
||||
);
|
||||
} finally {
|
||||
if (acquired) {
|
||||
acquired = false;
|
||||
gate.release();
|
||||
}
|
||||
}
|
||||
|
||||
if ('preflight' in result) {
|
||||
res.writeHead(204, result.preflight);
|
||||
@@ -131,7 +178,15 @@ 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,
|
||||
correlation,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -140,34 +195,27 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
|
||||
async function acquireBody(
|
||||
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, opts?.logger);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,45 +232,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);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
|
||||
|
||||
import type { Logger } from '../logger';
|
||||
|
||||
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
|
||||
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
|
||||
|
||||
type Signal = (typeof SIGNALS)[number];
|
||||
|
||||
interface SignalApi {
|
||||
runtime: string;
|
||||
on(signal: Signal, handler: () => void): void;
|
||||
off(signal: Signal, handler: () => void): void;
|
||||
exit(code: number): void;
|
||||
}
|
||||
|
||||
interface DenoSignals {
|
||||
addSignalListener(signal: Signal, handler: () => void): void;
|
||||
removeSignalListener(signal: Signal, handler: () => void): void;
|
||||
exit(code: number): void;
|
||||
}
|
||||
|
||||
interface ProcessSignals {
|
||||
on(signal: Signal, handler: () => void): unknown;
|
||||
off?(signal: Signal, handler: () => void): unknown;
|
||||
removeListener?(signal: Signal, handler: () => void): unknown;
|
||||
exit(code: number): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
|
||||
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
|
||||
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
|
||||
* listener holds the process open until it is removed. Node and Bun share `process`.
|
||||
*/
|
||||
function signalApi(): SignalApi | undefined {
|
||||
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
|
||||
|
||||
if (typeof deno?.addSignalListener === 'function')
|
||||
return {
|
||||
runtime: 'deno',
|
||||
on: (signal, handler) => deno.addSignalListener(signal, handler),
|
||||
off: (signal, handler) => deno.removeSignalListener(signal, handler),
|
||||
exit: (code) => deno.exit(code),
|
||||
};
|
||||
|
||||
const proc = (globalThis as { process?: ProcessSignals }).process;
|
||||
|
||||
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
|
||||
const remove = proc.off ?? proc.removeListener;
|
||||
|
||||
return {
|
||||
runtime: 'node',
|
||||
on: (signal, handler) => void proc.on(signal, handler),
|
||||
off: (signal, handler) => void remove?.call(proc, signal, handler),
|
||||
exit: (code) => proc.exit(code),
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
|
||||
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
|
||||
* the process from exiting on its own.
|
||||
*
|
||||
* The close is expected to unregister first thing, which leaves a **second signal falling through
|
||||
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
|
||||
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
|
||||
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
|
||||
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
|
||||
*
|
||||
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
|
||||
* not a clean one and an orchestrator should be told.
|
||||
*/
|
||||
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
|
||||
const api = signalApi();
|
||||
|
||||
if (!api) {
|
||||
logger.warn(
|
||||
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
|
||||
);
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const registered: Array<[Signal, () => void]> = [];
|
||||
|
||||
const remove = (): void => {
|
||||
while (registered.length) {
|
||||
const [signal, handler] = registered.pop()!;
|
||||
api.off(signal, handler);
|
||||
}
|
||||
};
|
||||
|
||||
for (const signal of SIGNALS) {
|
||||
const handler = (): void => {
|
||||
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
|
||||
void close().then(
|
||||
() => api.exit(0),
|
||||
(error: unknown) => {
|
||||
logger.error(`shutdown failed after ${signal}`, {
|
||||
signal,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
api.exit(1);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
api.on(signal, handler);
|
||||
registered.push([signal, handler]);
|
||||
} catch (error) {
|
||||
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
|
||||
// platform does have beats refusing to start over the one it does not.
|
||||
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
|
||||
signal,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return remove;
|
||||
}
|
||||
+10
-4
@@ -2,7 +2,7 @@ import type http from 'http';
|
||||
import { once } from 'events';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { Bus } from '../bus';
|
||||
import type { Bus, Correlation } from '../bus';
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
@@ -35,10 +35,16 @@ export async function pipeStream(
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
streams?: Set<() => void>,
|
||||
correlation: Correlation = {},
|
||||
): Promise<void> {
|
||||
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
|
||||
// is always the route pattern, never the concrete path the request events can carry — but a
|
||||
// consumer following the documented contract labels on `route` and would otherwise find it
|
||||
// absent on the longest-lived thing the server does. See `EventPayload.name`.
|
||||
const trace = { name, route: name, ...correlation };
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||
bus?.emit('stream:open', { name });
|
||||
bus?.emit('stream:open', trace);
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
@@ -76,13 +82,13 @@ export async function pipeStream(
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
bus?.emit('stream:error', { ...trace, error: err });
|
||||
const frame = encoder.encodeError(err);
|
||||
if (frame && !res.writableEnded) res.write(frame);
|
||||
} finally {
|
||||
if (ping) clearInterval(ping);
|
||||
streams?.delete(closer);
|
||||
if (!res.writableEnded && !res.destroyed) res.end();
|
||||
bus?.emit('stream:close', { name });
|
||||
bus?.emit('stream:close', trace);
|
||||
}
|
||||
}
|
||||
+17
-1
@@ -4,10 +4,14 @@ 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';
|
||||
import type { Logger } from '../logger';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
/** Per-request and per-server resource ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
||||
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
@@ -16,6 +20,14 @@ 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;
|
||||
/** Where this server writes diagnostics. Optional because `createHttpServer` takes no options at all in tests. */
|
||||
logger?: Logger;
|
||||
limits?: RequestLimits;
|
||||
streams?: Set<() => void>;
|
||||
tls?: TlsOptions;
|
||||
@@ -37,6 +49,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. */
|
||||
|
||||
+206
-102
@@ -1,34 +1,85 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, type HandleResult } from './core';
|
||||
import type { Bus, Correlation } from '../bus';
|
||||
import { createRequestGate } from './request-gate';
|
||||
import {
|
||||
handle,
|
||||
computeInjected,
|
||||
correlateRequest,
|
||||
emitShedPair,
|
||||
watchingRequests,
|
||||
type HandleResult,
|
||||
type Preflight,
|
||||
} from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { 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> {
|
||||
/**
|
||||
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
||||
* cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the
|
||||
* lifecycle of a stream must not depend on which adapter is serving it.
|
||||
*/
|
||||
export function asReadableStream(
|
||||
source: AsyncIterable<unknown>,
|
||||
encoder: StreamEncoder,
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
correlation: Correlation = {},
|
||||
): ReadableStream<Uint8Array> {
|
||||
const iterator = source[Symbol.asyncIterator]();
|
||||
const te = new TextEncoder();
|
||||
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
|
||||
// says label on `route`, so both are carried.
|
||||
const trace = { name, route: name, ...correlation };
|
||||
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
|
||||
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
|
||||
// its own path — so the close is latched rather than emitted from each of the three exits.
|
||||
let closed = false;
|
||||
|
||||
const close = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
bus?.emit('stream:close', trace);
|
||||
};
|
||||
|
||||
return new ReadableStream<Uint8Array>({
|
||||
start() {
|
||||
bus?.emit('stream:open', trace);
|
||||
},
|
||||
async pull(controller) {
|
||||
try {
|
||||
const { value, done } = await iterator.next();
|
||||
|
||||
if (done) {
|
||||
close();
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const encoded = encoder.encode(value);
|
||||
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
||||
controller.enqueue(bytes);
|
||||
controller.enqueue(frame(encoder.encode(value)));
|
||||
} catch (err) {
|
||||
controller.error(err);
|
||||
bus?.emit('stream:error', { ...trace, error: err });
|
||||
const errorFrame = encoder.encodeError(err);
|
||||
close();
|
||||
|
||||
// Framed and closed cleanly, which is what the Node adapter does and the better answer for
|
||||
// the client: an SSE consumer that received an `error` event knows what happened, where a
|
||||
// transport-level failure is indistinguishable from the connection simply dropping.
|
||||
// `controller.error` is kept for the encoder that has no error frame to offer, because
|
||||
// then breaking the stream is the only signal left.
|
||||
if (errorFrame === null) {
|
||||
controller.error(err);
|
||||
return;
|
||||
}
|
||||
|
||||
controller.enqueue(frame(errorFrame));
|
||||
controller.close();
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
close();
|
||||
await iterator.return?.();
|
||||
},
|
||||
});
|
||||
@@ -44,130 +95,183 @@ function headersToRecord(headers: Headers): Record<string, string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
|
||||
* 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, opts?.logger) };
|
||||
}
|
||||
|
||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
|
||||
* 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. */
|
||||
function outcomeToResponse(result: HandleResult): Response {
|
||||
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
|
||||
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||
const body = asReadableStream(
|
||||
result.outcome.stream,
|
||||
result.outcome.encoder,
|
||||
bus,
|
||||
result.outcome.route,
|
||||
correlation,
|
||||
);
|
||||
return new Response(body, { headers });
|
||||
}
|
||||
|
||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : 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);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
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>;
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(headers);
|
||||
const secure = url.protocol === 'https:';
|
||||
// Computed up-front from the same inputs `handle()` uses, so a preflight — the one response
|
||||
// this adapter builds itself — carries the same security/CORS headers every other one does.
|
||||
const injected = computeInjected(opts, { secure, headers });
|
||||
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
const watching = watchingRequests(opts?.bus);
|
||||
const startedAt = watching ? performance.now() : 0;
|
||||
|
||||
try {
|
||||
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
|
||||
} catch {
|
||||
matched = undefined; // handle() renders the shared 400 response without reading a body
|
||||
if (!gate.acquire()) {
|
||||
if (watching)
|
||||
emitShedPair(
|
||||
opts!.bus!,
|
||||
{
|
||||
method: request.method,
|
||||
url: path,
|
||||
requestId: correlation.requestId,
|
||||
traceId: correlation.traceId,
|
||||
},
|
||||
startedAt,
|
||||
);
|
||||
|
||||
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
||||
status: 503,
|
||||
headers: mergeInjectedHeaders(
|
||||
{
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
},
|
||||
injected,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
acquired = gate.limited;
|
||||
|
||||
result = await handle(
|
||||
routes,
|
||||
opts,
|
||||
{
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
readBody,
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
|
||||
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
|
||||
// is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
},
|
||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||
// one call per request.
|
||||
injected,
|
||||
);
|
||||
} finally {
|
||||
// Release when routing/handling finishes, not when a returned stream finishes.
|
||||
// Long-lived streams therefore do not permanently consume the request budget.
|
||||
if (acquired) gate.release();
|
||||
}
|
||||
|
||||
const secure = url.protocol === 'https:';
|
||||
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
||||
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
||||
// would have installed before body acquisition.
|
||||
const injected = computeInjected(opts, { secure, headers });
|
||||
let body: unknown;
|
||||
|
||||
if (matched) {
|
||||
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
|
||||
if ('response' in acquired) return acquired.response;
|
||||
body = acquired.body;
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
body,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
});
|
||||
|
||||
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
|
||||
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
|
||||
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
|
||||
// so picks up the same authoritative security headers `injected` carries.
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: mergeInjectedHeaders(result.preflight, injected),
|
||||
});
|
||||
}
|
||||
|
||||
return outcomeToResponse(result);
|
||||
return outcomeToResponse(result, opts?.bus, correlation);
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/**
|
||||
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
|
||||
@@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor {
|
||||
|
||||
if (platform) return platform;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws') as SocketCtor;
|
||||
return nodeRequire<SocketCtor>('ws');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+9
-3
@@ -1,5 +1,6 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { correlateRequest } from './core';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
|
||||
@@ -109,6 +110,11 @@ export async function runWsConnection(
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
const name = route.def.pattern;
|
||||
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
|
||||
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
|
||||
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
|
||||
// keeps one identity per connection instead of one per emitter.
|
||||
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
|
||||
const onAbort = () => {
|
||||
@@ -117,7 +123,7 @@ export async function runWsConnection(
|
||||
};
|
||||
|
||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||
bus?.emit('stream:open', { name });
|
||||
bus?.emit('stream:open', trace);
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({
|
||||
@@ -129,9 +135,9 @@ export async function runWsConnection(
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(socket, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
bus?.emit('stream:error', { ...trace, error: err });
|
||||
closeOnError(socket, err);
|
||||
} finally {
|
||||
bus?.emit('stream:close', { name });
|
||||
bus?.emit('stream:close', trace);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -3,14 +3,14 @@ import { channel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
function loadWss(): any | null {
|
||||
try {
|
||||
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
|
||||
// support don't fail. When absent this throws and we fall back to null (501 on upgrade).
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws').WebSocketServer;
|
||||
return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
+28
-7
@@ -5,8 +5,16 @@
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
|
||||
/** Package version, replaced at publish time. */
|
||||
export const VERSION = '26.8.0-beta.0';
|
||||
/**
|
||||
* Package version. Kept in step with `package.json` and `deno.json` by hand, and pinned to them by
|
||||
* `test/package-metadata.test.ts`.
|
||||
*
|
||||
* It used to say it was "replaced at publish time", which nothing ever did — not `tsup`, not
|
||||
* `stage.yml`, not `release.yml`, which only ever *reads* the version out of `package.json`. So the
|
||||
* constant drifted two releases behind while the comment explained why it could not, and the only
|
||||
* test touching it checked the CalVer shape, which a stale version satisfies perfectly.
|
||||
*/
|
||||
export const VERSION = '26.9.0-beta.2';
|
||||
|
||||
// Application
|
||||
export { createApp } from './app';
|
||||
@@ -40,8 +48,10 @@ export {
|
||||
Options,
|
||||
Html,
|
||||
} from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
|
||||
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
|
||||
export type { Hooks } from './app';
|
||||
export type { TeardownFn } from './lifecycle';
|
||||
|
||||
// Transformers & error signals
|
||||
export { JsonTransformer } from './transformers';
|
||||
@@ -54,26 +64,37 @@ export {
|
||||
NotModified,
|
||||
ValidationError,
|
||||
TransportMismatchError,
|
||||
HTTP_ERROR,
|
||||
VALIDATION_ERROR,
|
||||
isHttpError,
|
||||
isValidationError,
|
||||
} from './signals';
|
||||
export type { HttpErrorLike } from './signals';
|
||||
|
||||
// Bus & flow
|
||||
export { Bus } from './bus';
|
||||
export type { LifecycleEvent, EventPayload, Correlation, Events } 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';
|
||||
export type { Channel } from './channel';
|
||||
export { Rooms } from './rooms';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder, SseEvent, SseFields } from './encoders';
|
||||
|
||||
// HTTP, security & validation
|
||||
export type { RequestLimits } from './http';
|
||||
export { UNMATCHED_ROUTE } from './http/core';
|
||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||
export type { UploadedFile, MultipartBody } from './multipart';
|
||||
export type { StandardSchemaV1 } from './standard-schema';
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
+324
-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: { steps: frame.steps, 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,202 @@ export function connectLink(args: {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A manifest's step tokens, flattened to the set the refusal check compares. */
|
||||
function stepKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.steps);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 steps = stepKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const step of booted.steps) {
|
||||
if (!steps.has(step)) missing.push(`step '${step}'`);
|
||||
}
|
||||
|
||||
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;
|
||||
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: { steps: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
close: () => {
|
||||
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||
// 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): 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 });
|
||||
|
||||
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)) 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);
|
||||
|
||||
return link;
|
||||
},
|
||||
(error) => {
|
||||
// The first connect failed, so this `Link` never escaped — nobody holds it and nobody can
|
||||
// ever call `close()` on it. But `openSession`'s abort listener has already run `onEnd`,
|
||||
// which scheduled a retry: left alone, that supervisor reconnects forever to a handle no
|
||||
// caller has, and `closeLinks` cannot reach it because the link was never pushed to
|
||||
// `meshLinks`. Boot already retries above this (`connectUntilDeadline`), so a second
|
||||
// supervisor underneath it is pure leak — every failed attempt used to leave one behind.
|
||||
// Reconnection for a link that *did* connect is untouched: this path runs only on the
|
||||
// initial rejection, and a session that drops later still goes through `endSession`.
|
||||
state.closed = true;
|
||||
clearTimeout(state.retry);
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
+146
-12
@@ -1,33 +1,71 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* **One exception has been taken, and its terms are the point.** The manifest's `scopes` field was
|
||||
* renamed to `steps` at v1 — a rename, which the first rule above would otherwise cover — without a
|
||||
* bump. It was allowed because there is no deployed pair the rename could split: mesh is alpha,
|
||||
* every app using it is gated behind `experimental: true`, and both peers ship out of this one
|
||||
* repo, so a teacup and a teapot are always on the same version. Each of those three has to hold
|
||||
* for the exception to; the first mesh release that drops `experimental` retires it, and a rename
|
||||
* after that earns a bump like any other.
|
||||
*/
|
||||
export const MESH_PROTOCOL_VERSION = 1;
|
||||
|
||||
/** 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. */
|
||||
export interface ScopeEntry {
|
||||
token: string;
|
||||
scope: 'app' | 'request';
|
||||
}
|
||||
/** Manifest entry for an exported route. */
|
||||
export interface RouteEntry {
|
||||
method: string;
|
||||
pattern: string;
|
||||
}
|
||||
/** A mesh server's advertised scopes and routes. */
|
||||
|
||||
/**
|
||||
* A mesh server's advertised steps and routes.
|
||||
*
|
||||
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
|
||||
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
|
||||
* lazy — the token exists in the teacup's graph, and running it is an RPC.
|
||||
*/
|
||||
export interface Manifest {
|
||||
scopes: ScopeEntry[];
|
||||
steps: string[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
|
||||
@@ -40,7 +78,7 @@ export interface Manifest {
|
||||
*/
|
||||
export type Frame =
|
||||
| { type: 'hello'; v: number; secret: string }
|
||||
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
|
||||
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
|
||||
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
|
||||
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
|
||||
@@ -50,6 +88,9 @@ export type Frame =
|
||||
const isString = (value: unknown): value is string => typeof value === 'string';
|
||||
const isNumber = (value: unknown): boolean => typeof value === 'number';
|
||||
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
|
||||
/** A manifest route entry: both fields reach `compilePattern`, so both must really be strings. */
|
||||
const isRouteEntry = (value: unknown): boolean =>
|
||||
isObject(value) && isString((value as RouteEntry).method) && isString((value as RouteEntry).pattern);
|
||||
|
||||
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
|
||||
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
|
||||
@@ -66,7 +107,14 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
||||
},
|
||||
manifest: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
|
||||
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
|
||||
// Array.isArray above already guarantees this, but TS does not carry that narrowing through a
|
||||
// `never`-typed callback parameter — the cast is safe, not a bypass.
|
||||
if (!(frame.steps as unknown[]).every(isString)) bad('every step must be a string');
|
||||
// Checked for the same reason steps are: past `decode` a route entry goes straight to
|
||||
// `compilePattern`, where a non-string `pattern` dies as a boot `TypeError` about a peer's
|
||||
// frame — a failure that reads like a green-tea bug rather than a malformed manifest.
|
||||
if (!(frame.routes as unknown[]).every(isRouteEntry)) bad('every route must have a string method and pattern');
|
||||
},
|
||||
'rpc-req': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
@@ -87,6 +135,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);
|
||||
|
||||
+22
-19
@@ -14,38 +14,41 @@ 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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): {
|
||||
providers: RemoteScopeNode[];
|
||||
steps: RemoteScopeNode[];
|
||||
routes: RemoteRoute[];
|
||||
} {
|
||||
const providers: RemoteScopeNode[] = [];
|
||||
const steps: RemoteScopeNode[] = [];
|
||||
|
||||
for (const scope of link.manifest.scopes) {
|
||||
const node: RemoteScopeNode = {
|
||||
name: scope.token,
|
||||
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
|
||||
};
|
||||
(scope.scope === 'app' ? providers : steps).push(node);
|
||||
}
|
||||
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
|
||||
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
|
||||
name: token,
|
||||
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
|
||||
}));
|
||||
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
return { providers, steps, routes };
|
||||
|
||||
return { steps, routes };
|
||||
}
|
||||
+58
-16
@@ -9,6 +9,7 @@ import { isHttpError } from '../signals';
|
||||
import {
|
||||
encode,
|
||||
decode,
|
||||
untransportable,
|
||||
MESH_PROTOCOL_VERSION,
|
||||
type Manifest,
|
||||
type RequestEnvelope,
|
||||
@@ -19,19 +20,31 @@ import {
|
||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||
export function buildManifest(args: {
|
||||
providers: string[]; // exported provider tokens (app-scope)
|
||||
steps: string[]; // exported step tokens (request-scope)
|
||||
routes: RouteEntry[]; // exported buffered routes
|
||||
}): Manifest {
|
||||
return {
|
||||
scopes: [
|
||||
...args.providers.map((token) => ({ token, scope: 'app' as const })),
|
||||
...args.steps.map((token) => ({ token, scope: 'request' as const })),
|
||||
],
|
||||
routes: args.routes,
|
||||
};
|
||||
/**
|
||||
* 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 step tokens and buffered routes. */
|
||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||
return { steps: [...args.steps], routes: args.routes };
|
||||
}
|
||||
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
@@ -92,7 +105,7 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
|
||||
encode({
|
||||
type: 'manifest',
|
||||
v: MESH_PROTOCOL_VERSION,
|
||||
scopes: deps.manifest.scopes,
|
||||
steps: deps.manifest.steps,
|
||||
routes: deps.manifest.routes,
|
||||
}),
|
||||
);
|
||||
@@ -133,6 +146,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 +177,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 +224,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' });
|
||||
}
|
||||
}
|
||||
@@ -192,7 +234,7 @@ export function createMeshControl(deps: MeshControlDeps): {
|
||||
path: string;
|
||||
handle: (socket: WsSocket) => Promise<void>;
|
||||
} {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
|
||||
const exportedScopes = new Set(deps.manifest.steps);
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||
|
||||
return {
|
||||
|
||||
+50
-37
@@ -15,6 +15,12 @@ export interface ProviderMeta {
|
||||
provides: string;
|
||||
needs: string[];
|
||||
optional: boolean;
|
||||
/**
|
||||
* Always refused. `@Provider`'s options no longer declare `export`, so TypeScript rejects it at
|
||||
* the decorator and this can only be true for a JavaScript caller. It is still recorded so that
|
||||
* caller reaches `collectProviders`' boot error, which names the provider and the replacement,
|
||||
* rather than having the option silently ignored.
|
||||
*/
|
||||
export: boolean;
|
||||
}
|
||||
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
|
||||
@@ -58,18 +64,16 @@ const K = {
|
||||
};
|
||||
|
||||
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
|
||||
export function Provider(opts: {
|
||||
provides: string;
|
||||
needs?: string[];
|
||||
optional?: boolean;
|
||||
export?: boolean;
|
||||
}): ClassDecorator {
|
||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: ProviderMeta = {
|
||||
provides: opts.provides,
|
||||
needs: opts.needs ?? [],
|
||||
optional: opts.optional ?? false,
|
||||
export: opts.export ?? false,
|
||||
// Read through a cast because the options type deliberately does not offer `export`: only a
|
||||
// `@Step` or a route is exportable, and the option's only behaviour was to throw at boot.
|
||||
// A JavaScript caller can still pass it, and recording it is what routes them to that error.
|
||||
export: (opts as { export?: boolean }).export ?? false,
|
||||
};
|
||||
Reflect.defineMetadata(K.provider, meta, target);
|
||||
};
|
||||
@@ -100,48 +104,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 {
|
||||
|
||||
+2
-2
@@ -1,6 +1,7 @@
|
||||
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
|
||||
import { Readable } from 'stream';
|
||||
import { HttpError } from './signals';
|
||||
import { nodeRequire } from './node-require';
|
||||
|
||||
/** A single uploaded file part decoded from a multipart body. */
|
||||
export interface UploadedFile {
|
||||
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
|
||||
try {
|
||||
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
|
||||
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('busboy');
|
||||
return nodeRequire('busboy');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// src/node-require.ts — one `require` that survives being published as source.
|
||||
|
||||
type Require = <T>(id: string) => T;
|
||||
|
||||
interface NodeProcess {
|
||||
cwd?: () => string;
|
||||
getBuiltinModule?: (id: string) => unknown;
|
||||
}
|
||||
|
||||
let cached: Require | null | undefined;
|
||||
|
||||
function resolveRequire(): Require | undefined {
|
||||
// The CJS build has a native one, and tsup gives the ESM build one through a `createRequire`
|
||||
// banner (tsup.config.ts). Both npm paths stop here.
|
||||
if (typeof require === 'function') return require as Require;
|
||||
|
||||
// JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`.
|
||||
// `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all
|
||||
// three do it *synchronously* — which is the whole requirement, since every caller here sits on
|
||||
// a sync path that a dynamic `import()` could not serve.
|
||||
const proc = (globalThis as { process?: NodeProcess }).process;
|
||||
const nodeModule = proc?.getBuiltinModule?.('node:module') as
|
||||
{ createRequire?: (from: string) => Require } | undefined;
|
||||
if (!nodeModule?.createRequire || !proc?.cwd) return undefined;
|
||||
|
||||
// Resolve from the application's directory rather than from this file: served from JSR this
|
||||
// module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer
|
||||
// dependency such as `busboy` is installed in the app that asked for it.
|
||||
return nodeModule.createRequire(`${proc.cwd()}/`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a Node builtin or an installed package, synchronously.
|
||||
*
|
||||
* Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely
|
||||
* out of reach. Every caller already guards for that and reports it in its own terms; what they
|
||||
* must not do is report it when the module is in fact reachable, which is what a bare `require`
|
||||
* caused on JSR by failing with `ReferenceError` before any of them was consulted.
|
||||
*/
|
||||
export function nodeRequire<T>(id: string): T {
|
||||
if (cached === undefined) cached = resolveRequire() ?? null;
|
||||
if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`);
|
||||
return cached<T>(id);
|
||||
}
|
||||
+30
-19
@@ -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 {
|
||||
|
||||
+79
-14
@@ -1,8 +1,9 @@
|
||||
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';
|
||||
import { TransportMismatchError } from './signals';
|
||||
import type { Logger } from './logger';
|
||||
|
||||
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
||||
export interface PipelineStep {
|
||||
@@ -45,15 +46,56 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
|
||||
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
|
||||
* 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 +114,15 @@ export async function runPipeline(args: {
|
||||
bus: Bus;
|
||||
transport: Transport;
|
||||
onError?: ErrorRenderer;
|
||||
logger?: Logger;
|
||||
correlation?: Correlation;
|
||||
}): Promise<PipelineResult> {
|
||||
const { steps, handler, transformer, seed, bus, transport, onError } = args;
|
||||
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
let context: any = { ...seed };
|
||||
|
||||
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,12 +139,33 @@ 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 });
|
||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||
return renderError(
|
||||
error,
|
||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||
onError,
|
||||
);
|
||||
let status: number | undefined;
|
||||
|
||||
try {
|
||||
const rendered = renderError(
|
||||
error,
|
||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||
onError,
|
||||
logger,
|
||||
);
|
||||
status = rendered.status;
|
||||
return rendered;
|
||||
} finally {
|
||||
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
|
||||
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
|
||||
// what produces a trace that says a request failed without saying where.
|
||||
//
|
||||
// Emitted after the render rather than before it, because the status is only decided there:
|
||||
// `onError` may turn any throw into any status, so deriving one from the error would be a
|
||||
// guess that a custom renderer makes wrong.
|
||||
//
|
||||
// In `finally` rather than after the call, so that nothing between here and the emit can cost
|
||||
// us the only record that a request failed. `renderError` already contains a throwing
|
||||
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
|
||||
// first — but a failure whose reporting is what broke is the worst one to lose.
|
||||
if (bus.hasListeners('request:failed'))
|
||||
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
-8
@@ -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,63 @@ 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.
|
||||
*
|
||||
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
|
||||
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
|
||||
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
|
||||
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
|
||||
*
|
||||
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
|
||||
* would turn a one-way observation channel into something any node can forge events on.
|
||||
* `@needs('bus')` fails at boot and says so.
|
||||
*/
|
||||
export interface PluginApi {
|
||||
bus: { on: Bus['on'] };
|
||||
scope: ScopeApi;
|
||||
/**
|
||||
* 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 named object that wires itself up through the provided PluginApi.
|
||||
*
|
||||
* The name is a field rather than `fn.name` because `fn.name` cannot be relied on: an arrow
|
||||
* returned straight from a factory has `""`, `const plugin = …` reports `"plugin"`, and a minifier
|
||||
* rewrites both. The name is what `plugin:mounted` reports and what a failed mount is blamed on, so
|
||||
* it has to be the author's word, not the bundler's.
|
||||
*/
|
||||
export interface Plugin {
|
||||
readonly name: string;
|
||||
mount(api: PluginApi): void;
|
||||
}
|
||||
/** 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 };
|
||||
plugin(api);
|
||||
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
|
||||
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 };
|
||||
|
||||
try {
|
||||
plugin.mount(api);
|
||||
} catch (error) {
|
||||
// Without the name this surfaces as somebody else's stack trace: mounting happens inside
|
||||
// createApp, so the application sees a throw from a line it never wrote.
|
||||
throw new Error(`plugin "${plugin.name}" failed to mount: ${(error as Error).message}`, { cause: error });
|
||||
}
|
||||
|
||||
bus.emit('plugin:mounted', { name: plugin.name });
|
||||
}
|
||||
+26
-5
@@ -1,5 +1,7 @@
|
||||
// src/security.ts — pure header computation, no server deps
|
||||
|
||||
import type { Logger } from './logger';
|
||||
|
||||
/** TLS material for an HTTPS server. */
|
||||
export interface TlsOptions {
|
||||
key: Buffer | string;
|
||||
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
|
||||
return headers;
|
||||
}
|
||||
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
|
||||
if (spec === '*') return true;
|
||||
if (typeof spec === 'function') return spec(origin);
|
||||
if (Array.isArray(spec)) return spec.includes(origin);
|
||||
return spec === origin;
|
||||
if (typeof spec !== 'function') return spec === origin;
|
||||
|
||||
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
|
||||
// before the region where errors convert to a response, so a throw here would leave the request
|
||||
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
|
||||
// has not said yes, and a broken allowlist must never widen into an open one.
|
||||
try {
|
||||
return spec(origin);
|
||||
} catch (error) {
|
||||
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
|
||||
origin,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
|
||||
export function resolveCors(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
logger?: Logger,
|
||||
): Headers {
|
||||
const headers: Headers = {};
|
||||
const rawOrigin = req.headers['origin'];
|
||||
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
|
||||
|
||||
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
|
||||
if (opts.credentials) {
|
||||
@@ -112,8 +128,13 @@ export function resolveCors(
|
||||
export function corsPreflightHeaders(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
resolved?: Headers,
|
||||
): Headers {
|
||||
const headers = resolveCors(opts, req);
|
||||
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
|
||||
// response carries. Re-deriving here would consult `origins` a second time for the same request —
|
||||
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
|
||||
// preflight-only keys below belong to this 204, not to the shared object.
|
||||
const headers: Headers = { ...resolved };
|
||||
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
|
||||
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
|
||||
', ',
|
||||
|
||||
+35
-3
@@ -1,11 +1,36 @@
|
||||
import type { StandardIssue } from './standard-schema';
|
||||
|
||||
/**
|
||||
* Brands, so an error is recognised across two copies of core — an app that installed one from npm
|
||||
* and a plugin that brought another from JSR, or two npm versions npm could not dedupe.
|
||||
* `instanceof` cannot do that: each copy has its own class identity.
|
||||
*
|
||||
* `Symbol.for` is registry-wide, so both copies resolve the same symbol. The *string* is the public
|
||||
* protocol (`.specs/2026-09-15-plugin-ecosystem-design.md`, 1.2): a plugin that imports only types
|
||||
* cannot import this constant, so it writes `Symbol.for('green-tea.http-error')` itself.
|
||||
*
|
||||
* `unique symbol` is required by TypeScript for a computed class field, and `Symbol.for` on a `const`
|
||||
* satisfies it.
|
||||
*/
|
||||
export const HTTP_ERROR: unique symbol = Symbol.for('green-tea.http-error');
|
||||
export const VALIDATION_ERROR: unique symbol = Symbol.for('green-tea.validation-error');
|
||||
|
||||
/** The shape core reads off a branded error. Anything carrying the brand should satisfy it. */
|
||||
export interface HttpErrorLike {
|
||||
status: number;
|
||||
message: string;
|
||||
body?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error carrying an HTTP status code and optional response body. Base of all signals.
|
||||
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
|
||||
* rather than requiring a special case in the error renderer.
|
||||
*/
|
||||
export class HttpError extends Error {
|
||||
readonly [HTTP_ERROR] = true;
|
||||
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message?: string,
|
||||
@@ -47,6 +72,8 @@ export class Redirect extends HttpError {
|
||||
|
||||
/** 422 raised when request input fails Standard Schema validation. */
|
||||
export class ValidationError extends HttpError {
|
||||
readonly [VALIDATION_ERROR] = true;
|
||||
|
||||
constructor(
|
||||
public issues: StandardIssue[],
|
||||
public source: string,
|
||||
@@ -68,7 +95,12 @@ export class TransportMismatchError extends HttpError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard: true if `error` is an {@link HttpError}. */
|
||||
export function isHttpError(error: unknown): error is HttpError {
|
||||
return error instanceof HttpError;
|
||||
/** Type guard: true if `error` carries the HTTP-error brand — this copy's or another's. */
|
||||
export function isHttpError(error: unknown): error is HttpErrorLike {
|
||||
return typeof error === 'object' && error !== null && HTTP_ERROR in error;
|
||||
}
|
||||
|
||||
/** Type guard: true if `error` carries the validation brand. */
|
||||
export function isValidationError(error: unknown): error is ValidationError {
|
||||
return typeof error === 'object' && error !== null && VALIDATION_ERROR in error;
|
||||
}
|
||||
+31
-4
@@ -1,6 +1,7 @@
|
||||
import { isHttpError, ValidationError } from './signals';
|
||||
import { isHttpError, isValidationError } from './signals';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import { flattenPath } from './standard-schema';
|
||||
import type { Logger } from './logger';
|
||||
|
||||
/** A ready-to-send HTTP response. */
|
||||
export interface ErrorResponse {
|
||||
@@ -34,7 +35,7 @@ export const JsonTransformer: TransformerFn = (value) => ({
|
||||
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
|
||||
*/
|
||||
export function errorToResponse(error: unknown): ErrorResponse {
|
||||
if (error instanceof ValidationError) {
|
||||
if (isValidationError(error)) {
|
||||
return {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
|
||||
}
|
||||
|
||||
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
|
||||
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
|
||||
return onError?.(error, req) ?? errorToResponse(error);
|
||||
export function renderError(
|
||||
error: unknown,
|
||||
req: ErrorRequest,
|
||||
onError?: ErrorRenderer,
|
||||
logger?: Logger,
|
||||
): ErrorResponse {
|
||||
if (!onError) return errorToResponse(error);
|
||||
|
||||
// `onError` is user code, it runs on the request path, and it runs *after something already went
|
||||
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
|
||||
// occurs, the code written to report it fails, and the process ends instead of degrading.
|
||||
//
|
||||
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
|
||||
// custom renderer and no matching route is one request away from exiting.
|
||||
//
|
||||
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
|
||||
// overrides and therefore the honest thing to fall back to: the original error still gets its
|
||||
// response. The renderer's own failure is reported separately, because it is a different error
|
||||
// from the request's and a reader chasing the wrong one loses an afternoon.
|
||||
try {
|
||||
return onError(error, req) ?? errorToResponse(error);
|
||||
} catch (rendererError) {
|
||||
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
|
||||
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
|
||||
rendering: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
+8
-9
@@ -3,6 +3,7 @@
|
||||
|
||||
import type { TransformerFn } from './metadata';
|
||||
import type { HtmlMeta } from './metadata';
|
||||
import { nodeRequire } from './node-require';
|
||||
|
||||
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
|
||||
export function escapeHtml(s: string): string {
|
||||
@@ -58,12 +59,12 @@ export interface ViewsContext {
|
||||
|
||||
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
|
||||
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
|
||||
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
|
||||
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
|
||||
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
|
||||
* filesystem should hear about it here rather than at the first request. */
|
||||
function readViewFile(views: string | undefined, path: string): string {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodePath = require('node:path') as typeof import('node:path');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const fs = require('node:fs') as typeof import('node:fs');
|
||||
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
|
||||
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
|
||||
const base = views ?? process.cwd();
|
||||
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
|
||||
|
||||
@@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
let nodePath: typeof import('node:path');
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
fs = require('node:fs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
nodePath = require('node:path');
|
||||
fs = nodeRequire('node:fs');
|
||||
nodePath = nodeRequire('node:path');
|
||||
} catch {
|
||||
throw new Error(
|
||||
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// test/app-boot.test.ts
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createApp, Get, Module, Route, needs } from '../src/index';
|
||||
import type { Plugin } from '../src/index';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/x')
|
||||
x(@needs('thing') thing: string) {
|
||||
return { thing };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const plugin = (run: () => Promise<Record<string, unknown>>): Plugin => ({
|
||||
name: 'thing',
|
||||
mount({ scope }) {
|
||||
scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run });
|
||||
},
|
||||
});
|
||||
|
||||
describe('app.boot()', () => {
|
||||
it('surfaces a failing provider instead of leaving it for the first request', async () => {
|
||||
const app = createApp({ modules: [M], plugins: [plugin(async () => { throw new Error('bad key'); })] });
|
||||
|
||||
await expect(app.boot()).rejects.toThrow(/bad key/);
|
||||
});
|
||||
|
||||
it('runs provider factories exactly once, and serves afterwards', async () => {
|
||||
const run = vi.fn(async () => ({ thing: 'ok' }));
|
||||
const app = createApp({ modules: [M], plugins: [plugin(run)] });
|
||||
|
||||
await app.boot();
|
||||
await app.boot();
|
||||
const response = await app.fetch(new Request('http://x/x'));
|
||||
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
expect(await response.json()).toEqual({ thing: 'ok' });
|
||||
});
|
||||
|
||||
// The memo keeps the rejection, which is exactly why a failed boot answers 500 for the life of
|
||||
// the process instead of retrying. It is the documented behaviour, so it gets a test rather than
|
||||
// a sentence: if it ever starts retrying, the guide in Task 7 becomes wrong.
|
||||
it('keeps a failed boot failed', async () => {
|
||||
const run = vi.fn(async () => {
|
||||
throw new Error('bad key');
|
||||
});
|
||||
const app = createApp({ modules: [M], plugins: [plugin(run)] });
|
||||
|
||||
await expect(app.boot()).rejects.toThrow(/bad key/);
|
||||
await expect(app.boot()).rejects.toThrow(/bad key/);
|
||||
await expect(app.fetch(new Request('http://x/x'))).rejects.toThrow(/bad key/);
|
||||
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -66,9 +66,12 @@ describe('app.upgrade', () => {
|
||||
|
||||
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
|
||||
const seen: string[] = [];
|
||||
const logger = (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
|
||||
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
|
||||
const logger = {
|
||||
name: 'ws-step-logger',
|
||||
mount: (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
|
||||
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
|
||||
},
|
||||
};
|
||||
const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
|
||||
+103
-25
@@ -56,7 +56,10 @@ test('ready() is a no-op on a non-mesh app, so one protocol works for both', asy
|
||||
|
||||
test('a logger plugin observes step:enter without mutating the chain', async () => {
|
||||
const seen: string[] = [];
|
||||
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
|
||||
const logger = {
|
||||
name: 'step-logger',
|
||||
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
|
||||
};
|
||||
const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -256,17 +259,20 @@ describe('per-route subgraph slicing', () => {
|
||||
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
|
||||
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
|
||||
const ran: string[] = [];
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'obs',
|
||||
needs: [],
|
||||
provides: [],
|
||||
run: () => {
|
||||
ran.push('obs');
|
||||
return {};
|
||||
},
|
||||
});
|
||||
const observer = {
|
||||
name: 'side-effect-observer',
|
||||
mount: (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'obs',
|
||||
needs: [],
|
||||
provides: [],
|
||||
run: () => {
|
||||
ran.push('obs');
|
||||
return {};
|
||||
},
|
||||
}),
|
||||
};
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
@@ -285,17 +291,20 @@ describe('per-route subgraph slicing', () => {
|
||||
|
||||
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
|
||||
let seen: any;
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'audit',
|
||||
needs: ['user'],
|
||||
provides: [],
|
||||
run: (ctx: any) => {
|
||||
seen = ctx.user;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
const observer = {
|
||||
name: 'audit-observer',
|
||||
mount: (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'audit',
|
||||
needs: ['user'],
|
||||
provides: [],
|
||||
run: (ctx: any) => {
|
||||
seen = ctx.user;
|
||||
return {};
|
||||
},
|
||||
}),
|
||||
};
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
@@ -439,6 +448,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 +495,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', () => {
|
||||
@@ -538,7 +612,11 @@ describe('rooms auto-provide', () => {
|
||||
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
|
||||
s.close();
|
||||
});
|
||||
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
|
||||
// This used to be allowed, and the user's provider silently replaced the framework's. The same
|
||||
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
|
||||
// the logger core writes to — a divergence discovered from a log line that never appeared.
|
||||
// Framework token names are reserved now, and taking one is a boot error.
|
||||
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
|
||||
@Provider({ provides: 'rooms' })
|
||||
class MyRooms {
|
||||
provide() {
|
||||
@@ -553,7 +631,7 @@ describe('rooms auto-provide', () => {
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
|
||||
class M {}
|
||||
expect(() => createApp({ modules: [M] })).not.toThrow();
|
||||
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -76,3 +76,46 @@ describe('renderMarkdown', () => {
|
||||
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderMarkdown runtime matrix', () => {
|
||||
const base = {
|
||||
env: { date: '2026-09-01', commit: 'abc1234', node: 'v22', os: 'darwin', cpu: 'M4', ram: '69 GB', pinned: false },
|
||||
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
|
||||
scenarios: [],
|
||||
stepScaling: [],
|
||||
secureCost: [],
|
||||
};
|
||||
|
||||
it('renders one column per runtime and one row per scenario', () => {
|
||||
const md = renderMarkdown({
|
||||
...base,
|
||||
runtimes: [
|
||||
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
|
||||
{ runtime: 'bun', scenario: 'JSON hello', reqSec: 120_000 },
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(md).toContain('## green-tea across runtimes');
|
||||
expect(md).toContain('| Scenario | node | bun |');
|
||||
expect(md).toContain('| JSON hello | 90,000 | 120,000 |');
|
||||
});
|
||||
|
||||
it('marks a runtime that produced no number rather than printing a zero', () => {
|
||||
// A skipped runtime must not read as "it ran and scored nothing".
|
||||
const md = renderMarkdown({
|
||||
...base,
|
||||
runtimes: [
|
||||
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
|
||||
{ runtime: 'deno', scenario: 'Route param', reqSec: 80_000 },
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(md).toContain('| JSON hello | 90,000 | — |');
|
||||
expect(md).toContain('| Route param | — | 80,000 |');
|
||||
});
|
||||
|
||||
it('omits the section entirely when no runtime was measured', () => {
|
||||
expect(renderMarkdown({ ...base, runtimes: [] } as never)).not.toContain('across runtimes');
|
||||
expect(renderMarkdown(base as never)).not.toContain('across runtimes');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
// Independent providers boot concurrently; dependent ones still wait.
|
||||
//
|
||||
// The graph already proved which providers cannot constrain each other — that is what the topo
|
||||
// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies
|
||||
// instead of its longest chain, for no ordering anyone declared.
|
||||
//
|
||||
// Timing is asserted structurally rather than by clock: "all three entered before any left" is
|
||||
// the same claim as "they overlapped" and does not get flaky on a loaded CI box.
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Get, Module, Provider, Route, type Ctor } from '../src/metadata';
|
||||
import { createApp } from '../src/app';
|
||||
import type { Logger } from '../src/logger';
|
||||
|
||||
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
|
||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/ping') ping() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
/** Boots the app by serving one request — providers are lazy until something is actually served. */
|
||||
async function boot(module: Ctor, logger = silentLogger()): Promise<void> {
|
||||
const app = createApp({ modules: [module], logger });
|
||||
await app.fetch(new Request('http://x/ping'));
|
||||
await app.close();
|
||||
}
|
||||
|
||||
describe('provider boot concurrency', () => {
|
||||
it('overlaps providers that do not depend on each other', async () => {
|
||||
const log: string[] = [];
|
||||
|
||||
const independent = (name: string): Ctor => {
|
||||
@Provider({ provides: name })
|
||||
class P {
|
||||
async provide() {
|
||||
log.push(`${name}:in`);
|
||||
await sleep(10);
|
||||
log.push(`${name}:out`);
|
||||
return { [name]: name };
|
||||
}
|
||||
}
|
||||
return P;
|
||||
};
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] })
|
||||
class M {}
|
||||
await boot(M);
|
||||
|
||||
// Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit.
|
||||
expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']);
|
||||
expect(log).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('still waits for a provider its dependant needs', async () => {
|
||||
const log: string[] = [];
|
||||
|
||||
@Provider({ provides: 'base' })
|
||||
class Base {
|
||||
async provide() {
|
||||
log.push('base:in');
|
||||
await sleep(10);
|
||||
log.push('base:out');
|
||||
return { base: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
@Provider({ provides: 'derived', needs: ['base'] })
|
||||
class Derived {
|
||||
provide(ctx: { base: number }) {
|
||||
log.push('derived:in');
|
||||
return { derived: ctx.base + 1 };
|
||||
}
|
||||
}
|
||||
|
||||
// Declared out of order on purpose: the wait is the graph's doing, not the array's.
|
||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] })
|
||||
class M {}
|
||||
await boot(M);
|
||||
|
||||
expect(log).toEqual(['base:in', 'base:out', 'derived:in']);
|
||||
});
|
||||
|
||||
it('gives a dependant every value from its level, not just the one that finished first', async () => {
|
||||
@Provider({ provides: 'slow' })
|
||||
class Slow {
|
||||
async provide() {
|
||||
await sleep(15);
|
||||
return { slow: 'slow' };
|
||||
}
|
||||
}
|
||||
|
||||
@Provider({ provides: 'fast' })
|
||||
class Fast {
|
||||
provide() {
|
||||
return { fast: 'fast' };
|
||||
}
|
||||
}
|
||||
|
||||
let seen: Record<string, unknown> = {};
|
||||
@Provider({ provides: 'joined', needs: ['slow', 'fast'] })
|
||||
class Joined {
|
||||
provide(ctx: Record<string, unknown>) {
|
||||
seen = { slow: ctx.slow, fast: ctx.fast };
|
||||
return { joined: true };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] })
|
||||
class M {}
|
||||
await boot(M);
|
||||
|
||||
expect(seen).toEqual({ slow: 'slow', fast: 'fast' });
|
||||
});
|
||||
|
||||
it('tears down in reverse boot order even though boot is concurrent', async () => {
|
||||
const disposed: string[] = [];
|
||||
|
||||
const independent = (name: string, delay: number): Ctor => {
|
||||
@Provider({ provides: name })
|
||||
class P {
|
||||
async provide() {
|
||||
await sleep(delay);
|
||||
return { [name]: name };
|
||||
}
|
||||
dispose() {
|
||||
disposed.push(name);
|
||||
}
|
||||
}
|
||||
return P;
|
||||
};
|
||||
|
||||
// `c` finishes first and `a` last — completion order is the reverse of declaration order, so a
|
||||
// teardown registered as each one lands would come out in a different order than this.
|
||||
@Module({
|
||||
mountpoint: '/',
|
||||
controllers: [Ctl],
|
||||
providers: [independent('a', 20), independent('b', 10), independent('c', 1)],
|
||||
})
|
||||
class M {}
|
||||
await boot(M);
|
||||
|
||||
expect(disposed).toEqual(['c', 'b', 'a']);
|
||||
});
|
||||
|
||||
it('fails the boot on a required provider, and still registers its siblings for teardown', async () => {
|
||||
const disposed: string[] = [];
|
||||
|
||||
@Provider({ provides: 'ok' })
|
||||
class Ok {
|
||||
async provide() {
|
||||
await sleep(10); // still in flight when its sibling rejects
|
||||
return { ok: true };
|
||||
}
|
||||
dispose() {
|
||||
disposed.push('ok');
|
||||
}
|
||||
}
|
||||
|
||||
@Provider({ provides: 'broken' })
|
||||
class Broken {
|
||||
provide(): never {
|
||||
throw new Error('no pool');
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], logger: silentLogger() });
|
||||
|
||||
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
|
||||
// The sibling booted — it was already in flight — so whatever it opened has to be closeable.
|
||||
await app.close();
|
||||
expect(disposed).toEqual(['ok']);
|
||||
});
|
||||
|
||||
it('degrades an optional provider without taking its level down', async () => {
|
||||
const logger = silentLogger();
|
||||
|
||||
@Provider({ provides: 'flaky', optional: true })
|
||||
class Flaky {
|
||||
provide(): never {
|
||||
throw new Error('nope');
|
||||
}
|
||||
}
|
||||
|
||||
@Provider({ provides: 'solid' })
|
||||
class Solid {
|
||||
provide() {
|
||||
return { solid: true };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], logger });
|
||||
await app.fetch(new Request('http://x/ping'));
|
||||
|
||||
expect(app.degraded()).toEqual(['flaky']);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -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, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
run() {
|
||||
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', steps: [Config, 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. */
|
||||
async function startTeapot(port: number) {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = await 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 = 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' } }));
|
||||
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 = await 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();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming
|
||||
// Real Bun integration test for mesh: a teapot exporting its steps and a teacup consuming
|
||||
// them, both under the actual Bun runtime, driven entirely through serveBun.
|
||||
//
|
||||
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
|
||||
@@ -8,14 +8,14 @@
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
run() {
|
||||
return { config: { region: 'mx', runtime: 'bun' } };
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ class Auth {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
@Module({ mountpoint: '/api', steps: [Config, Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
@@ -42,14 +42,14 @@ const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
|
||||
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const tServer = serveBun(teapot, { port: 0 });
|
||||
const tServer = await serveBun(teapot, { port: 0 });
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
|
||||
});
|
||||
const cServer = serveBun(teacup, { port: 0 });
|
||||
const cServer = await serveBun(teacup, { port: 0 });
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
||||
@@ -67,7 +67,7 @@ test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () =>
|
||||
|
||||
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const tServer = serveBun(teapot, { port: 0 });
|
||||
const tServer = await serveBun(teapot, { port: 0 });
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// 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, Provider, needs } 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 = await serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
|
||||
await Bun.sleep(50); // let the request actually reach the handler
|
||||
|
||||
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 = await serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
|
||||
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
|
||||
|
||||
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: [{
|
||||
name: 'teardown-probe',
|
||||
mount: (api) => api.onShutdown(async () => {
|
||||
await Bun.sleep(10);
|
||||
closed.push('plugin');
|
||||
}),
|
||||
}],
|
||||
});
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
|
||||
await server.close({ timeoutMs: 2000 });
|
||||
|
||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||
expect(closed).toEqual(['plugin', 'hook']);
|
||||
});
|
||||
|
||||
// The boot gate, which is why serveBun is async. Before it, a provider that threw was memoized as a
|
||||
// rejection and answered 500 to every request from the runtime, never reaching onError — so the
|
||||
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
|
||||
@Provider({ provides: 'key' })
|
||||
class BadKey {
|
||||
provide(): never {
|
||||
throw new Error('no such key file');
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class NeedsKey {
|
||||
@Get('/signed')
|
||||
signed(@needs('key') key: string) {
|
||||
return { key };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
|
||||
class KeyModule {}
|
||||
|
||||
test('serveBun rejects when a provider fails, instead of binding a port that 500s', async () => {
|
||||
const app = createApp({ modules: [KeyModule] });
|
||||
|
||||
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
|
||||
});
|
||||
+1
-1
@@ -26,7 +26,7 @@ class M {}
|
||||
|
||||
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = serveBun(app, { port: 0 });
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// The three legitimate ways to reach the bus, exercised together in one app.
|
||||
//
|
||||
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
|
||||
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
|
||||
// from inside the graph all still work, and only `emit` stays where it was.
|
||||
import 'reflect-metadata';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Route, Get, Module, needs } from '../src/index';
|
||||
import type { Events, Plugin } from '../src/index';
|
||||
|
||||
@Route('/b')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('events') events: Events) {
|
||||
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
|
||||
// about, and nothing here does that.
|
||||
return { hasOn: typeof events.on === 'function' };
|
||||
}
|
||||
}
|
||||
|
||||
describe('reaching the bus', () => {
|
||||
it('works from outside, from a plugin and from the graph, all at once', async () => {
|
||||
const fromOutside: string[] = [];
|
||||
const fromPlugin: string[] = [];
|
||||
|
||||
const observer: Plugin = {
|
||||
name: 'bus-observer',
|
||||
mount(api) {
|
||||
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
|
||||
},
|
||||
};
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
// 1. from outside: the public `app.bus`, which keeps `emit` too.
|
||||
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
|
||||
|
||||
// 3. from the graph: the handler receives `events` and reports its shape.
|
||||
const res = await app.fetch(new Request('http://x/b/x'));
|
||||
|
||||
expect(await res.json()).toEqual({ hasOn: true });
|
||||
expect(fromOutside).toEqual(['/b/x']);
|
||||
expect(fromPlugin).toEqual(['/b/x']);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('keeps emit outside the graph and outside plugins, and only there', async () => {
|
||||
let injected: Events | undefined;
|
||||
const seen: string[] = [];
|
||||
|
||||
@Route('/e')
|
||||
class Grab {
|
||||
@Get('/x') x(@needs('events') events: Events) {
|
||||
injected = events;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Grab] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M] });
|
||||
await app.fetch(new Request('http://x/e/x'));
|
||||
|
||||
// The graph's slice cannot forge an event...
|
||||
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
|
||||
|
||||
// ...while the application that owns the app still can, which is what `app.bus` is for.
|
||||
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
|
||||
app.bus.emit('plugin:mounted', { name: 'from the owner' });
|
||||
expect(seen).toEqual(['from the owner']);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// `scripts/changelog-section.mjs` writes the body of every GitHub release. It is the only place where
|
||||
// a mistake is invisible until it is already published, so its boundaries are pinned here rather than
|
||||
// checked by eye at release time.
|
||||
const SCRIPT = resolve(process.cwd(), 'scripts/changelog-section.mjs');
|
||||
const section = (version: string, tag?: string): string =>
|
||||
execFileSync('node', [SCRIPT, version, ...(tag ? [tag] : [])], { encoding: 'utf8' });
|
||||
|
||||
const changelog = readFileSync(resolve(process.cwd(), 'CHANGELOG.md'), 'utf8');
|
||||
const released = [...changelog.matchAll(/^## \[(\d[^\]]*)\]/gm)].map(([, v]) => v);
|
||||
|
||||
describe('changelog section extraction', () => {
|
||||
it('finds every released version', () => {
|
||||
expect(released.length).toBeGreaterThan(0);
|
||||
for (const version of released) {
|
||||
expect(section(version).trim(), version).not.toBe('');
|
||||
}
|
||||
});
|
||||
|
||||
it('stops at the next version, so a section never carries the one below it', () => {
|
||||
for (const version of released) {
|
||||
expect(section(version), version).not.toMatch(/^## \[/m);
|
||||
}
|
||||
});
|
||||
|
||||
// The oldest section is the one at risk: nothing follows it but the `[label]: url` block that
|
||||
// defines the compare links, which belongs to no version and once ended up inside it.
|
||||
it('stops at the link-reference block', () => {
|
||||
for (const version of released) {
|
||||
expect(section(version), version).not.toMatch(/^\[[^\]]+\]:\s+\S/m);
|
||||
}
|
||||
});
|
||||
|
||||
// A release body resolves relative links against the release page, not the repository, so every
|
||||
// link has to be absolute by the time it is published.
|
||||
it('rewrites relative links against the tag', () => {
|
||||
for (const version of released) {
|
||||
const links = [...section(version, `v${version}`).matchAll(/\]\(([^)\s]+)\)/g)].map(([, url]) => url);
|
||||
expect(links.filter((url) => !url.startsWith('http')), version).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it('fails rather than publishing an empty body for a version it cannot find', () => {
|
||||
expect(() => section('0.0.0-nonexistent')).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
});
|
||||
@@ -29,7 +29,13 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
|
||||
});
|
||||
|
||||
const upgrade = vi.fn().mockResolvedValue(undefined);
|
||||
serveDeno({ upgrade } as unknown as App);
|
||||
// `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
|
||||
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
|
||||
const handleSignals = <T,>(closer: T): T => closer;
|
||||
// `serveDeno` boots before it binds, so the stub needs the gate even though this test never
|
||||
// exercises it.
|
||||
const boot = vi.fn().mockResolvedValue(undefined);
|
||||
await serveDeno({ upgrade, handleSignals, boot } as unknown as App);
|
||||
const info = {
|
||||
get remoteAddr() {
|
||||
if (upgraded) throw new TypeError('Request closed');
|
||||
|
||||
@@ -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 = await serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
||||
}
|
||||
|
||||
/** 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();
|
||||
}
|
||||
});
|
||||
@@ -10,14 +10,14 @@
|
||||
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
const NODE_PEER = 'test/interop/_node-peer.ts';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
run() {
|
||||
return { config: { region: 'mx', runtime: 'deno' } };
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ class Auth {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
@Module({ mountpoint: '/api', steps: [Config, Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
@@ -112,7 +112,7 @@ Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
|
||||
try {
|
||||
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||
assertEquals(res.status, 200);
|
||||
// the config came from the Node process: proof the scope crossed the runtime boundary
|
||||
// the config came from the Node process: proof the remote step crossed the runtime boundary
|
||||
assertEquals(await res.json(), {
|
||||
config: { region: 'mx', runtime: 'node' },
|
||||
auth: { token: 'abc' },
|
||||
@@ -127,7 +127,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
let port = 0;
|
||||
const { serveDeno } = await import('../../src/deno.ts');
|
||||
const server = serveDeno(teapot, {
|
||||
const server = await serveDeno(teapot, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
@@ -140,7 +140,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
|
||||
try {
|
||||
const result = await firstJsonLine(node);
|
||||
assertEquals(result.ok, true);
|
||||
// the Node peer resolved a scope served by Deno's app.upgrade control channel
|
||||
// the Node peer ran a step served by Deno's app.upgrade control channel
|
||||
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
|
||||
assertEquals(result.body.auth, { token: 'abc' });
|
||||
} finally {
|
||||
|
||||
@@ -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, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
run() {
|
||||
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', steps: [Config, 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 = await 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();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming
|
||||
// Real Deno integration test for mesh: a teapot exporting its steps and a teacup consuming
|
||||
// them, both under the actual Deno runtime, driven entirely through serveDeno.
|
||||
//
|
||||
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
|
||||
@@ -13,14 +13,14 @@
|
||||
// including Node-only modules this test never executes. tsc covers those.
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
run() {
|
||||
return { config: { region: 'mx', runtime: 'deno' } };
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ class Auth {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
@Module({ mountpoint: '/api', steps: [Config, Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
@@ -46,7 +46,7 @@ class TeacupModule {}
|
||||
/** Starts an app on Deno and resolves once its port is known. */
|
||||
async function serve(app: ReturnType<typeof createApp>) {
|
||||
let port = 0;
|
||||
const server = serveDeno(app, {
|
||||
const server = await serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// 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, Provider, needs } 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 = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
|
||||
fetch(`http://127.0.0.1:${portOf(server)}/hang`).catch(() => {});
|
||||
await new Promise((r) => setTimeout(r, 50)); // let the request actually reach the handler
|
||||
|
||||
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 = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
|
||||
const inFlight = fetch(`http://127.0.0.1:${portOf(server)}/slow`).then((r) => r.json());
|
||||
await new Promise((r) => setTimeout(r, 50)); // must be *in* the handler before we close
|
||||
|
||||
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 = await serveDeno(createApp({ modules: [M] }), { port: 0, signal: ac.signal, onListen: () => {} });
|
||||
|
||||
ac.abort();
|
||||
await server.finished; // hangs here if chaining the caller's signal into ours dropped it
|
||||
});
|
||||
|
||||
// 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: [{
|
||||
name: 'teardown-probe',
|
||||
mount: (api) => api.onShutdown(async () => {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
closed.push('plugin');
|
||||
}),
|
||||
}],
|
||||
});
|
||||
const server = await serveDeno(app, { port: 0 });
|
||||
|
||||
await server.close({ timeoutMs: 2000 });
|
||||
|
||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||
if (closed.join(',') !== 'plugin,hook') throw new Error(`expected plugin,hook — got ${closed.join(',')}`);
|
||||
});
|
||||
|
||||
// The boot gate, which is why serveDeno is async. Before it, a provider that threw was memoized as
|
||||
// a rejection and answered 500 to every request from the runtime, never reaching onError — so the
|
||||
// failure looked like a runtime fault at 3am instead of a deploy that refused to start.
|
||||
@Provider({ provides: 'key' })
|
||||
class BadKey {
|
||||
provide(): never {
|
||||
throw new Error('no such key file');
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class NeedsKey {
|
||||
@Get('/signed')
|
||||
signed(@needs('key') key: string) {
|
||||
return { key };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [BadKey], controllers: [NeedsKey] })
|
||||
class KeyModule {}
|
||||
|
||||
Deno.test('serveDeno rejects when a provider fails, instead of binding a port that 500s', async () => {
|
||||
const app = createApp({ modules: [KeyModule] });
|
||||
let message = '';
|
||||
|
||||
try {
|
||||
await serveDeno(app, { port: 0, onListen: () => {} });
|
||||
} catch (error) {
|
||||
message = (error as Error).message;
|
||||
}
|
||||
|
||||
if (!message.includes('no such key file')) {
|
||||
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// `createApp({ handleSignals: true })` under the real Deno runtime.
|
||||
//
|
||||
// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno
|
||||
// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed —
|
||||
// so an app that closed itself and forgot to unregister would hang here and nowhere else.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import { assert, assertEquals } from 'jsr:@std/assert';
|
||||
|
||||
const HARNESS = 'test/interop/_signal-app-deno.ts';
|
||||
|
||||
async function run(): Promise<{ code: number; lines: string[] }> {
|
||||
const child = new Deno.Command('deno', {
|
||||
args: ['run', '--allow-all', '--no-check', HARNESS],
|
||||
stdout: 'piped',
|
||||
stderr: 'inherit',
|
||||
}).spawn();
|
||||
|
||||
const lines: string[] = [];
|
||||
let buffered = '';
|
||||
let signalled = false;
|
||||
|
||||
const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader();
|
||||
const pump = (async () => {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buffered += value;
|
||||
const parts = buffered.split('\n');
|
||||
buffered = parts.pop() ?? '';
|
||||
for (const line of parts.filter(Boolean)) {
|
||||
lines.push(line);
|
||||
if (!signalled && line.includes('"ready"')) {
|
||||
signalled = true;
|
||||
child.kill('SIGTERM');
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
const status = await child.status;
|
||||
await pump;
|
||||
return { code: status.code, lines };
|
||||
}
|
||||
|
||||
Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => {
|
||||
const { code, lines } = await run();
|
||||
assert(
|
||||
lines.some((l) => l.includes('"disposed"')),
|
||||
`dispose() never ran — got: ${lines.join(' | ')}`,
|
||||
);
|
||||
assertEquals(code, 0);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it.
|
||||
//
|
||||
// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire`
|
||||
// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has
|
||||
// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a
|
||||
// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a
|
||||
// green suite. Run with: npm run test:deno
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Get, Html, Module } from '../../src/index.ts';
|
||||
|
||||
// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`.
|
||||
const dir = 'test/fixtures/views';
|
||||
|
||||
@Route('/')
|
||||
class Views {
|
||||
@Get('/dash') @Html('dash.html') dash() {}
|
||||
@Get('/user') @Html('user.html', { template: true }) user() {
|
||||
return { name: 'Deno' };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Views] })
|
||||
class M {}
|
||||
|
||||
Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => {
|
||||
const app = createApp({ modules: [M], views: dir });
|
||||
const res = await app.fetch(new Request('http://x/dash'));
|
||||
assertEquals(res.status, 200);
|
||||
assertEquals(await res.text(), '<h1>Dash</h1>');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('@Html template mode renders', async () => {
|
||||
const app = createApp({ modules: [M], views: dir });
|
||||
const res = await app.fetch(new Request('http://x/user'));
|
||||
assertStringIncludes(await res.text(), 'Hi Deno');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
// Deno has a filesystem, so `static` must not report the runtime as the reason for anything.
|
||||
Deno.test('static: true builds a resolver instead of blaming the runtime', async () => {
|
||||
const app = createApp({ modules: [], static: dir });
|
||||
const res = await app.fetch(new Request('http://x/asset.txt'));
|
||||
assertEquals(res.status, 200);
|
||||
assertEquals(await res.text(), 'served');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy`
|
||||
// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that
|
||||
// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one
|
||||
// diagnosis guaranteed to send a reader to reinstall a package they already have.
|
||||
Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => {
|
||||
const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts');
|
||||
|
||||
@R('/')
|
||||
class Upload {
|
||||
@Post('/up') up(@body() b: { fields: Record<string, string>; files: Record<string, { filename: string }> }) {
|
||||
return { name: b.fields.name, filename: b.files.file.filename };
|
||||
}
|
||||
}
|
||||
|
||||
@Mod({ mountpoint: '/', controllers: [Upload] })
|
||||
class UploadMod {}
|
||||
|
||||
const app = create({ modules: [UploadMod] });
|
||||
const form = new FormData();
|
||||
form.set('name', 'joe');
|
||||
form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png');
|
||||
|
||||
const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form }));
|
||||
assertEquals(res.status, 200);
|
||||
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
|
||||
await app.close();
|
||||
});
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user