Compare commits
225
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f9e6b19d6 | ||
|
|
7be26fda5c | ||
|
|
e540752f1e | ||
|
|
e86051382d | ||
|
|
b8cb684a6b | ||
|
|
2c838c8753 | ||
|
|
cd4f47486f | ||
|
|
ffb5139cae | ||
|
|
46342a0aa2 | ||
|
|
1975a7c03f | ||
|
|
f2cb411eac | ||
|
|
1ccbf6cadf | ||
|
|
6ffbad9825 | ||
|
|
6672185ba2 | ||
|
|
198e62944f | ||
|
|
7d04b2d736 | ||
|
|
51608b0631 | ||
|
|
bbcc90eb4d | ||
|
|
9b5347aa75 | ||
|
|
0218508a96 | ||
|
|
41c1f4308b | ||
|
|
bb75cabeea | ||
|
|
bead3c1569 | ||
|
|
0414aff665 | ||
|
|
21765c2a47 | ||
|
|
cd6e2f073f | ||
|
|
38b73cebce | ||
|
|
62d0b7aa3a | ||
|
|
24feca481c | ||
|
|
bfe8b66127 | ||
|
|
78b5034936 | ||
|
|
a5c1fda886 | ||
|
|
e778f62902 | ||
|
|
9f72604cbb | ||
|
|
101c4fe65a | ||
|
|
a4bb3c02d6 | ||
|
|
0c9f8a545e | ||
|
|
e625d5c881 | ||
|
|
5fafe97bc5 | ||
|
|
8d8ef7ed09 | ||
|
|
0c5decbeae | ||
|
|
86dd3fe9b6 | ||
|
|
523e3184b0 | ||
|
|
92987d0a24 | ||
|
|
e052d5ba8f | ||
|
|
df460f01dd | ||
|
|
7b0a3d4e24 | ||
|
|
dabab1812b | ||
|
|
633ef58032 | ||
|
|
2c47ee8896 | ||
|
|
7bd11bff27 | ||
|
|
d324ecfcb4 | ||
|
|
8c3844e577 | ||
|
|
f97ac8098b | ||
|
|
e4a2047a1e | ||
|
|
586e14da72 | ||
|
|
085eb9a67d | ||
|
|
91f349bef7 | ||
|
|
f96c2ad401 | ||
|
|
a0fd74da34 | ||
|
|
1c5a908fb9 | ||
|
|
30f33b6383 | ||
|
|
70bb9902dc | ||
|
|
9c3bc9574b | ||
|
|
08310ac252 | ||
|
|
31cafcc3fa | ||
|
|
4aae9c3e71 | ||
|
|
2e4712788b | ||
|
|
9d95260706 | ||
|
|
3dcf784159 | ||
|
|
7518a5a785 | ||
|
|
da6099b0e6 | ||
|
|
f200045fd7 | ||
|
|
18d441b3ec | ||
|
|
3714f7befc | ||
|
|
ab58c064d5 | ||
|
|
6fa40672c6 | ||
|
|
1bb82491bd | ||
|
|
b08ecb66cc | ||
|
|
9bff2a52c9 | ||
|
|
551e79a86c | ||
|
|
61bef36d60 | ||
|
|
024b0a79fd | ||
|
|
8c781c1258 | ||
|
|
84a2a29ed6 | ||
|
|
9d8e970c85 | ||
|
|
9e5e5cffe9 | ||
|
|
beec350fcd | ||
|
|
37693246d7 | ||
|
|
1b8f2f3140 | ||
|
|
e820954ea8 | ||
|
|
324ddf0d61 | ||
|
|
f2db461187 | ||
|
|
55263f2d97 | ||
|
|
506dedb624 | ||
|
|
1030109efa | ||
|
|
08d92f5de7 | ||
|
|
4f504eda11 | ||
|
|
94ab334d85 | ||
|
|
3a8d93320d | ||
|
|
270480b2d6 | ||
|
|
27f1d103ea | ||
|
|
0ad53fa284 | ||
|
|
8babcb9554 | ||
|
|
6dd23ed874 | ||
|
|
5fccd3cc8c | ||
|
|
9398a5a2df | ||
|
|
29aafde84c | ||
|
|
dbb996dd4c | ||
|
|
05e59383f1 | ||
|
|
97a146a758 | ||
|
|
aa3402bd84 | ||
|
|
f45ee7d309 | ||
|
|
00aef4541b | ||
|
|
bd3b2556bc | ||
|
|
87c1226e97 | ||
|
|
1db4e01e40 | ||
|
|
74f09d2e0b | ||
|
|
fcd3df7022 | ||
|
|
934fbd4c19 | ||
|
|
d9276a4769 | ||
|
|
3a56e656bd | ||
|
|
a2acec69bf | ||
|
|
9a61ba8646 | ||
|
|
63be0ef8f7 | ||
|
|
8e38fffd77 | ||
|
|
790db661e5 | ||
|
|
63a61aeb0b | ||
|
|
e343ae501f | ||
|
|
813a29001b | ||
|
|
e0212d14e5 | ||
|
|
8d923e053c | ||
|
|
ab6b1b1ef2 | ||
|
|
1a313c21ad | ||
|
|
3ff90b418d | ||
|
|
523e302012 | ||
|
|
8e822cad17 | ||
|
|
3fe0016dbd | ||
|
|
e068426582 | ||
|
|
8bd2a3f61c | ||
|
|
96d863d402 | ||
|
|
33df70730b | ||
|
|
5fc37a2df7 | ||
|
|
2a84331022 | ||
|
|
91fe8f8aff | ||
|
|
3a4cd5a7ce | ||
|
|
642ef109b2 | ||
|
|
4081106813 | ||
|
|
b72883c2ed | ||
|
|
489aa685bb | ||
|
|
c12be9a2f5 | ||
|
|
0541464093 | ||
|
|
502b2c6b72 | ||
|
|
dba40b0c8b | ||
|
|
5e7d952f45 | ||
|
|
9886e53747 | ||
|
|
34dbb32b2c | ||
|
|
033af2d1fc | ||
|
|
a74417494f | ||
|
|
0c68cba532 | ||
|
|
db9a7712af | ||
|
|
0ea4db3fef | ||
|
|
71b59e7c25 | ||
|
|
87772868ab | ||
|
|
dd0ea91a1b | ||
|
|
d56eeafcd8 | ||
|
|
9421b102d9 | ||
|
|
922700674c | ||
|
|
44cf547f1b | ||
|
|
76267b74ec | ||
|
|
2b646eaec6 | ||
|
|
535392baba | ||
|
|
4d1ff33f74 | ||
|
|
f613a6427b | ||
|
|
35861f0fc1 | ||
|
|
2d6306b318 | ||
|
|
289ca5f8ff | ||
|
|
ad3a06f057 | ||
|
|
b8ebb9d04b | ||
|
|
e1a2c3253b | ||
|
|
da5cc936a3 | ||
|
|
e54de8c1db | ||
|
|
df13a62d93 | ||
|
|
6833293ccf | ||
|
|
cb4ecd6801 | ||
|
|
70925035d7 | ||
|
|
a4c9df9a74 | ||
|
|
9344cc7d43 | ||
|
|
86c206d2c9 | ||
|
|
82824e5f6d | ||
|
|
3d21117a07 | ||
|
|
4351b41038 | ||
|
|
fd6446f514 | ||
|
|
8d3a4ca420 | ||
|
|
4a6ef784ec | ||
|
|
47b7bf5f24 | ||
|
|
f85b39c2c3 | ||
|
|
e9357efb5c | ||
|
|
12eccd941c | ||
|
|
d72452d9b6 | ||
|
|
7a8be39d57 | ||
|
|
5e68d2de65 | ||
|
|
179a58f0e4 | ||
|
|
0aab3ed123 | ||
|
|
58853e8ba8 | ||
|
|
43a4316a29 | ||
|
|
1fee7de543 | ||
|
|
b75f127b2c | ||
|
|
08cb8554e6 | ||
|
|
93a4246de5 | ||
|
|
fc75cc05e5 | ||
|
|
16823408c7 | ||
|
|
118eb5516d | ||
|
|
9d97443847 | ||
|
|
aaafe76d8f | ||
|
|
27a984f070 | ||
|
|
2db5de6858 | ||
|
|
7c20d74fe4 | ||
|
|
40d3390ddb | ||
|
|
654c0563fc | ||
|
|
d6c5cee0ee | ||
|
|
9d79972f62 | ||
|
|
3ca4c8680e | ||
|
|
bb960ee669 | ||
|
|
0df82479ee |
No files matched your search
@@ -1,18 +0,0 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [develop, main]
|
||||
pull_request:
|
||||
branches: [develop, main]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
- run: npm ci
|
||||
- run: npm run typecheck
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
# Pre-commit gate. Auto-fixes formatting/lint on staged source, then enforces
|
||||
# lint + cognitive-complexity. Enabled via `git config core.hooksPath .githooks`
|
||||
# (run automatically by the `prepare` npm script on install).
|
||||
set -e
|
||||
|
||||
# Auto-fix format + lint on staged TypeScript sources, then re-stage them.
|
||||
staged=$(git diff --cached --name-only --diff-filter=ACM -- 'src/*.ts' 'src/**/*.ts')
|
||||
if [ -n "$staged" ]; then
|
||||
echo "$staged" | xargs npx prettier --write
|
||||
echo "$staged" | xargs npx eslint --fix
|
||||
echo "$staged" | xargs git add
|
||||
fi
|
||||
|
||||
# Enforce (no auto-fix): lint must be clean, and no function over the complexity gate.
|
||||
npm run lint
|
||||
npm run complexity:check
|
||||
@@ -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
|
||||
@@ -0,0 +1,105 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [develop, main, contrib]
|
||||
pull_request:
|
||||
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:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
- run: npm ci
|
||||
- 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'
|
||||
# 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
|
||||
@@ -0,0 +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).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
push-github:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # full history + tags for a clean push
|
||||
- name: Push main + tags to GitHub
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
||||
run: |
|
||||
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
|
||||
fi
|
||||
@@ -0,0 +1,107 @@
|
||||
name: Release → npmjs
|
||||
|
||||
# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable
|
||||
# package to npmjs via OIDC **Trusted Publishing** — no long-lived token. Requires a trusted
|
||||
# publisher configured on npmjs for this package (org Expressive-Tea, repo green-tea,
|
||||
# workflow release.yml). npm also attaches build provenance automatically.
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
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
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
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`.
|
||||
- uses: denoland/setup-deno@v2
|
||||
with:
|
||||
deno-version: v2.x
|
||||
# Gate both registries before either one ships. JSR checks things npm never looks at — slow
|
||||
# types, module analysis — and learning about them after npm has published leaves the tag
|
||||
# half-shipped. Seconds, against a failure mode with no clean recovery.
|
||||
- run: deno publish --dry-run
|
||||
- name: Publish to npmjs
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
|
||||
echo "$VERSION under dist-tag: $TAG"
|
||||
# Skip rather than fail when the version is already up. A step after this one can fail —
|
||||
# the dist-tag move below does — and a re-run of the job has to be able to finish the
|
||||
# remaining work instead of dying on a duplicate npm rejects anyway.
|
||||
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
|
||||
echo "npm already has $VERSION"
|
||||
else
|
||||
npm publish --access public --tag "$TAG"
|
||||
fi
|
||||
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
|
||||
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
|
||||
# failure *after* it would cost a version number permanently. Version and entry points come
|
||||
# from deno.json, which `test/package-metadata.test.ts` pins to package.json — JSR has no
|
||||
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
|
||||
# id-token npm just used; the package is linked to this repository on jsr.io.
|
||||
- name: Publish to JSR
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
PKG=${PKG#@}
|
||||
# 404 until the version exists — and it stays 404 for a package with no versions yet, which
|
||||
# is the state this repository is actually in, so the guard must not read that as an error.
|
||||
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
|
||||
echo "JSR already has $VERSION"
|
||||
else
|
||||
deno publish
|
||||
fi
|
||||
# `latest` is what a bare `npm install @green-tea/core` resolves to, and while there is no
|
||||
# stable release the docs promise it is the newest beta. `npm publish --tag beta` sets exactly
|
||||
# one tag, so `latest` has to be moved separately — and `npm dist-tag` cannot use Trusted
|
||||
# Publishing, whose OIDC exchange lives only inside `npm publish`. So we run that same exchange
|
||||
# by hand (id-token → short-lived npm token) rather than keep a long-lived token in a secret for
|
||||
# one command. Last on purpose: both registries already have the version, and a dist-tag is the
|
||||
# only thing here that can be redone. If this step fails, the release is out but `latest` is
|
||||
# stale — recover with `npm dist-tag add @green-tea/core@<version> latest`.
|
||||
- name: Point `latest` at this release while no stable exists
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
case "$VERSION" in
|
||||
*-*) ;;
|
||||
*) echo "$VERSION is stable — npm publish already put it on latest"; exit 0 ;;
|
||||
esac
|
||||
# A stable release owns `latest` for good; a beta published afterwards must never drag it
|
||||
# backwards, so the newest-beta rule applies only until the first stable exists.
|
||||
# Read the list first so a failed lookup fails the step, rather than reading as "no stable
|
||||
# exists" and moving `latest` backwards on the strength of a network error.
|
||||
VERSIONS=$(npm view "$PKG" versions --json)
|
||||
if node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
|
||||
echo "a stable version exists — leaving latest where it is"; exit 0
|
||||
fi
|
||||
URL=$(node -p "const u=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);u.searchParams.set('audience','npm:registry.npmjs.org');u.href")
|
||||
ID_TOKEN=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$URL" \
|
||||
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).value")
|
||||
echo "::add-mask::$ID_TOKEN"
|
||||
NODE_AUTH_TOKEN=$(curl -fsS -X POST -H "Authorization: Bearer $ID_TOKEN" \
|
||||
"https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/$(node -p "encodeURIComponent(process.env.PKG)")" \
|
||||
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).token")
|
||||
echo "::add-mask::$NODE_AUTH_TOKEN"
|
||||
export NODE_AUTH_TOKEN
|
||||
npm dist-tag add "$PKG@$VERSION" latest
|
||||
@@ -0,0 +1,40 @@
|
||||
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 versions are intentionally mutable: an existing prerelease is removed before
|
||||
# publishing the updated release candidate under the same version.
|
||||
on:
|
||||
push:
|
||||
branches: ['release/**']
|
||||
|
||||
jobs:
|
||||
publish-stg:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
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
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
||||
run: |
|
||||
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||
VER=$(node -p "require('./package.json').version")
|
||||
case "$VER" in
|
||||
*-*) ;;
|
||||
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
||||
esac
|
||||
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
|
||||
npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg
|
||||
+11
@@ -10,3 +10,14 @@ coverage/
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
|
||||
|
||||
# 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,8 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always"
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for AI coding assistants working in this repository. Claude Code, Codex, Cursor and anything else that reads this file.
|
||||
|
||||
If you are an assistant: a person reads every line of what you produce before it lands, and the person submitting it signs off on it. Make that reading worth their time — leave the reasoning visible, don't quietly widen the scope you were asked for, and say what you were unsure about instead of smoothing over it. The "Working with AI assistance" section of `CONTRIBUTING.md` applies to your output.
|
||||
|
||||
## What this is
|
||||
|
||||
`@green-tea/core` — a type-safe HTTP framework where the API is a dependency graph rather than a middleware chain. You declare what each step needs and provides; the framework computes execution order, fails at boot if something is missing, and can print the whole pipeline. Runs on Node, Deno, Bun and the edge from one codebase.
|
||||
|
||||
**Hard constraint: one runtime dependency.** `reflect-metadata`, and nothing else. `busboy` and `ws` are peer dependencies. Anything that would add a third belongs in a plugin, not in core.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
npm run lint # eslint
|
||||
npm run format:check # prettier, src/**/*.ts only
|
||||
npm run typecheck # must be clean; includes the compile-time-guarantee type test
|
||||
npm test # vitest
|
||||
npm run build # tsup
|
||||
npm run complexity:check
|
||||
|
||||
npm run test:deno # the other runtimes are NOT covered by `npm test`
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Run the first four before proposing anything as finished. The runtime suites stay separate commands on purpose — a change to shared code that passes `npm test` may still be broken on Deno or Bun — but they are no longer optional: CI runs all three on every push and each one gates a merge. Run them yourself for anything touching `src/http/`, the adapters, or `src/mesh/`, rather than finding out from CI.
|
||||
|
||||
## Two forges
|
||||
|
||||
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and release tags, nothing else.
|
||||
|
||||
```
|
||||
feature/* → develop → main → [promote.yml] → GitHub main
|
||||
↑ ↓
|
||||
lead dev GitHub contrib ← external PRs
|
||||
```
|
||||
|
||||
- **Gitea `develop`** — active development.
|
||||
- **Gitea `main`** — staging. Merging here publishes nothing; only a `v*` tag publishes.
|
||||
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
|
||||
- **`contrib`** — exists on *both* forges. Where outside contributions land.
|
||||
|
||||
`develop` and `main` on Gitea have direct push disabled with an empty whitelist, so nobody can push to them, admins included. Advance them by opening a PR and merging it.
|
||||
|
||||
## Procedure
|
||||
|
||||
**Promotions are fast-forward-only.** `develop → main` merges with Gitea's fast-forward-only style, so `main` becomes an exact copy of `develop` and no commit is ever born on `main`. This is not a preference: merge-style promotions created seven of the ten commits of drift that had to be cleaned up in August 2026, because each one lived on `main` and never travelled back. Release boundaries are marked by `v*` tags, not by promotion commits.
|
||||
|
||||
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
|
||||
|
||||
**Diagnosing "this branch is ahead of main".** Usually it is pre-rebase duplication, not unmerged work: the same content under different SHAs, because contributions are rebased on their way into `develop`. Confirm before acting:
|
||||
|
||||
```bash
|
||||
git diff <branch> <main> -- <suspect file> # empty means the content is already in main
|
||||
```
|
||||
|
||||
Merging such a branch to "recover" the commits duplicates the work and drags stale history along.
|
||||
|
||||
**External contributions.** They arrive on GitHub `contrib`. Merge the pull request there, mirror that branch to Gitea, then open a `contrib → develop` pull request and merge it. Merge rather than rebase: because promotions are fast-forward-only, `develop` and `main` are the same commit, so there is no main-only history for a merge to drag in. Rebasing would rewrite the contributor's SHAs for no gain and push `contrib` out of `main`'s ancestry, which then costs a force-push at reset time. Merging keeps their commits reaching `main` under their own name and hash.
|
||||
|
||||
The exception is a `hotfix/*`, which lands on `main` without passing through `develop` and leaves the two out of step. Back-merge before taking a contribution through, or rebase that one and accept the force-push. If you do rebase, take the commit range from the pull request itself and never "everything since main": if a second contributor branched from `contrib` after the first one merged, the broad range sweeps up work that isn't theirs.
|
||||
|
||||
**After every promotion, reset *both* `contrib` branches to `main`.** GitHub's is where external work lands; Gitea's is its mirror, and the easy one to forget because nothing there refuses the push. Normally this is an ordinary fast-forward, since `contrib` is already inside `main`'s history. It only needs a force-push when SHAs were rewritten on the way in — and GitHub then refuses it even for admins, so that branch's protection has to be lifted and restored around the reset.
|
||||
|
||||
A conflict against unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve.
|
||||
|
||||
## Releasing
|
||||
|
||||
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
|
||||
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
|
||||
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
|
||||
nowhere is worse than no heading at all, because the next reader believes it.
|
||||
|
||||
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
|
||||
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
|
||||
two contradictory things — that beta.1 was released, and that everything in it was not.
|
||||
|
||||
So the order is: everything merged and promoted → **close the section with the release date** → tag →
|
||||
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
|
||||
number feels.
|
||||
|
||||
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
|
||||
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
||||
A version number is a plan; a changelog heading is a receipt.
|
||||
|
||||
## CI
|
||||
|
||||
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
|
||||
|
||||
**The forges disagree about where workflows come from.** GitHub reads `pull_request` workflows from the base branch, so a workflow fix cannot validate itself and must reach the base before it gates anything. Gitea reads from the head. Likewise, `continue-on-error` steps report as `success` on GitHub, hiding the advisory in the log, but as `failure` with the job still green on Gitea.
|
||||
|
||||
GitHub does not run workflows on fork pull requests until a maintainer approves them. A contributor's first push may sit with no checks at all.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Conventional Commits, focused on the *why*. Every commit signed off (`git commit -s`) — the project uses a DCO, and unsigned commits are rejected. No AI co-authoring attribution.
|
||||
- Comments carry reasoning the code cannot show. When editing a block, keep them; if one explains an ordering or a version floor, it is load-bearing.
|
||||
- A new option or method on a public interface has to change `src/app/types.ts` too. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
|
||||
- Behaviour that differs between runtimes must be explicit. An "unavailable here" is fine; silently accepting an option that does nothing is a bug.
|
||||
- New public API needs a note in `README.md` **and a companion pull request to the documentation repository**, [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) — separate, because a pull request cannot span two repositories. Since the split, nothing here imports those pages and nothing fails when they disagree with this code — the CI job that used to build them is gone. That makes this the only thing standing between a rename and a guide that quietly documents a version nobody can install.
|
||||
+285
-10
@@ -3,14 +3,271 @@
|
||||
All notable changes to `@green-tea/core` are documented here.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
green-tea uses calendar versioning: `YY.MM.PATCH`.
|
||||
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]
|
||||
|
||||
Beta on the road to a release candidate. No published release yet; the
|
||||
version below is a placeholder until the API freeze.
|
||||
## [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 ▸
|
||||
catch-all; matching remains a linear scan.
|
||||
- **`@Head` and `@Options` route decorators**, explicit-handler priority, buffered-GET HEAD fallback,
|
||||
and automatic `204` OPTIONS responses with deterministic `Allow` ordering. GET implies HEAD and
|
||||
every existing path implies OPTIONS; streaming GET routes do not become implicit HEAD routes.
|
||||
- **OpenAPI route constraints and methods:** constrained path params emit `schema.pattern`, and
|
||||
explicitly declared HEAD/OPTIONS handlers appear as operations without inventing automatic ones.
|
||||
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
|
||||
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
||||
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
||||
File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere.
|
||||
- **`app.fetch(request): Promise<Response>`** — a Web-Standards handler so the
|
||||
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API.
|
||||
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno.
|
||||
- **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
|
||||
(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.
|
||||
- **`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
|
||||
connects the teapots and splices their scopes in; on every other app it is a no-op, so
|
||||
`await app.ready()` before `inspect()`/`graph()`/`explain()` works against either kind without
|
||||
knowing which you were handed. It does **not** boot providers: resolving the graph and being
|
||||
ready to serve are different things, and drawing a diagram should not open your database
|
||||
connections. Serving boots them too and shares the same memoized step.
|
||||
|
||||
- **Mesh heartbeat** (`mesh.heartbeatMs`, default 15s): each teacup pings its teapots and closes a
|
||||
link after two unanswered rounds, so a half-open connection surfaces as an immediate 503 rather
|
||||
than every request paying `timeoutMs` first. Ping/pong are mesh frames, not WebSocket protocol
|
||||
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
|
||||
adapters, retaining configured security/CORS headers. `/path` and `/path/` remain equivalent.
|
||||
- Ambiguous same-method route shapes now fail at boot with both declarations named. Effective-shape
|
||||
checks also cover remote mesh conflicts and local routes that shadow a remote export.
|
||||
- HEAD responses always suppress the body while preserving handler status and headers; Fetch
|
||||
responses also avoid constructing forbidden bodies for `204`, `205`, and `304` statuses.
|
||||
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
|
||||
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
||||
not only the Node `app.listen()` path.
|
||||
- **A teapot with a live control channel could never shut down.** Mesh control connections were
|
||||
not registered with the stream registry, so `server.close()` waited on a connected teacup that
|
||||
had no reason to hang up, and `app.close()` never resolved.
|
||||
- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs`
|
||||
(30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait
|
||||
bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and
|
||||
a slow one are different operational stories, and neither is "this service broke".
|
||||
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
||||
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
|
||||
documented plugin API. All transports now run their steps through one path.
|
||||
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
|
||||
both teapots, instead of silently serving whichever connected first and leaving the other dead.
|
||||
There is no load balancing to fall back on, so green-tea will not pick for you.
|
||||
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
|
||||
override a teapot — but a silently shadowed export used to look like a broken teapot.
|
||||
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
|
||||
(every Deno/Bun deployment) no longer leaks its teapot connections.
|
||||
- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot
|
||||
before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke
|
||||
first lost those frames — for mesh, that was the handshake itself.
|
||||
- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits
|
||||
`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.
|
||||
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
||||
call no longer re-runs provider factories or their side effects.
|
||||
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
||||
`WsRequest` (`{ url, headers, protocol, ip }`) instead of the Node
|
||||
`http.IncomingMessage`, so it works the same across Node and Deno. Node-only
|
||||
fields such as `req.socket` / `req.rawHeaders` are no longer available on
|
||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||
instead — all still provided.
|
||||
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
||||
(`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
|
||||
`AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
|
||||
fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
|
||||
still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` to stream — a return value no longer
|
||||
changes a route's wire contract.
|
||||
|
||||
## [26.7.0-beta.0] - 2026-07-07
|
||||
|
||||
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
|
||||
@@ -19,10 +276,18 @@ version below is a placeholder until the API freeze.
|
||||
[Standard Schema](https://standardschema.dev) (zod / valibot / arktype); the
|
||||
parsed value is passed to the handler, invalid input returns `422` with
|
||||
per-field issues. Core stays dependency-free.
|
||||
- **Body parsing** — JSON, `application/x-www-form-urlencoded`, and
|
||||
`multipart/form-data` file uploads (`@body()` → `{ fields, files }`), with a
|
||||
configurable repeated-field policy (`bodyDuplicates`, per-route overridable)
|
||||
and a `maxParts` DoS bound.
|
||||
- **Body parsing** — JSON and `application/x-www-form-urlencoded` out of the
|
||||
box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via
|
||||
the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency
|
||||
(a multipart request without it returns `501`), with a configurable
|
||||
repeated-field policy (`bodyDuplicates`, per-route overridable) and a
|
||||
`maxParts` DoS bound.
|
||||
- **Routing** — `:name*` catch-all params, specificity-based precedence
|
||||
(static ▸ `:param` ▸ catch-all, independent of registration order), and
|
||||
`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`.
|
||||
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
|
||||
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
|
||||
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
|
||||
@@ -30,11 +295,21 @@ version below is a placeholder until the API freeze.
|
||||
- **Operational hardening** — request body/size limits (`413`), request and
|
||||
keep-alive timeouts, and `app.close()` graceful shutdown (drains in-flight
|
||||
requests, closes live streams and mesh links).
|
||||
- **Visible degradation** — optional providers that fail at boot are
|
||||
summarized on `listen()` and queryable via `app.degraded()`, instead of a
|
||||
silent warning.
|
||||
- **Testing ergonomics** — `createApp({ overrides })` swaps any provider/step
|
||||
by token in one line.
|
||||
- **Mesh (walking skeleton)** — `teapot`/`teacup` distributed dependency
|
||||
injection over a secret-gated WebSocket control channel. Experimental.
|
||||
- **Mesh (alpha, walking skeleton)** — `teapot`/`teacup` distributed dependency
|
||||
injection over a secret-gated WebSocket control channel. Gated behind
|
||||
`experimental: true`; `createApp` throws if `mesh` is configured without it.
|
||||
- **Packaging** — dual **ESM + CommonJS** builds behind an `exports` map, with
|
||||
matching type declarations; one runtime dependency (`reflect-metadata`),
|
||||
`ws` and `busboy` optional peers.
|
||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||
|
||||
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/commits/develop
|
||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...main
|
||||
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||
@@ -0,0 +1,3 @@
|
||||
# CLAUDE.md
|
||||
|
||||
See [AGENTS.md](./AGENTS.md). It is the same guidance, kept in one place so the two files cannot drift apart.
|
||||
@@ -0,0 +1,89 @@
|
||||
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **compliance@expressive-tea.io**. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
If you would rather write to a named person than to an address, the project lead reads
|
||||
diego.resendez@expressive-tea.io. Reports about a maintainer, including the project lead,
|
||||
should go to compliance@expressive-tea.io, which is not maintained by the project team.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
|
||||
+112
-4
@@ -2,6 +2,36 @@
|
||||
|
||||
Thanks for your interest. green-tea is open source, but not anyone can push directly — contributions land through reviewed pull/merge requests with a **DCO sign-off**.
|
||||
|
||||
## Where to send your changes
|
||||
|
||||
Development happens on a private Gitea instance. The GitHub repository is a downstream mirror: it receives `main` and release tags, and nothing else. Which branch you target depends on where you are.
|
||||
|
||||
**From GitHub, if you are an outside contributor:** open your pull request against **`contrib`**. Not `main`. `main` on GitHub is a mirror of released code, and merging into it puts the two forges out of sync and breaks the next release push. A maintainer reviews on `contrib` and then carries your commits upstream into Gitea's `develop`, with your authorship and your sign-off intact.
|
||||
|
||||
**From Gitea, if you have access:** follow the branch model below.
|
||||
|
||||
### Worked example
|
||||
|
||||
```bash
|
||||
# fork Expressive-Tea/green-tea on GitHub, then
|
||||
git clone git@github.com:<you>/green-tea.git
|
||||
cd green-tea
|
||||
git remote add upstream https://github.com/Expressive-Tea/green-tea.git
|
||||
git fetch upstream
|
||||
|
||||
# branch from contrib, not from main
|
||||
git checkout -b fix/close-timeout upstream/contrib
|
||||
|
||||
# ... make the change, add a test ...
|
||||
|
||||
git commit -s -m "fix: add a timeout to app.close()"
|
||||
git push origin fix/close-timeout
|
||||
```
|
||||
|
||||
Then open the pull request with **`contrib`** as the base branch.
|
||||
|
||||
`contrib` tracks released code, so it is reset to `main` after each release. If your branch has been open across one, rebase onto the new `contrib` before pushing again.
|
||||
|
||||
## Developer Certificate of Origin (DCO)
|
||||
|
||||
We use the [Developer Certificate of Origin](./DCO) instead of a CLA. It's a lightweight, per-commit affirmation that you have the right to submit your work under the project's license. No copyright assignment, no paperwork.
|
||||
@@ -26,6 +56,34 @@ To sign off a range you forgot to sign:
|
||||
git rebase --signoff <base>
|
||||
```
|
||||
|
||||
Or, for the commit you just made:
|
||||
|
||||
```bash
|
||||
git commit --amend -s
|
||||
git push --force-with-lease
|
||||
```
|
||||
|
||||
## Working with AI assistance
|
||||
|
||||
Use one if it helps. There is no permission to ask for and nothing to declare.
|
||||
|
||||
What we do ask is that you read what it hands you before it becomes a pull request. Every line that lands here is reviewed by a person, by hand, and usually that person is one person. A diff its own author hasn't read moves that work onto them, and turns review into proofreading — which is the thing review is worst at.
|
||||
|
||||
So go through the diff the way you would go through a stranger's, because that is what it is. If you can't say why a line is there, it isn't ready to send. That's the whole of it.
|
||||
|
||||
**What assistants tend to get wrong here in particular** — worth checking before you push:
|
||||
|
||||
- They add dependencies. Core has one runtime dependency, and that is a design constraint rather than an oversight.
|
||||
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` does not cover them.
|
||||
- They delete comments they read as redundant. In this codebase a comment usually carries reasoning the code can't show on its own.
|
||||
- They skip the test.
|
||||
|
||||
**Where you're unsure, say so** — not as a disclosure, as a pointer. "I'm not confident about the Deno path here" tells a reviewer where to spend their attention, and that is worth more to them than a pull request that merely looks clean.
|
||||
|
||||
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the work under this project's license, and that stays true however the text was produced.
|
||||
|
||||
If your assistant reads repository instructions, `AGENTS.md` has the conventions and the architecture notes.
|
||||
|
||||
## Branch model (GitFlow)
|
||||
|
||||
- `main` — production-ready, protected. No direct pushes.
|
||||
@@ -33,6 +91,7 @@ git rebase --signoff <base>
|
||||
- `feature/<name>` — branch from `develop`.
|
||||
- `hotfix/<name>` — branch from `main`.
|
||||
- `release/<version>` — release stabilization.
|
||||
- `contrib` — GitHub only. Where outside contributions land before a maintainer moves them to `develop`.
|
||||
|
||||
`main` and `develop` are protected: they require a reviewed MR and signed-off commits. (Branch protection is configured on the git server, not in this repo.)
|
||||
|
||||
@@ -40,17 +99,66 @@ git rebase --signoff <base>
|
||||
|
||||
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`, `chore:`, `docs:`, `test:`, `refactor:`. Focus the message on the *why*. Do not add AI co-authoring attribution.
|
||||
|
||||
## Before you open an MR
|
||||
## Local setup
|
||||
|
||||
Node 18 or newer, which is what `engines` requires and what CI runs.
|
||||
|
||||
```bash
|
||||
npm test # all tests must pass
|
||||
npm install
|
||||
```
|
||||
|
||||
That does one thing worth knowing about: the `prepare` script points `core.hooksPath` at
|
||||
`.githooks/`, which installs a pre-commit gate. The gate formats and lint-fixes your staged
|
||||
sources automatically, then refuses the commit if `npm run lint` or `npm run complexity:check`
|
||||
fails. It is there so CI tells you nothing you couldn't have heard locally. Confirm it took:
|
||||
|
||||
```bash
|
||||
git config core.hooksPath # should print .githooks
|
||||
```
|
||||
|
||||
If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you install with
|
||||
something other than npm, check this before your first commit rather than after.
|
||||
|
||||
`npm test` runs the Node suite under Vitest. The other three runtimes have their own commands
|
||||
and their own toolchains, and none of them run in CI:
|
||||
|
||||
```bash
|
||||
npm run test:deno # needs deno
|
||||
npm run test:bun # needs bun
|
||||
npm run test:edge # Miniflare
|
||||
```
|
||||
|
||||
You are not expected to install all three to fix a typo. You are expected to run the one your
|
||||
change touches, and to say in the pull request which ones you ran.
|
||||
|
||||
## Before you open a pull request
|
||||
|
||||
Run what CI runs:
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format:check
|
||||
npm run typecheck # must be clean — this includes the compile-time-guarantee type test
|
||||
npm test # all tests must pass
|
||||
npm run complexity:check
|
||||
npm run build
|
||||
```
|
||||
|
||||
- Write tests for new behavior (TDD welcome). We use Vitest.
|
||||
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
|
||||
- Keep runtime dependencies at zero beyond `reflect-metadata`.
|
||||
- New public API needs a doc note in `README.md`.
|
||||
- A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package.
|
||||
- New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page.
|
||||
- If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not.
|
||||
|
||||
On GitHub, workflows do not run on pull requests from forks until a maintainer approves them, so your first push may sit without any checks for a while. That is not a rejection.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
Open an issue with a minimal reproduction: green-tea version, Node version, and the smallest module/route that shows the problem.
|
||||
Open an issue with a minimal reproduction: green-tea version, runtime and version, and the smallest module/route that shows the problem.
|
||||
|
||||
**Except for security.** If what you found is exploitable, do not open an issue — an issue is world-readable the moment you press the button. Email security@expressive-tea.io or use the [private advisory form](https://github.com/Expressive-Tea/green-tea/security/advisories/new). [`SECURITY.md`](./SECURITY.md) has the scope and what to expect back.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
By taking part here you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md), which is the Contributor Covenant 2.1. Reports go to compliance@expressive-tea.io.
|
||||
@@ -1,43 +1,152 @@
|
||||
# 🍵 green-tea
|
||||
<p align="center">
|
||||
<img src="./assets/logo.png" width="112" alt="Green Tea" />
|
||||
</p>
|
||||
|
||||
> A calm, type-safe HTTP framework for Node. Your API is an explicit **dependency graph** you can see, slice, and trust — not a mutable bag threaded through positional middleware.
|
||||
<h1 align="center">Green Tea.</h1>
|
||||
|
||||
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata` (`ws` is an optional peer, only for WebSocket/mesh).
|
||||
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core reflect-metadata
|
||||
```
|
||||
<p align="center">
|
||||
<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>
|
||||
|
||||
---
|
||||
|
||||
## The problem
|
||||
|
||||
```js
|
||||
const user = req.user;
|
||||
```
|
||||
|
||||
It compiles. TypeScript is happy. And it's a prayer — `req.user` exists only if some middleware ran before this handler, which depends on where the router got mounted, which line `app.use()` sits on, and whether a package you installed last sprint quietly inserted itself into the middle of your chain.
|
||||
|
||||
So you keep the whole request in your head: what ran, what's on `req` by now, what order things fire in, which plugin deleted your body parser. That bookkeeping is where the bugs live, and no test or type catches them, because nothing is *wrong* — the code is correct and the app is still broken.
|
||||
|
||||
## The idea
|
||||
|
||||
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That mental bookkeeping is where bugs live.
|
||||
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing.
|
||||
|
||||
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`.
|
||||
- Order is **derived** from your dependencies, never maintained by hand.
|
||||
- Boot **fails loudly** when nothing provides a key, so you never serve `undefined`.
|
||||
- A route runs **only** the steps its handler actually depends on.
|
||||
- `app.explain('/users/:id')` prints the whole chain. Onboarding is reading, not archaeology.
|
||||
|
||||
Less to hold in your head. That's the tea.
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core@beta reflect-metadata
|
||||
```
|
||||
|
||||
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
|
||||
|
||||
```bash
|
||||
npm install ws # WebSocket routes (@Ws) and mesh
|
||||
npm install busboy # multipart/form-data file uploads
|
||||
```
|
||||
|
||||
## What's different — and why it matters
|
||||
|
||||
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
|
||||
- **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. *Why it matters:* onboarding, debugging, and audits are reading, not archaeology. (NestJS puts this behind a paid Devtools plan.)
|
||||
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||
- **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.
|
||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe), `scope.add(...)` (extend its own scope) and `onShutdown(...)` (release what it opened). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
|
||||
## Batteries included — still one dependency
|
||||
## Who does the work?
|
||||
|
||||
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
|
||||
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
|
||||
|
||||
Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app.
|
||||
|
||||
green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
|
||||
|
||||
| Declare | Direction | Transport | Reach for it when |
|
||||
|---|---|---|---|
|
||||
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
||||
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
|
||||
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
|
||||
|
||||
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
|
||||
|
||||
- **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
|
||||
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
|
||||
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
|
||||
|
||||
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
|
||||
|
||||
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
|
||||
|
||||
```typescript
|
||||
@Route('/live')
|
||||
class Live {
|
||||
@Sse('/prices') // one iterable out — each yield is an event
|
||||
prices() {
|
||||
return (async function* () {
|
||||
while (true) { yield { btc: await getPrice() }; await sleep(1000); }
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/echo') // duplex — consume @inbound, return the outbound stream
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
||||
|
||||
## What the foundation already carries
|
||||
|
||||
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.
|
||||
- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
|
||||
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
|
||||
- **Real body parsing.** JSON, urlencoded, and `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), size-capped (`413`) against DoS.
|
||||
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything.
|
||||
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
||||
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
@@ -58,10 +167,11 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
|
||||
| **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** |
|
||||
| **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators |
|
||||
| **See the pipeline** | read the code | read the code | paid Devtools | `inspect` | **`explain` / `graph` / `/__graph__` — free** |
|
||||
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same primitive |
|
||||
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
|
||||
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
|
||||
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
|
||||
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) |
|
||||
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
|
||||
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
|
||||
|
||||
### Read it as a story
|
||||
|
||||
@@ -128,32 +238,85 @@ The handler signature declares exactly what it wants — in any order, nothing m
|
||||
| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
|
||||
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
|
||||
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
|
||||
| `@headers(...)` | request headers | `()` · `('authorization')` · `(schema)` |
|
||||
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
|
||||
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
|
||||
|
||||
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
|
||||
|
||||
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. The first serving call (`fetch`, `upgrade`, or `listen`) prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
|
||||
|
||||
## Routing
|
||||
|
||||
Patterns match by segment: static, constrained params such as `:id(\d+)`, plain `:param`, and a trailing `:name*` **catch-all**. The most specific wins (static ▸ constrained ▸ plain param ▸ catch-all), and ambiguous same-method shapes fail at boot instead of depending on registration order.
|
||||
|
||||
```typescript
|
||||
@Get('/users/:id(\\d+)') // /users/42
|
||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||
```
|
||||
|
||||
`@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
|
||||
|
||||
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
|
||||
|
||||
## Two layers
|
||||
|
||||
1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
|
||||
2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
|
||||
|
||||
## Why legacy decorators
|
||||
|
||||
green-tea uses **legacy** (experimental) decorators — you set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
|
||||
|
||||
The framework's argument injection (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators** — and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so a handler like `handler(@param('id') id: string)` is only expressible with legacy decorators.
|
||||
|
||||
"Stage 3" also means *not finalized*: the proposal can still change before engines ship it. We track it, and if parameter injection ever gets a viable standard path we'll revisit. Until then, legacy decorators are the right tool for this API — not a shortcut. (We don't rely on `emitDecoratorMetadata`/`design:type` reflection; argument positions are recorded explicitly, so this is the only legacy surface we depend on.)
|
||||
|
||||
## Honest scope
|
||||
|
||||
green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. green-tea's mesh is a walking skeleton — distributed DI works, but discovery, load-balancing, and failover are not built yet. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
|
||||
green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
|
||||
|
||||
**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.
|
||||
|
||||
**Observability is a contract, not an integration.** Core emits a correlated lifecycle event stream — every request gets an id (an incoming `x-request-id` is adopted, not replaced), every event carries it, and each step reports its own duration. `createApp({ logger })` takes any logger; the default writes structured JSON, or a readable line on a TTY. Nothing in core writes to `console`, which is enforced by a lint rule rather than a promise. `createApp({ logRequests: true })` logs a line per request, off by default.
|
||||
|
||||
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
|
||||
|
||||
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||
|
||||
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||
|
||||
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
|
||||
|
||||
## Docs & development
|
||||
|
||||
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
|
||||
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
|
||||
- **[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
|
||||
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/
|
||||
npm run build # emit dist/ (tsup: dual ESM + CJS)
|
||||
npm run bench # regenerate BENCHMARKS.md
|
||||
```
|
||||
|
||||
`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`.
|
||||
@@ -161,11 +324,17 @@ npm run bench # regenerate BENCHMARKS.md
|
||||
- ✅ **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.
|
||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
|
||||
- ✅ **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
|
||||
|
||||
green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped; breaking changes are called out in the [CHANGELOG](./CHANGELOG.md).
|
||||
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
|
||||
|
||||
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.8.0-beta.0`) and publish under the npm `beta` dist-tag. Until the first stable release there is nothing else to install, so `latest` tracks the newest beta too — `npm install @green-tea/core` and `@green-tea/core@beta` resolve to the same version. Install with the explicit `@beta` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. The API can still change between betas.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+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,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
|
||||
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="currentColor" transform="translate(501,80)"/>
|
||||
|
||||
<g stroke="currentColor" stroke-width="12" stroke-linecap="round" fill="none">
|
||||
<path d="M277 312 Q255 263 221 247"/>
|
||||
<path d="M338 276 Q382 305 393 340"/>
|
||||
<path d="M366 258 Q348 214 317 200"/>
|
||||
<path d="M443 186 Q469 204 475 224"/>
|
||||
</g>
|
||||
<g fill="currentColor">
|
||||
<circle cx="221" cy="247" r="13"/>
|
||||
<circle cx="393" cy="340" r="13"/>
|
||||
<circle cx="475" cy="224" r="11"/>
|
||||
</g>
|
||||
<circle cx="317" cy="200" r="18" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
|
||||
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
|
||||
|
||||
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
|
||||
<path d="M277 312 Q255 263 221 247"/>
|
||||
<path d="M338 276 Q382 305 393 340"/>
|
||||
<path d="M366 258 Q348 214 317 200"/>
|
||||
<path d="M443 186 Q469 204 475 224"/>
|
||||
</g>
|
||||
<g fill="#5FB88A">
|
||||
<circle cx="221" cy="247" r="13"/>
|
||||
<circle cx="393" cy="340" r="13"/>
|
||||
<circle cx="475" cy="224" r="11"/>
|
||||
</g>
|
||||
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
@@ -12,7 +12,7 @@ app.post('/validate', {
|
||||
if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
|
||||
return { email: b.email };
|
||||
});
|
||||
app.listen({ port: 0 }, (err, addr) => {
|
||||
app.listen({ port: 0, host: '0.0.0.0' }, (err, addr) => {
|
||||
if (err) { console.error(err); process.exit(1); }
|
||||
console.log(`READY ${Number(new URL(addr).port)}`);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
import { serveBun } from '../../dist/bun.mjs';
|
||||
|
||||
// Same BenchModule as green-tea.ts (Node), served via Bun.serve instead of app.listen.
|
||||
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 });
|
||||
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' });
|
||||
console.log(`READY ${server.port}`);
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
import { serveDeno } from '../../dist/deno.mjs';
|
||||
|
||||
// Same BenchModule as green-tea.ts (Node), served via Deno.serve instead of app.listen.
|
||||
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 });
|
||||
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
|
||||
@@ -9,7 +9,7 @@ async function main() {
|
||||
inst.disable('x-powered-by');
|
||||
inst.set('etag', false);
|
||||
const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
|
||||
await app.listen(0, '127.0.0.1');
|
||||
await app.listen(0, '0.0.0.0');
|
||||
const server = app.getHttpServer();
|
||||
server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
|
||||
console.log(`READY ${server.address().port}`);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { BenchModule } from './_nest-shared';
|
||||
async function main() {
|
||||
const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
|
||||
const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false });
|
||||
await app.listen(0, '127.0.0.1');
|
||||
await app.listen(0, '0.0.0.0');
|
||||
const server = app.getHttpServer();
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import express from 'express';
|
||||
|
||||
// Express counterpart: /chain/N runs N trivial middlewares before the handler —
|
||||
// the closest apples-to-apples to green-tea's N chained steps.
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
app.set('etag', false);
|
||||
|
||||
const mw = (_req: any, _res: any, next: any) => next();
|
||||
|
||||
function route(path: string, n: number): void {
|
||||
const chain = Array.from({ length: n }, () => mw);
|
||||
app.get(path, ...chain, (_req, res) => { res.json({ ok: 1 }); });
|
||||
}
|
||||
|
||||
route('/chain/0', 0);
|
||||
route('/chain/10', 10);
|
||||
route('/chain/25', 25);
|
||||
route('/chain/50', 50);
|
||||
route('/chain/75', 75);
|
||||
route('/chain/100', 100);
|
||||
|
||||
const server = app.listen(0, () => {
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
// 100 chained steps: s1..s100, each needs the previous. A route that @needs the Nth
|
||||
// pulls exactly N steps transitively — so /chain/100 runs the full 100-deep graph slice.
|
||||
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 = Array.from({ length: 100 }, (_, i) => makeStep(i + 1));
|
||||
|
||||
@Route('/chain')
|
||||
class Chain {
|
||||
@Get('/0') d0() { return { ok: 1 }; }
|
||||
@Get('/10') d10(@needs('s10') s: number) { return { s }; }
|
||||
@Get('/25') d25(@needs('s25') s: number) { return { s }; }
|
||||
@Get('/50') d50(@needs('s50') s: number) { return { s }; }
|
||||
@Get('/75') d75(@needs('s75') s: number) { return { s }; }
|
||||
@Get('/100') d100(@needs('s100') s: number) { return { s }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Chain] })
|
||||
class ScaleModule {}
|
||||
|
||||
const app = createApp({ modules: [ScaleModule], security: false });
|
||||
|
||||
async function main() {
|
||||
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,31 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.8.0-beta.1",
|
||||
"license": "MIT",
|
||||
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
|
||||
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
|
||||
// `@green-tea/core/bun` has to work whichever registry the reader installed from.
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./deno": "./src/deno.ts",
|
||||
"./bun": "./src/bun.ts",
|
||||
"./edge": "./src/edge.ts"
|
||||
},
|
||||
"publish": {
|
||||
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
|
||||
},
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"lib": ["deno.window", "deno.ns"]
|
||||
},
|
||||
"unstable": ["sloppy-imports"],
|
||||
"imports": {
|
||||
"http": "node:http",
|
||||
"https": "node:https",
|
||||
"crypto": "node:crypto",
|
||||
"events": "node:events",
|
||||
"stream": "node:stream"
|
||||
},
|
||||
"lint": { "exclude": ["dist", "node_modules"] }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"version": "5",
|
||||
"specifiers": {
|
||||
"jsr:@std/assert@*": "1.0.19",
|
||||
"jsr:@std/internal@^1.0.12": "1.0.14"
|
||||
},
|
||||
"jsr": {
|
||||
"@std/assert@1.0.19": {
|
||||
"integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
|
||||
"dependencies": [
|
||||
"jsr:@std/internal"
|
||||
]
|
||||
},
|
||||
"@std/internal@1.0.14": {
|
||||
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"packageJson": {
|
||||
"dependencies": [
|
||||
"npm:@eslint/js@^9.39.5",
|
||||
"npm:@nestjs/common@^11.1.28",
|
||||
"npm:@nestjs/core@^11.1.28",
|
||||
"npm:@nestjs/platform-express@^11.1.28",
|
||||
"npm:@nestjs/platform-fastify@^11.1.28",
|
||||
"npm:@stylistic/eslint-plugin@^5.10.0",
|
||||
"npm:@types/autocannon@^7.12.7",
|
||||
"npm:@types/busboy@^1.5.4",
|
||||
"npm:@types/express@^5.0.6",
|
||||
"npm:@types/node@^18.19.0",
|
||||
"npm:@types/ws@^8.18.1",
|
||||
"npm:autocannon@8",
|
||||
"npm:busboy@^1.6.0",
|
||||
"npm:cognitive-complexity-ts@~0.8.2",
|
||||
"npm:esbuild@0.27.2",
|
||||
"npm:eslint@^9.39.5",
|
||||
"npm:express@^5.2.1",
|
||||
"npm:fastify@^5.11.0",
|
||||
"npm:graphql@^16.9.0",
|
||||
"npm:miniflare@^4.20260730.0",
|
||||
"npm:prettier@^3.9.6",
|
||||
"npm:reflect-metadata@0.2.2",
|
||||
"npm:rxjs@^7.8.2",
|
||||
"npm:tsup@^8.5.1",
|
||||
"npm:tsx@^4.23.5",
|
||||
"npm:typescript-eslint@^8.65.0",
|
||||
"npm:typescript@^5.5.0",
|
||||
"npm:vite@^6.4.3",
|
||||
"npm:vitest@^3.2.7",
|
||||
"npm:ws@^8.21.1"
|
||||
],
|
||||
"overrides": {
|
||||
"find-my-way": "9.7.0",
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
# green-tea — Architecture
|
||||
|
||||
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
|
||||
> You declare *what* you need; the framework computes the order. The graph can extend in
|
||||
> **time** (streams) and across **machines** (mesh).
|
||||
|
||||
## The four layers
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph L3["#3 MESH — the graph crosses machines"]
|
||||
direction LR
|
||||
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
|
||||
end
|
||||
subgraph L2["#2 STREAMS — the graph emits over time"]
|
||||
sse["SSE / ndjson"]:::n
|
||||
ws["WebSocket duplex"]:::n
|
||||
end
|
||||
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
|
||||
sig["handler signature = dependency declaration"]:::n
|
||||
end
|
||||
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
|
||||
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
|
||||
end
|
||||
L3 --> L2 --> L15 --> L1
|
||||
classDef n fill:#f6f8fa,stroke:#aaa;
|
||||
```
|
||||
|
||||
## Building blocks
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Provider["@Provider\n(app scope · singleton)"]:::p
|
||||
Step["@Step\n(request scope · per call)"]:::s
|
||||
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
|
||||
Transformer["@Transformer\nvalue → ResponseShape"]:::t
|
||||
Container["Container.resolve()\nasync · transport-agnostic"]:::c
|
||||
Bus["Bus\nlifecycle events"]:::b
|
||||
|
||||
Provider --> Container
|
||||
Step --> Container
|
||||
Route --> Transformer
|
||||
Container -. "remote binding (mesh)" .-> Provider
|
||||
classDef p fill:#e7f5ff,stroke:#4dabf7;
|
||||
classDef s fill:#fff3bf,stroke:#f59f00;
|
||||
classDef r fill:#ebfbee,stroke:#40c057;
|
||||
classDef t fill:#f3f0ff,stroke:#7950f2;
|
||||
classDef c fill:#fff0f6,stroke:#e64980;
|
||||
classDef b fill:#f1f3f5,stroke:#868e96;
|
||||
```
|
||||
|
||||
## Request lifecycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant H as http.ts (transport)
|
||||
participant P as Pipeline
|
||||
participant G as Graph (providers/steps)
|
||||
participant T as Transformer
|
||||
|
||||
C->>H: HTTP request
|
||||
H->>H: matchRoute(method, path)
|
||||
H->>P: runPipeline(seed = req envelope)
|
||||
P->>G: providers (cached) + steps (topo order)
|
||||
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
|
||||
P->>P: handler(args resolved from ctx)
|
||||
alt returns a value
|
||||
P->>T: transformer → {status, headers, body}
|
||||
T-->>C: buffered response
|
||||
else returns an AsyncIterable
|
||||
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
|
||||
else @needs a remote token
|
||||
G-->>C: RPC to teapot, value spliced into ctx
|
||||
end
|
||||
```
|
||||
|
||||
## The unifying rule
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Q{"what does the handler return /\nwhere does a token live?"}
|
||||
Q -->|"a value"| A["buffered (transformer → JSON)"]
|
||||
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
|
||||
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
|
||||
```
|
||||
|
||||
One question — *"what produces this token and where does it live?"* — answers local DI,
|
||||
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
|
||||
**the graph is the product.**
|
||||
|
||||
## Mesh walking skeleton (spec #3)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph A["Node A — teapot"]
|
||||
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
|
||||
mc["control channel\n/__mesh__/control\n(secret-gated)"]
|
||||
end
|
||||
subgraph B["Node B — teacup"]
|
||||
bn["@needs('auth') with\nno local provider"]
|
||||
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
|
||||
end
|
||||
bn --> lk
|
||||
lk -- "hello + secret" --> mc
|
||||
mc -- "manifest {scopes, routes}" --> lk
|
||||
lk -- "rpc-req {id, kind, name, ctx}" --> mc
|
||||
mc -- "rpc-res {id, ok, result}" --> lk
|
||||
```
|
||||
|
||||
- **Provider exported → app scope** (resolved once via RPC, cached).
|
||||
- **Step exported → request scope** (RPC per request, carries the request envelope).
|
||||
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
|
||||
|
||||
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
|
||||
@@ -0,0 +1,170 @@
|
||||
# Router correctness and security beta design
|
||||
|
||||
**Date:** 2026-08-02
|
||||
**Target:** `26.8.0-beta.0`
|
||||
**Status:** Approved
|
||||
|
||||
## Goal
|
||||
|
||||
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
|
||||
|
||||
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
|
||||
|
||||
## Scope
|
||||
|
||||
This change includes:
|
||||
|
||||
- first-class `HEAD` and `OPTIONS` routes;
|
||||
- automatic `HEAD` fallback to `GET`;
|
||||
- automatic bare `OPTIONS` responses;
|
||||
- correct and deterministic `Allow` headers;
|
||||
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
|
||||
- route-pattern validation at boot;
|
||||
- safe parameter constraints such as `:id(\d+)`;
|
||||
- malformed URI handling as a client error;
|
||||
- duplicate and ambiguous route detection;
|
||||
- OpenAPI projection of constrained parameters;
|
||||
- dependency remediation for the root package and `website/`;
|
||||
- public documentation and changelog updates;
|
||||
- the `26.8.0-beta.0` package-version bump.
|
||||
|
||||
This change excludes:
|
||||
|
||||
- a radix-tree matcher;
|
||||
- arbitrary, unrestricted regular expressions;
|
||||
- manual publication, npm tags, or registry mutations;
|
||||
- mesh discovery, load balancing, and failover.
|
||||
|
||||
## Route semantics
|
||||
|
||||
### Path normalization
|
||||
|
||||
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
|
||||
|
||||
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
|
||||
|
||||
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
|
||||
|
||||
### Methods
|
||||
|
||||
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
|
||||
|
||||
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
|
||||
|
||||
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
|
||||
|
||||
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
|
||||
|
||||
### Pattern validation
|
||||
|
||||
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
|
||||
|
||||
- a catch-all outside the final segment;
|
||||
- empty parameter or catch-all names;
|
||||
- repeated parameter names in one pattern;
|
||||
- repeated internal slashes in declarations;
|
||||
- malformed constraints;
|
||||
- duplicate routes with the same method and effective pattern;
|
||||
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
|
||||
|
||||
Errors name the method, pattern, controller origin, and conflict when applicable.
|
||||
|
||||
### Segment constraints
|
||||
|
||||
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
|
||||
|
||||
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
|
||||
|
||||
Specificity remains deterministic:
|
||||
|
||||
1. static segment;
|
||||
2. constrained parameter;
|
||||
3. unconstrained parameter;
|
||||
4. catch-all.
|
||||
|
||||
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
|
||||
|
||||
## Architecture
|
||||
|
||||
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
|
||||
|
||||
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
|
||||
|
||||
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
|
||||
|
||||
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
|
||||
|
||||
## Error behavior
|
||||
|
||||
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
|
||||
|
||||
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
|
||||
|
||||
## Dependency remediation
|
||||
|
||||
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
|
||||
|
||||
The root update will prefer the smallest supported versions that close each advisory:
|
||||
|
||||
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
|
||||
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
|
||||
- Miniflare moves to its current compatible patch with fixed Sharp;
|
||||
- Fastify and compatible toolchain packages receive current patch/minor updates;
|
||||
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
|
||||
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
|
||||
|
||||
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
|
||||
|
||||
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
|
||||
|
||||
## Documentation
|
||||
|
||||
The change updates:
|
||||
|
||||
- the README routing section and roadmap;
|
||||
- the Routing guide;
|
||||
- the Decorators reference;
|
||||
- the OpenAPI guide where constrained parameters affect output;
|
||||
- the CHANGELOG and package version;
|
||||
- the Starlight 404 configuration that currently emits a build warning.
|
||||
|
||||
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
|
||||
|
||||
## Verification
|
||||
|
||||
The implementation adds unit and integration coverage for:
|
||||
|
||||
- explicit and implicit `HEAD`;
|
||||
- body suppression and header preservation;
|
||||
- explicit and automatic `OPTIONS`;
|
||||
- CORS-preflight precedence;
|
||||
- deterministic `Allow` values;
|
||||
- trailing slash equivalence and double-slash rejection;
|
||||
- invalid percent encoding;
|
||||
- route-declaration failures;
|
||||
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
|
||||
- OpenAPI path and `schema.pattern` output;
|
||||
- Node and Fetch parity;
|
||||
- mesh method serialization where relevant.
|
||||
|
||||
The release gate runs:
|
||||
|
||||
- root and website audits with zero known vulnerabilities;
|
||||
- the runtime-only root audit separately;
|
||||
- Node tests, typecheck, lint, format, complexity, and build;
|
||||
- Deno, Bun, and Edge suites when their runtimes are available;
|
||||
- documentation build without the current 404 warning;
|
||||
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
|
||||
- `npm pack --dry-run` to inspect the published artifact.
|
||||
|
||||
## CI and publication flow
|
||||
|
||||
Gitea remains the source of the release flow:
|
||||
|
||||
1. CI runs on `develop` and `main`.
|
||||
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
|
||||
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
|
||||
4. A promoted `v*` tag triggers GitHub's `release.yml`.
|
||||
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
|
||||
|
||||
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
|
||||
@@ -0,0 +1,679 @@
|
||||
# Router Security Beta Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
|
||||
|
||||
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
|
||||
|
||||
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Compile and validate route patterns
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/http/types.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
|
||||
**Step 1: Write failing compiler tests**
|
||||
|
||||
Add tests that establish the supported grammar and precedence:
|
||||
|
||||
```typescript
|
||||
describe('compilePattern', () => {
|
||||
it('compiles constrained params and gives them precedence over plain params', () => {
|
||||
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
|
||||
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
|
||||
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'/files/:rest*/tail',
|
||||
'/users/:',
|
||||
'/users/:id/:id',
|
||||
'/users//:id',
|
||||
'/users/:id((a+)+)',
|
||||
'/users/:id((?=a)a)',
|
||||
'/users/:id(\\1)',
|
||||
])('rejects invalid or unsafe pattern %s', (pattern) => {
|
||||
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
|
||||
|
||||
**Step 2: Run the focused test and confirm RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because `compilePattern` and constrained matching do not exist.
|
||||
|
||||
**Step 3: Implement the compiled representation**
|
||||
|
||||
In `src/http/router.ts`, add:
|
||||
|
||||
```typescript
|
||||
type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
| { kind: 'param'; name: string; constraint?: RegExp }
|
||||
| { kind: 'catchAll'; name: string };
|
||||
|
||||
export interface CompiledPattern {
|
||||
source: string;
|
||||
normalized: string;
|
||||
shape: string;
|
||||
segments: CompiledSegment[];
|
||||
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
|
||||
catchAll: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
|
||||
|
||||
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
|
||||
|
||||
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
|
||||
|
||||
**Step 4: Run tests and confirm GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all router tests pass and TypeScript reports no errors.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/http/types.ts test/router.test.ts
|
||||
git commit -s -m "feat(router): compile safe constrained patterns"
|
||||
```
|
||||
|
||||
### Task 2: Validate request paths and route-table ambiguity
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/app/index.ts`
|
||||
- Modify: `src/app/types.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
- Test: `test/app.test.ts`
|
||||
|
||||
**Step 1: Write failing path-policy tests**
|
||||
|
||||
Add router tests for the approved normalization:
|
||||
|
||||
```typescript
|
||||
expect(normalizeRequestPath('/users')).toBe('/users');
|
||||
expect(normalizeRequestPath('/users/')).toBe('/users');
|
||||
expect(normalizeRequestPath('/')).toBe('/');
|
||||
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||
```
|
||||
|
||||
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
|
||||
|
||||
```typescript
|
||||
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
|
||||
```
|
||||
|
||||
Cover the same path under different methods as valid.
|
||||
|
||||
**Step 2: Run focused tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/app.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because normalization and ambiguity checks are absent.
|
||||
|
||||
**Step 3: Implement request normalization**
|
||||
|
||||
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
|
||||
|
||||
**Step 4: Implement route-table validation**
|
||||
|
||||
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
|
||||
|
||||
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
|
||||
|
||||
**Step 5: Run focused and mesh tests**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all selected tests pass.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
|
||||
git commit -s -m "fix(router): reject invalid and ambiguous paths"
|
||||
```
|
||||
|
||||
### Task 3: Add HEAD and OPTIONS to the public decorator API
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/metadata.ts`
|
||||
- Modify: `src/index.ts`
|
||||
- Modify: `src/signals.ts`
|
||||
- Test: `test/metadata.test.ts`
|
||||
- Test: `test/smoke.test.ts`
|
||||
|
||||
**Step 1: Write failing decorator tests**
|
||||
|
||||
```typescript
|
||||
class Methods {
|
||||
@Head('/resource') head() {}
|
||||
@Options('/resource') options() {}
|
||||
}
|
||||
|
||||
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
|
||||
```
|
||||
|
||||
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
|
||||
|
||||
**Step 2: Run tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/metadata.test.ts test/smoke.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because the exports do not exist.
|
||||
|
||||
**Step 3: Implement decorators and messages**
|
||||
|
||||
Extend `HttpMethod`:
|
||||
|
||||
```typescript
|
||||
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||
```
|
||||
|
||||
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
|
||||
|
||||
**Step 4: Run tests and typecheck**
|
||||
|
||||
```bash
|
||||
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
|
||||
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
|
||||
```
|
||||
|
||||
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/http/core.ts`
|
||||
- Modify: `src/http/web.ts`
|
||||
- Modify: `src/http/server.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
- Test: `test/http.test.ts`
|
||||
- Test: `test/fetch.test.ts`
|
||||
- Test: `test/parity.test.ts`
|
||||
- Test: `test/transport-security.test.ts`
|
||||
|
||||
**Step 1: Write failing method-semantics tests**
|
||||
|
||||
Cover these cases in both Node and `app.fetch`:
|
||||
|
||||
```typescript
|
||||
// Explicit HEAD wins.
|
||||
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
|
||||
// Streaming GET does not become implicit HEAD.
|
||||
// Explicit OPTIONS wins.
|
||||
// Automatic OPTIONS returns 204 and deterministic Allow.
|
||||
// GET implies HEAD; every existing path implies OPTIONS.
|
||||
// CORS preflight still runs before explicit/automatic OPTIONS.
|
||||
// Double slash and malformed encoding return 400 with security headers.
|
||||
```
|
||||
|
||||
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
|
||||
|
||||
**Step 2: Run focused tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
```
|
||||
|
||||
Expected: new assertions fail under the current 405 behavior.
|
||||
|
||||
**Step 3: Implement method resolution**
|
||||
|
||||
In `src/http/router.ts`, add a stable method order and helpers:
|
||||
|
||||
```typescript
|
||||
export interface ResolvedRoute extends MatchedRoute {
|
||||
implicitHead: boolean;
|
||||
}
|
||||
|
||||
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
|
||||
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
|
||||
```
|
||||
|
||||
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
|
||||
|
||||
**Step 4: Implement core outcomes**
|
||||
|
||||
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
|
||||
|
||||
**Step 5: Align body acquisition in both adapters**
|
||||
|
||||
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
|
||||
|
||||
**Step 6: Run focused tests and confirm GREEN**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all selected tests pass with Node/Fetch parity.
|
||||
|
||||
**Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
|
||||
```
|
||||
|
||||
### Task 5: Project constraints into OpenAPI and introspection
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/openapi.ts`
|
||||
- Modify: `src/app/introspect.ts`
|
||||
- Test: `test/openapi.test.ts`
|
||||
- Test: `test/graph-viz.test.ts`
|
||||
|
||||
**Step 1: Write failing OpenAPI tests**
|
||||
|
||||
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
|
||||
|
||||
```typescript
|
||||
expect(doc.paths['/api/users/{id}']).toBeDefined();
|
||||
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
|
||||
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
|
||||
);
|
||||
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
|
||||
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
|
||||
```
|
||||
|
||||
Assert that automatic HEAD/OPTIONS operations are not invented.
|
||||
|
||||
**Step 2: Run tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
|
||||
```
|
||||
|
||||
Expected: constrained template parsing or schema assertions fail.
|
||||
|
||||
**Step 3: Implement projection**
|
||||
|
||||
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
|
||||
|
||||
**Step 4: Run tests and typecheck**
|
||||
|
||||
```bash
|
||||
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
|
||||
git commit -s -m "feat(openapi): document constrained route params"
|
||||
```
|
||||
|
||||
### Task 6: Remove root and website dependency advisories
|
||||
|
||||
**Skills:** `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Modify: `package-lock.json`
|
||||
- Modify: `website/package.json`
|
||||
- Modify: `website/package-lock.json`
|
||||
- Test: `bench/servers/nestjs-express.ts`
|
||||
- Test: `bench/servers/nestjs-fastify.ts`
|
||||
|
||||
**Step 1: Record the failing audit baseline**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm --prefix website audit
|
||||
npm audit --omit=dev
|
||||
```
|
||||
|
||||
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
|
||||
|
||||
**Step 2: Apply supported direct updates**
|
||||
|
||||
Update root dependencies with explicit commands so the manifests and lockfile agree:
|
||||
|
||||
```bash
|
||||
npm install --save-dev vitest@^3.2.6 \
|
||||
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
|
||||
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
|
||||
fastify@^5.11.0 miniflare@^4.20260730.0 \
|
||||
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
|
||||
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
|
||||
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
|
||||
```
|
||||
|
||||
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
|
||||
|
||||
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
|
||||
|
||||
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
|
||||
|
||||
```json
|
||||
{
|
||||
"overrides": {
|
||||
"@nestjs/platform-fastify": {
|
||||
"find-my-way": "9.7.0"
|
||||
},
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
|
||||
|
||||
**Step 4: Prove compatibility before accepting overrides**
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm test
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
|
||||
|
||||
**Step 5: Verify clean audits**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm audit --omit=dev
|
||||
npm --prefix website audit
|
||||
```
|
||||
|
||||
Expected: all three commands exit 0 with zero vulnerabilities.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json package-lock.json website/package.json website/package-lock.json
|
||||
git commit -s -m "chore(deps): remediate security advisories"
|
||||
```
|
||||
|
||||
### Task 7: Add security and documentation gates to CI
|
||||
|
||||
**Skills:** `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
**Step 1: Define the expected gates**
|
||||
|
||||
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
|
||||
|
||||
**Step 2: Update CI**
|
||||
|
||||
Add these steps after the root `npm ci`:
|
||||
|
||||
```yaml
|
||||
- run: npm audit
|
||||
- run: npm ci --prefix website
|
||||
- run: npm audit --prefix website
|
||||
- run: npm run docs:build
|
||||
```
|
||||
|
||||
Keep lint, format, complexity, typecheck, test, and build unchanged.
|
||||
|
||||
**Step 3: Update the GitHub release gate**
|
||||
|
||||
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
|
||||
|
||||
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
|
||||
|
||||
- Gitea `main` → Verdaccio `stg`;
|
||||
- Gitea `main` and `v*` tags → GitHub;
|
||||
- GitHub `v*` → npm OIDC release.
|
||||
|
||||
**Step 4: Validate workflow syntax and diff**
|
||||
|
||||
```bash
|
||||
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
|
||||
git diff --check
|
||||
```
|
||||
|
||||
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add .github/workflows/ci.yml .github/workflows/release.yml
|
||||
git commit -s -m "ci: gate releases on clean dependency audits"
|
||||
```
|
||||
|
||||
### Task 8: Audit and align the complete website documentation
|
||||
|
||||
**Skills:** `@writing-clearly-and-concisely`
|
||||
|
||||
**Files:**
|
||||
- Review: every page under `website/src/content/docs/`
|
||||
- Modify: `website/src/content/docs/guides/routing.md`
|
||||
- Modify: `website/src/content/docs/reference/decorators.md`
|
||||
- Modify: `website/src/content/docs/guides/openapi.md`
|
||||
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
|
||||
- Create: `website/src/content/docs/404.md`
|
||||
|
||||
**Step 1: Build a code-backed website documentation inventory**
|
||||
|
||||
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
|
||||
|
||||
Do not change a claim from memory. Each correction must be supported by code or a passing test.
|
||||
|
||||
**Step 2: Update routing documentation from the verified behavior**
|
||||
|
||||
Document:
|
||||
|
||||
- `@Head` and `@Options`;
|
||||
- explicit-route priority and automatic fallbacks;
|
||||
- canonical `Allow` behavior;
|
||||
- `/path` equals `/path/`;
|
||||
- `//` and malformed encoding return `400`;
|
||||
- catch-all must be final;
|
||||
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
|
||||
- the matcher remains linear and a radix tree remains deferred.
|
||||
|
||||
Remove the current statement that bare OPTIONS returns 405.
|
||||
|
||||
**Step 3: Align cross-cutting website references**
|
||||
|
||||
At minimum, verify and correct:
|
||||
|
||||
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
|
||||
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
|
||||
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
|
||||
- mesh route-conflict wording after effective-pattern normalization;
|
||||
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
|
||||
- navigation/frontmatter descriptions that still advertise the old router surface.
|
||||
|
||||
Keep intentional historical or roadmap statements only when they remain true.
|
||||
|
||||
**Step 4: Fix the Starlight 404 warning**
|
||||
|
||||
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
|
||||
|
||||
**Step 5: Validate the whole website documentation tree**
|
||||
|
||||
```bash
|
||||
npm run docs:build
|
||||
npm --prefix website audit
|
||||
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
|
||||
rg -n '\]\(/docs/' website/src/content/docs
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add website/src/content/docs
|
||||
git commit -s -m "docs(website): align guides with router behavior"
|
||||
```
|
||||
|
||||
### Task 9: Align package documentation and prepare the August beta
|
||||
|
||||
**Skills:** `@writing-clearly-and-concisely`
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
- Modify: `CHANGELOG.md`
|
||||
- Modify: `src/index.ts`
|
||||
- Modify: `package.json`
|
||||
- Modify: `package-lock.json`
|
||||
|
||||
**Step 1: Align the package-facing documentation**
|
||||
|
||||
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
|
||||
|
||||
**Step 2: Bump the beta version consistently**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npm version 26.8.0-beta.0 --no-git-tag-version
|
||||
```
|
||||
|
||||
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
|
||||
|
||||
**Step 3: Verify docs and version consistency**
|
||||
|
||||
```bash
|
||||
npm run docs:build
|
||||
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
|
||||
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
|
||||
|
||||
**Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
|
||||
git commit -s -m "docs: document router completeness for beta"
|
||||
```
|
||||
|
||||
### Task 10: Run the complete release-candidate verification
|
||||
|
||||
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify only if a verification failure reveals an in-scope defect.
|
||||
|
||||
**Step 1: Run static and Node gates**
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format:check
|
||||
npm run complexity:check
|
||||
npm run typecheck
|
||||
npm run typecheck:bench
|
||||
npm test
|
||||
npm run build
|
||||
```
|
||||
|
||||
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
|
||||
|
||||
**Step 2: Run multi-runtime gates**
|
||||
|
||||
```bash
|
||||
npm run test:deno
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
|
||||
|
||||
**Step 3: Run security, docs, and benchmark gates**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm audit --omit=dev
|
||||
npm --prefix website audit
|
||||
npm run docs:build
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
|
||||
|
||||
**Step 4: Inspect the publish artifact without publishing**
|
||||
|
||||
```bash
|
||||
npm pack --dry-run
|
||||
```
|
||||
|
||||
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
|
||||
|
||||
**Step 5: Review branch and workflow boundaries**
|
||||
|
||||
```bash
|
||||
git status --short --branch
|
||||
git log --oneline --decorate develop..HEAD
|
||||
git diff --check develop...HEAD
|
||||
git diff --stat develop...HEAD
|
||||
```
|
||||
|
||||
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
|
||||
|
||||
**Step 6: Commit any verification-only repair**
|
||||
|
||||
Only if Step 1–5 exposed an in-scope defect:
|
||||
|
||||
```bash
|
||||
git add <exact repaired files>
|
||||
git commit -s -m "fix: address beta verification findings"
|
||||
```
|
||||
|
||||
Re-run the failed gate and the complete related suite after any repair.
|
||||
@@ -0,0 +1,166 @@
|
||||
# Observability — Design
|
||||
|
||||
**Issue:** [#10](https://github.com/Expressive-Tea/green-tea/issues/10) · **Status:** reviewed, all decisions settled · **Constraint:** no new runtime dependency
|
||||
|
||||
---
|
||||
|
||||
## The diagnosis is not the one in the issue
|
||||
|
||||
#10 says green-tea "ships no logging, metrics or tracing contract today", and asks for an injectable logger, structured output, tracing hooks and metrics as one design. The framing is right; the starting point is wrong, and it changes what the work is.
|
||||
|
||||
**The mechanism already exists.** `Bus` (`src/bus.ts`) is an in-process event emitter with 19 emission points already wired through boot, the pipeline, streams, WebSockets, mesh and plugins. Plugins already receive `bus.on` — and only `on`, so isolation is structural (`src/plugin.ts:27`).
|
||||
|
||||
What is actually missing is narrower and more serious than "there is no logger":
|
||||
|
||||
| # | Finding | Where |
|
||||
|---|---|---|
|
||||
| 1 | **No event carries request identity.** Under any concurrency, interleaved `request:step:enter` events cannot be attributed to a request. | `src/pipeline.ts:53,56` |
|
||||
| 2 | **`durationMs` is declared and never set by anything.** There is no timing in the system at all. | `src/bus.ts:22`, zero writers |
|
||||
| 3 | **No request-level events exist.** No `started`/`completed`/`failed`, so there is no span for step events to hang from. | — |
|
||||
| 4 | **A failing step is reported as `name: 'pipeline'`**, losing which step broke. | `src/pipeline.ts:98` |
|
||||
| 5 | **8 `console.warn` calls in core**, unredirectable. | `src/app/index.ts` ×6, `src/deno.ts`, `src/bun.ts` |
|
||||
|
||||
So the real statement of the problem is:
|
||||
|
||||
> The event stream exists but is **not correlatable and not measured**, which makes it unusable for production observability regardless of what consumes it.
|
||||
|
||||
That is *why* #10 is one design and not six — a sharper reason than the issue had. A logger, a metrics exporter and an OpenTelemetry bridge are not three features; they are three **consumers of one corrected event stream**. Fix correlation and timing once, and all three become adapters outside core. Ship them separately and each grows its own private notion of "which request was that", which is the three-mechanisms failure #10 warned about.
|
||||
|
||||
**Consequence for sequencing:** most of this work is in `src/bus.ts` and `src/pipeline.ts`, not in new files.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1 — The logger is a distinct registration, not an ordinary provider
|
||||
|
||||
`createApp({ logger })`, not `@Provider({ provides: 'logger' })`.
|
||||
|
||||
The deciding constraint is ordering. `boot:provider:start`/`fail` fire *while* the graph is booting (`src/app/index.ts:639-647`), and the optional-provider failure warning at `src/app/index.ts` logs during that same phase. A provider cannot log its own boot failure, and a logger that only exists after the graph resolves cannot report the graph failing to resolve. Shutdown has the same shape: `closeApp` warns after the graph is gone.
|
||||
|
||||
The logger is therefore framework infrastructure with a lifetime wider than the graph.
|
||||
|
||||
It is *additionally* exposed as an injectable key so steps and handlers reach it with `@needs('logger')` like anything else. One object, two access paths, no second implementation.
|
||||
|
||||
**Default:** structured JSON. Human-readable when the process is interactive, decided once at boot rather than per call. **Never a dependency** — the default writes to `console` behind the same interface everyone else implements, which is what lets the 8 direct `console.warn` calls become logger calls without core gaining a logging library.
|
||||
|
||||
### D2 — One emitter. Extend `Bus`; do not add a parallel hook system
|
||||
|
||||
Per-category hooks would be a second mechanism competing with an emitter that already has 19 call sites and a plugin contract built on it. `LifecycleEvent` grows; nothing new is introduced.
|
||||
|
||||
This also keeps the existing guarantee intact: `emit` swallows listener failures (`src/bus.ts:41`) precisely so observers can never break the pipeline. Observability must not acquire the power to take down a request.
|
||||
|
||||
**This is exactly why shutdown teardown does not belong here** — see Task 2.5 in the trust-release plan. A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
|
||||
|
||||
### D3 — A step failure emits both `request:step:error` and `request:failed`
|
||||
|
||||
They answer different questions — *which step broke* and *did this request fail* — and a tracing exporter needs both: one marks the span, the other marks the trace. Emitting only the outer event is what produces a trace that says a request failed with no indication where.
|
||||
|
||||
`request:step:error` must also carry the real step name. Emitting `name: 'pipeline'` (`src/pipeline.ts:98`) is a bug, not a design choice, and it is fixed as part of this.
|
||||
|
||||
### D4 — Streams and WebSockets emit lifecycle events only, never per-message
|
||||
|
||||
`stream:open`/`close`/`error` already exist and are the right granularity. A per-message event on a high-rate SSE or WebSocket stream is a firehose that costs more than it reports, and the cost lands on the workload least able to absorb it.
|
||||
|
||||
Anyone who needs per-message visibility instruments their own handler, where they know the message semantics. Same reasoning that keeps WebSocket upgrades outside the concurrency gate in #21.
|
||||
|
||||
### D5 — Request identity is generated with `crypto.randomUUID()`, and inherited when offered
|
||||
|
||||
No new dependency is available, so no UUID library. `globalThis.crypto.randomUUID` is present on Node, Deno and Bun (verified locally) and is Web Crypto on workerd.
|
||||
|
||||
**To validate during implementation:** Node 18 is the floor in `package.json` and CI's `build` job pins `node-version: '18'`, so a gap there fails CI rather than reaching a user. `test:edge` covers workerd the same way.
|
||||
|
||||
An incoming `x-request-id` is adopted rather than replaced — a green-tea service behind a gateway must not start a second identity for the same request. A `traceparent` header, if present, is carried as `traceId` untouched; core parses nothing and implements no propagation spec. That belongs in the OpenTelemetry adapter, which owns W3C Trace Context.
|
||||
|
||||
---
|
||||
|
||||
## The contract
|
||||
|
||||
### Events
|
||||
|
||||
Existing, unchanged in name: `boot:provider:start|ok|fail`, `request:step:enter|leave|error`, `stream:open|close|error`, `mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||
|
||||
Added:
|
||||
|
||||
```
|
||||
request:start request:end request:failed
|
||||
route:matched route:unmatched
|
||||
graph:resolved graph:failed
|
||||
```
|
||||
|
||||
`route:unmatched` rather than the report's `route.not_found`: a 405 is also an unmatched route and is not a 404, and naming the event after one outcome would misreport the other.
|
||||
|
||||
### Payload
|
||||
|
||||
`EventPayload` gains the correlation and measurement fields it lacks. Every field stays optional — mesh and boot events have no request to name, and forcing a shape on them would mean inventing values.
|
||||
|
||||
```ts
|
||||
interface EventPayload {
|
||||
name: string;
|
||||
scope?: string;
|
||||
error?: unknown;
|
||||
durationMs?: number; // declared today, written by nothing — this design makes it real
|
||||
requestId?: string; // the correlation fix
|
||||
traceId?: string; // inherited from traceparent when present; never synthesized
|
||||
route?: string; // the matched pattern, not the raw URL — bounded cardinality for metrics
|
||||
method?: string;
|
||||
transport?: Transport;
|
||||
status?: number;
|
||||
runtime?: 'node' | 'deno' | 'bun' | 'edge';
|
||||
}
|
||||
```
|
||||
|
||||
`route` is the **pattern** (`/users/:id`), never the concrete path. A metrics consumer that labels a counter with the raw URL produces unbounded cardinality and takes down the metrics backend rather than the app — the framework should not hand a user that shape by default.
|
||||
|
||||
### Metrics
|
||||
|
||||
No metrics registry in core, and no new event type for them. Per-step timings come from `durationMs` on the events already defined; a metrics adapter subscribes and aggregates. The graph already knows every node, which is what makes this close to free — but the timing instrumentation is measured before it is declared free, per Trust Release §6, and stays opt-in if the measurement says otherwise.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope, deliberately
|
||||
|
||||
- **OpenTelemetry itself.** A separate `@green-tea/opentelemetry` package. Core exposes the stream; it never imports an exporter, and never depends on one.
|
||||
- **Log shipping, sampling, redaction.** Consumer concerns. Core hands over structured records.
|
||||
- **Trace context propagation.** Carried, not parsed. The adapter owns W3C Trace Context.
|
||||
- **Shutdown teardown for plugins/providers.** Task 2.5, a different guarantee — see D2.
|
||||
|
||||
---
|
||||
|
||||
### D6 — A request span ends when the handler returns, and stream events carry its `requestId`
|
||||
|
||||
A streaming route returns from `handle()` in milliseconds while the connection lives for minutes or hours. `request:end` fires at the handler's return, so latency histograms measure time-to-first-byte and stay meaningful instead of mixing 2 ms buffered requests with hour-long SSE connections in one distribution. Connection duration is already available from `stream:open`/`stream:close`, which now carry the same `requestId` so a consumer can join the two.
|
||||
|
||||
This is the same boundary #21 chose for its concurrency gate — release when `handle()` returns, treat long-lived streams like upgrades. Answering it differently in the two places would mean the framework disagreed with itself about when a request is over.
|
||||
|
||||
### D7 — Per-step timing is always on, measured at step boundaries
|
||||
|
||||
Measured before deciding, on the box `BENCHMARKS.md` was produced on:
|
||||
|
||||
| Approach | Cost per step | Share of one request |
|
||||
|---|---:|---:|
|
||||
| `performance.now()` ×2 per step | 45.3 ns | 0.44% |
|
||||
| **`performance.now()` at step boundaries (N+1 calls for N steps)** | **25.2 ns** | **0.25%** |
|
||||
| `Date.now()` ×1 | 28.6 ns | — |
|
||||
|
||||
Baseline: 98,093 req/s ≈ 10.19 µs per request.
|
||||
|
||||
Two things follow. `Date.now()` loses on both axes — slower *and* coarser — so `performance.now()` is unambiguous. And a step's end is the next step's start, so a pipeline of N steps needs N+1 timestamps rather than 2N, halving the cost.
|
||||
|
||||
At 0.25% per step the overhead sits **below the 0.3% run-to-run CV of the project's own benchmark**, so it is not measurable in the harness that would have to justify a flag. Making it opt-in would buy two code paths and a configuration surface in exchange for something nobody can observe. Always on.
|
||||
|
||||
> **Correction, after implementation.** This decision survived; its reasoning did not. The measured cost is **+7.0% of the framework's own per-request work** (~0.29 µs, ~2% over a real socket), and it is *fixed per request* rather than per step — per-step work is skipped entirely when nothing subscribes. "Always on" is still right, and for a better reason: there is nothing per-step left to make optional.
|
||||
>
|
||||
> Three earlier figures for this were published before that one and all three were wrong, each from a comparison with more than one variable moving. See Task 7 in the implementation plan for what went wrong and why interleaving is not optional here.
|
||||
|
||||
### D8 — Request logging is a `Bus` subscriber, wrapped so a failing logger cannot go silent
|
||||
|
||||
The logger is a callable sink either way — the 8 direct diagnostics (shutdown timeout, degraded provider) are not events and need one regardless. The decision is only about request logging, and it goes through the event stream: one path, and it is composable and removable exactly as #10 asks for ("a composable step, not a global middleware").
|
||||
|
||||
The cost this closes: `emit` swallows listener failures by design (`src/bus.ts:41`), so a user-supplied logger that throws would stop writing with nobody informed. The built-in subscriber is therefore wrapped to fall back to `console` on failure. The Bus keeps its guarantee — an observer still cannot break a request — without buying it with silence.
|
||||
|
||||
---
|
||||
|
||||
## Verification this design must survive
|
||||
|
||||
`npm run lint && npm run format:check && npm run typecheck && npm test`, plus `test:deno`, `test:bun` and `test:edge` — all four now gate a merge. Per-request instrumentation is on the hot path, so `npm run bench` before and after, with the numbers in the implementation plan.
|
||||
@@ -0,0 +1,166 @@
|
||||
# Observability — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Design:** [2026-08-16-observability-design.md](./2026-08-16-observability-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
|
||||
|
||||
**Goal:** Make the existing event stream correlatable and measured, then build the logger on top of it as its first consumer. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
|
||||
|
||||
**Architecture:** Most of this lands in `src/bus.ts` and `src/pipeline.ts`. The `Bus` already has 19 emission points; this adds identity, timing and the request-level events those points had nothing to hang from. No new runtime dependency — `reflect-metadata` stays the only one, and the OpenTelemetry bridge lives outside core.
|
||||
|
||||
**Tech Stack:** TypeScript, Vitest, Deno/Bun/workerd suites, `performance.now()`, `crypto.randomUUID()`.
|
||||
|
||||
---
|
||||
|
||||
## Order
|
||||
|
||||
Tasks 1–3 are the correction; 4–6 are what consumes it. Do not start 4 before 3 — a logger built on uncorrelated events would need its own notion of request identity, which is the failure the design exists to prevent.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Give every request an identity, and carry it
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/core.ts` (`NeutralRequest`, `handle`)
|
||||
- Modify: `src/http/server.ts` (~line 120, the Node call into `handle`)
|
||||
- Modify: `src/http/web.ts` (~line 178, the Fetch call into `handle`)
|
||||
- Modify: `src/bus.ts`
|
||||
- Test: `test/observability.test.ts` (new)
|
||||
|
||||
**Step 1:** Extend `EventPayload` with the optional fields from the design: `requestId`, `traceId`, `route`, `method`, `transport`, `status`, `runtime`. All optional — boot and mesh events have no request to name.
|
||||
|
||||
**Step 2:** Add `requestId` to `NeutralRequest` (`src/http/core.ts`). Generate it in the **adapters**, not in `handle()`, and here is why that placement matters: both adapters read and size-check the body before they reach `handle()` (`server.ts:107`, `web.ts:143` per the #21 analysis), so a 413 is rejected before `handle()` ever sees the request. Generating inside `handle()` would leave exactly the failures an operator most wants to correlate without an id.
|
||||
|
||||
**Step 3:** One shared helper for generation, so the two adapters cannot diverge on the rule: adopt an incoming `x-request-id`, otherwise `crypto.randomUUID()`. Carry `traceparent` through as `traceId` **without parsing it** (D5).
|
||||
|
||||
**Step 4:** Write the test that fails first: fire two concurrent requests through `app.fetch`, collect `request:step:enter` from the bus, and assert every event carries a `requestId` and that the two requests' events never share one. This is the defect the whole design exists to fix, so it is the first test.
|
||||
|
||||
**Verify:** `crypto.randomUUID` on Node 18 — CI's `build` job pins `node-version: '18'`, and `test:edge` covers workerd. Do not assume; let both run.
|
||||
|
||||
### Task 2: Measure steps at their boundaries
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pipeline.ts` (`runSteps`, ~line 48)
|
||||
- Test: `test/observability.test.ts`
|
||||
|
||||
**Step 1:** Take `performance.now()` once before the loop, then once per iteration — **N+1 timestamps for N steps**, because a step's end is the next step's start. Not two per step. The design measured the difference: 25.2 ns vs 45.3 ns per step (D7).
|
||||
|
||||
**Step 2:** Attach `durationMs` to `request:step:leave`. The field has been declared in `EventPayload` since the beginning and written by nothing; this is what makes it real.
|
||||
|
||||
**Step 3:** Always on, no flag (D7 — 0.25% of a request, below the benchmark's own 0.3% CV).
|
||||
|
||||
**Verify:** a step that sleeps a known interval reports a `durationMs` in that neighbourhood. Assert a range, never an exact value.
|
||||
|
||||
### Task 3: Stop losing which step failed
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pipeline.ts` (`runSteps`, and the catch at ~line 98)
|
||||
- Test: `test/observability.test.ts`
|
||||
|
||||
`request:step:error` currently emits `{ name: 'pipeline' }`, which throws away the one fact it exists to report.
|
||||
|
||||
**Step 1:** Wrap each `step.run` inside `runSteps`, emit `request:step:error` with the real step name and `scope`, and rethrow unchanged. Do not swallow.
|
||||
|
||||
**Step 2:** `runPipeline`'s existing catch now emits `request:failed` instead of a second `step:error` (D3). Both fire for a failing step, deliberately: one marks the span, the other the trace.
|
||||
|
||||
**Verify:** a three-step pipeline whose middle step throws emits `request:step:error` naming *that* step, plus exactly one `request:failed`.
|
||||
|
||||
### Task 4: The logger contract
|
||||
|
||||
**Files:**
|
||||
- Create: `src/logger.ts`
|
||||
- Modify: `src/app/index.ts` (`createApp` options; the 6 `console.warn` calls)
|
||||
- Modify: `src/deno.ts`, `src/bun.ts` (1 `console.warn` each)
|
||||
- Modify: `src/index.ts` (export the type)
|
||||
- Test: `test/logger.test.ts` (new)
|
||||
|
||||
**Step 1:** Define the interface. Keep it to the levels core actually uses — resist inventing a hierarchy nobody calls.
|
||||
|
||||
**Step 2:** Default implementation: structured JSON, human-readable when the process is interactive, decided **once at boot** rather than per call. It writes through `console`; core gains no logging dependency (D1).
|
||||
|
||||
**Step 3:** `createApp({ logger })`. A distinct registration, not a provider — it has to outlive the graph to report the graph failing to boot (D1). Per `AGENTS.md`, a new public option means `src/app/types.ts` too if it appears on `App`.
|
||||
|
||||
**Step 4:** Replace all 8 `console.warn` calls. `grep -rn "console\." src/` must return nothing afterwards, which is the check #10 actually asks for.
|
||||
|
||||
**Step 5:** Expose the logger under an injectable key so steps and handlers reach it with `@needs('logger')`. One object, two access paths, no second implementation.
|
||||
|
||||
### Task 5: Request logging as a subscriber
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/logger.ts`
|
||||
- Test: `test/logger.test.ts`
|
||||
|
||||
**Step 1:** Build request logging as `bus.on(...)` over the corrected stream (D8). Composable and removable, which is what #10 means by "a composable step, not a global middleware".
|
||||
|
||||
**Step 2:** Wrap the subscriber so a throwing logger falls back to `console`. `Bus.emit` swallows listener failures by design (`src/bus.ts:41`); without the wrapper a broken user logger stops writing and tells nobody. The Bus keeps its guarantee; it just stops paying for it with silence.
|
||||
|
||||
**Verify:** a logger that throws on every call still produces output, and the request still succeeds.
|
||||
|
||||
### Task 6: The remaining events
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/bus.ts`, `src/http/core.ts`, `src/app/index.ts`
|
||||
|
||||
**Step 1:** Add `request:start|end|failed`, `route:matched|unmatched`, `graph:resolved|failed` to `LifecycleEvent`.
|
||||
|
||||
**Step 2:** `request:end` fires **when the handler returns**, not when a stream closes (D6). `stream:open`/`close` carry the same `requestId` so a consumer joins them itself.
|
||||
|
||||
**Step 3:** `route:unmatched` covers 404 and 405 both — naming it after one outcome would misreport the other.
|
||||
|
||||
**Step 4:** `route` on every payload is the **matched pattern**, never the concrete path. A metrics consumer labelling on raw URLs produces unbounded cardinality and takes down the metrics backend; the framework must not hand anyone that shape by default.
|
||||
|
||||
### Task 7: Benchmark, and publish the number — **DONE; D7 was wrong in shape**
|
||||
|
||||
**Files:**
|
||||
- Modify: `BENCHMARKS.md`
|
||||
|
||||
D7 predicted ~0.25% **per step**, invisible against the harness's own 0.3% CV.
|
||||
|
||||
**Measured: +7.0% of the framework's own per-request work** — 4.074 µs → 4.361 µs, medians of five interleaved rounds, ranges not overlapping. About 0.29 µs, or ~2% of a request over a real socket.
|
||||
|
||||
The prediction was wrong in **shape**, not only magnitude. Per-step work is skipped entirely when nothing subscribes (`Bus.hasListeners`), so a deep pipeline pays no more than a shallow one; what remains is a **fixed per-request** cost — generating the request id, reading two headers, and the guard checks. "Always on" survives, for a better reason than it was made with: there is nothing per-step left to make optional.
|
||||
|
||||
**Three earlier numbers for this were published and all three were wrong**, which is the more useful lesson: −3.9%, then 0.8%, then −6.8%. Each came from a comparison with more than one variable moving.
|
||||
|
||||
- The first two were sequential rather than interleaved. The same code measured at the start and end of one session differed by **12%** as the machine warmed, so run order was indistinguishable from effect — one of them even reported the wrong sign.
|
||||
- The third compared `7bd11bf` against `HEAD`, which differ by observability **and** three performance fixes pulling the other way. It reported their net as if it were one of them.
|
||||
|
||||
The number above compares `7bd11bf` against `523e318`, the last commit before those fixes, alternating round by round.
|
||||
|
||||
Two regressions were found and fixed by measuring rather than reasoning, both larger than anything the design anticipated:
|
||||
|
||||
- **A second `async` frame in `handle()` cost 0.43 µs/request** — a promise and two microtask ticks, an order of magnitude more than the four `Map` lookups it existed to arrange. `handle()` is no longer `async`.
|
||||
- **A closure allocated per request inside `correlateRequest`** cost 0.16 µs, 45% of the then-remaining overhead, for a helper capturing nothing.
|
||||
|
||||
Recorded here because the lesson generalises: on this path, an extra promise costs more than any amount of bookkeeping, and a hot-path prediction reasoned from primitive costs was off by more than 10×.
|
||||
|
||||
### Task 8: Documentation
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md` (the *Honest scope* paragraph at ~line 246)
|
||||
- Modify: `website/src/content/docs/` — a new observability guide, plus the `createapp` reference table
|
||||
|
||||
`README.md:246` currently opens "**No observability layer, either.**" and links to #10. It is the single most load-bearing sentence in the CTO assessment, and rewriting it is part of this work rather than follow-up. Say what now exists and what still does not — the OpenTelemetry adapter is not in core and should not be implied to be.
|
||||
|
||||
Per `AGENTS.md`, new public API needs a note in `README.md`.
|
||||
|
||||
> If Phase 4 has already moved the site, the guide lands in the docs repository instead.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope
|
||||
|
||||
`@green-tea/opentelemetry`, log shipping, sampling, redaction, W3C Trace Context parsing, and plugin/provider teardown (Task 2.5 in the trust-release plan — an awaited teardown and a non-blocking observer are opposite guarantees).
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run complexity:check && npm run typecheck && npm test
|
||||
npm run test:deno && npm run test:bun && npm run test:edge # all three gate a merge now
|
||||
npm run bench # hot-path change
|
||||
grep -rn "console\." src/ # must be empty
|
||||
```
|
||||
@@ -0,0 +1,350 @@
|
||||
# Trust Release Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Close the gaps that four independent evaluations agree on, in the order that makes each one cheap. Prove portability in CI, make derived execution explainable, ship an observability contract, and move the documentation site out of the core repository so it gets its own lifecycle.
|
||||
|
||||
**Architecture:** Nothing here adds a runtime dependency. The observability work is a contract plus emission points, with exporters living outside core. The explain work is a resolver over data `explainRoute` already returns. The runtime matrix runs suites that already exist. The docs split moves a directory that is already self-contained.
|
||||
|
||||
**Tech Stack:** TypeScript, legacy decorators, Vitest, Deno/Bun/Workers runtimes, JSR, Astro/Starlight, GitHub/Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
## Why this order
|
||||
|
||||
The four reports in `.specs/reports/` were written independently and converge on one gap. Observability is the only dimension the CTO due diligence marks as risk **Alto** on its own (§5.3, risk register), it is P0 twice in the Trust Release report (§4, §5), and it is a listed con in the lead-dev report (§4). That is GH #10, and it is the largest item here — which is exactly why it is not first. The three phases before it are cheap, unblock evidence, and produce the material that #10's design needs.
|
||||
|
||||
Two things the reports demand that had **no issue filed**, both verified against the code rather than taken on the report's word:
|
||||
|
||||
- **Runtime matrix in CI.** `package.json:91-93` defines `test:deno`, `test:bun` and `test:edge`. `.github/workflows/ci.yml` runs none of them. `AGENTS.md:23` already warns that `npm test` does not cover the other runtimes — and CI does not close that. The framework's headline claim has no CI evidence. Trust Release §7 (P0), CTO §8.2 and P0-6.
|
||||
- **`explain()` does not explain causality.** `src/app/introspect.ts:62` returns a flat `chain` with `needs`/`provides` per node, but never the edge from a need to the node that produced it. Trust Release §2 (P0).
|
||||
|
||||
One thing that **has** an issue but appears in no report: **#13 circuit breaker**. Neither the CTO report nor the Trust Release report raises it; the nearest item is "rate limiter" under the CTO's security pack (P0-3), which is a different mechanism. The issue itself already says a worked example in the docs might close it outright. It is scheduled last, as documentation.
|
||||
|
||||
**API freeze is deliberately not a phase.** `README.md:276` already declares it under `**next**`. It needs the RC boundary, and freezing a public surface before #10 lands would freeze an API that is still missing its observability contract. What this plan adds instead is a stability *contract* — a statement of which areas are volatile today, which promises nothing and commits to no date (Task 6.1).
|
||||
|
||||
**Out of scope: #21 and #17.** Both are claimed by `hgshreyas` with the design already settled in the issue threads. Do not touch them.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0: Unblock releases
|
||||
|
||||
### Task 0.1: Scope the audit gate in stage and release
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/stage.yml`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
`AGENTS.md:71` states the policy: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. `ci.yml:56-59` implements it. `stage.yml:21` and `release.yml:26` run bare `npm audit`, so a dev-only advisory blocks a publish. This is drift, not a second policy.
|
||||
|
||||
That drift is what stopped work twice. The `nanoid` advisory reached the tree through `tsup → postcss → nanoid` — a build-tooling path that ships to nobody.
|
||||
|
||||
**Step 1:** In both files, change `npm audit` to `npm audit --omit=dev`, and add a non-blocking full `npm audit` with `continue-on-error: true` after it so the advisory is still visible in the log.
|
||||
|
||||
**Step 2:** Carry a comment on the blocking step pointing at the rule, in the voice `ci.yml` already uses — the next person to read it should see a decision, not an omission.
|
||||
|
||||
**Verify:** `grep -n "npm audit" .github/workflows/*.yml` — every blocking occurrence carries `--omit=dev`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Prove portability, and publish to JSR
|
||||
|
||||
These are one phase because they are one subject. The type error JSR found is on the `app.fetch` path, which is the path Deno, Bun and edge all use; a runtime matrix would have caught it first. Fixing them together means the matrix has a green baseline to protect.
|
||||
|
||||
### Task 1.1: Fix the `BodyInit` hole on the Fetch path
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/web.ts`
|
||||
- Test: `test/` (the Fetch adapter suite)
|
||||
|
||||
Gitea #19 reports, from a real `deno publish --dry-run`:
|
||||
|
||||
```
|
||||
TS2345: Argument of type 'string | Buffer<ArrayBufferLike> | null' is not
|
||||
assignable to parameter of type 'BodyInit | null | undefined'.
|
||||
--> src/http/web.ts:112:23
|
||||
```
|
||||
|
||||
`Buffer` is not a valid `BodyInit` under Deno's lib. It works at runtime because implementations are forgiving, which is what makes it worth fixing before a user reports it as a bug: it is a genuine typing hole on the runtime-agnostic path, not a JSR formality.
|
||||
|
||||
**Step 1:** Write a failing test that drives a `Buffer` body through the Fetch adapter and asserts the response body round-trips byte-for-byte.
|
||||
|
||||
**Step 2:** Narrow the body to a real `BodyInit` at the boundary — convert the `Buffer` to a view its type declares, rather than casting the error away. A cast would keep the hole and hide it.
|
||||
|
||||
**Step 3:** Confirm the test passes and `npm run typecheck` is clean.
|
||||
|
||||
### Task 1.2: Give the slow-type sites explicit return types
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/metadata.ts` (11 sites)
|
||||
- Modify: `src/params.ts` (6 sites)
|
||||
|
||||
Two shapes, both mechanical: `missing-explicit-return-type` on factory functions (`routeDecorator` at `src/metadata.ts:103`, `envelope` at `src/params.ts:35`) and `missing-explicit-type` on the exported constants built from them (`export const Get = routeDecorator('GET', 'buffer')` at `src/metadata.ts:126`).
|
||||
|
||||
**Do not pass `--allow-slow-types`.** That flag degrades generated declarations and makes type checking 1.5–2× slower for consumers, in the framework whose central claim is type safety. Shipping it would contradict the pitch on its own install page.
|
||||
|
||||
**Step 1:** Annotate the factories first — several of the constant errors resolve on their own once the factory's return type is written down.
|
||||
|
||||
**Step 2:** Annotate whatever constants remain.
|
||||
|
||||
**Step 3:** `deno publish --dry-run` reports zero slow types, with no flags.
|
||||
|
||||
**Verify:** `npm run typecheck` and `npm test` still clean; the public types in `dist/` are unchanged or strictly more precise.
|
||||
|
||||
### Task 1.3: Runtime matrix in CI
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
|
||||
The suites exist and CI ignores them. Add a matrix job that runs `test:deno`, `test:bun` and `test:edge` alongside the Node build.
|
||||
|
||||
**Step 1:** Add a job with the three runtimes, each installing its own toolchain. Keep it a separate job from `build` so a Bun failure reports as a Bun failure and does not bury the Node lint output — the same reasoning `ci.yml:53` already applies to the audit step.
|
||||
|
||||
**Step 2:** Confirm the forge difference documented at `AGENTS.md:73` does not bite: GitHub reads `pull_request` workflows from the base branch, so this workflow change cannot validate itself and must reach the base before it gates anything.
|
||||
|
||||
**Step 3:** Publish the resulting capability matrix. `README.md:273` already claims all four runtimes; the matrix is what turns that claim into evidence.
|
||||
|
||||
**Verify:** A deliberate break in shared code fails the Deno job and not only the Node one.
|
||||
|
||||
### Task 1.4: Claim the JSR scope and publish
|
||||
|
||||
**Files:**
|
||||
- Modify: `deno.json`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
**Blocked on Diego and not delegable:** `@green-tea` on jsr.io must be claimed with a GitHub account.
|
||||
|
||||
**Step 1:** Add `name`, `version` and `exports` to `deno.json`. Decide whether all four entry points (`.`, `./deno`, `./bun`, `./edge`) are exported or only the Deno one.
|
||||
|
||||
**Step 2:** Publish from the same `v*` tag that publishes to npm, using GitHub Actions OIDC. `release.yml` already holds `id-token: write` for npm Trusted Publishing, so JSR needs no new secret.
|
||||
|
||||
**Step 3:** Nothing here justifies cutting a release on its own — it rides along with the next version cut that has a reason.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: The shutdown cluster
|
||||
|
||||
Four open issues, all consequences of the `close({ timeoutMs })` contribution that just merged (`3dcf784`). Treated as one deliverable because they are one subject: Trust Release §14 (P1, lifecycle guarantees) and CTO P0-4 (production checklist, shutdown).
|
||||
|
||||
Order matters — the bug first, then the API, then the docs that describe the finished API.
|
||||
|
||||
### Task 2.1: #20 — `finish()` reads its timer before declaration
|
||||
|
||||
A use-before-declare bug. Smallest item in this plan and it is already shipped. Fix it, and leave a test that fails if the ordering regresses.
|
||||
|
||||
### Task 2.2: #19 — shutdown deadline settable at `createApp` level
|
||||
|
||||
The 10s deadline is hardcoded. Make it configurable at app level, with `close({ timeoutMs })` still overriding per call.
|
||||
|
||||
Per `AGENTS.md:81`, a new option on a public interface **must** also change `src/app/types.ts`. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
|
||||
|
||||
### Task 2.3: #15 — graceful shutdown is Node-only — **DECIDED, DONE**
|
||||
|
||||
**Decision: `app.close()` stays Node-only; each adapter that owns a server offers the same `close({ timeoutMs })`.** The framework's line is *it handles architecture, you handle business*, and draining is owned by whoever holds the handle.
|
||||
|
||||
What the runtimes turned out to allow, measured rather than assumed:
|
||||
|
||||
| Runtime | Drain | After the deadline |
|
||||
|---|---|---|
|
||||
| Node | `server.close()` | `closeAllConnections()` — remainder cut |
|
||||
| Bun | `stop(false)` | `stop(true)` — remainder cut |
|
||||
| Deno | `shutdown()` | **returns anyway** — remainder ends with the process |
|
||||
|
||||
Deno cannot escalate. Aborting the serve signal while `shutdown()` is pending throws `BadResource: Bad resource ID` from Deno's own listener — uncaught, and fatal under `deno test`. Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long `close()` waits, not when connections die, and `runtimes.md` says so in a table rather than averaging the three.
|
||||
|
||||
`closeWithDeadline` (`src/http/shutdown.ts`) is shared so the two adapters cannot drift into different meanings of the same `timeoutMs`, and it resolves on its own timer rather than awaiting the force call — Bun's `stop(true)` was measured waiting out a handler with a pending timer, which is the unbounded wait the deadline exists to prevent.
|
||||
|
||||
### Task 2.5: Shutdown as an extension point — **OPEN, needs its own design**
|
||||
|
||||
Raised while deciding #15: shutdown should emit signals so plugins and providers register their own teardown, instead of every consumer writing `process.on('SIGTERM', …)` by hand. Same principle as the decision above — the framework owns the plumbing.
|
||||
|
||||
It does **not** fit the existing `Bus`, and that is the finding worth carrying forward. `Bus.on` takes a synchronous listener (`src/bus.ts:29`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:38`, `catch {}`). That is deliberate — observers must never break the pipeline — but a plugin closing a database connection needs shutdown to *wait for it*. Registering a teardown is not observing an event, and bending `Bus` to do both would cost the guarantee that makes it safe.
|
||||
|
||||
So it needs: an await-aware teardown registry, a new surface on `PluginApi` (public API — `src/plugin.ts:19`), and a decision about provider cleanup. That is Trust Release §14 "Graceful lifecycle guarantees" and CTO P0-4, and it belongs in a design document rather than inside a bug-fix cluster. Sequence it with Phase 3, whose observability contract shares the same lifecycle vocabulary.
|
||||
|
||||
### Task 2.4: #18 — docs still describe `close()` without the timeout
|
||||
|
||||
Last, so it documents the finished API rather than being rewritten twice. If Phase 4 has already run, this lands in the docs repository instead.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Observability (#10)
|
||||
|
||||
The one every report puts first, and the only one that needs a design document before code.
|
||||
|
||||
### Task 3.1: Design document
|
||||
|
||||
**Files:**
|
||||
- Create: `.specs/2026-XX-XX-green-tea-observability-design.md`
|
||||
|
||||
Write the design before any implementation, following the design/plan pairing already in `.specs/`.
|
||||
|
||||
The issue is explicit that this is **one design, not six**: an injectable logger, structured output and tracing hooks are the same API decision, and solving them separately leaves three mechanisms that do not fit together.
|
||||
|
||||
Inputs to reconcile:
|
||||
|
||||
- The scope in GH #10 — injectable logger contract, JSON default with human-readable dev output, request/response logging as a composable step rather than global middleware, hooks an exporter can attach to, metrics export.
|
||||
- The Trust Release event vocabulary (§4) — `request.*`, `route.*`, `step.*`, `provider.*`, `graph.*`, `websocket.*`, `stream.*` — and its context fields (`requestId`, `traceId`, `route`, `transport`, `step`, `duration`, `status`, `scope`, `runtime`).
|
||||
- Trust Release §6, graph timing. Per-step timings are close to free because the graph already knows every node, but the instrumentation stays opt-in if overhead is measurable. Measure before deciding.
|
||||
|
||||
Hard constraint, restated from `AGENTS.md:11`: **no new runtime dependency.** Core stays on `reflect-metadata` alone. An OpenTelemetry exporter is a separate package (`@green-tea/opentelemetry`), never a core dependency.
|
||||
|
||||
Decisions the design must settle rather than leave open:
|
||||
|
||||
1. Is the logger a provider like any other, or a distinct registration?
|
||||
2. Do events go through one emitter or through per-category hooks?
|
||||
3. Does a step failure emit `step.failed` and `request.failed`, or only the outer one?
|
||||
4. Do long-lived streams and WebSockets emit per-message events, or only lifecycle ones? (The same reasoning that keeps upgrades out of the #21 gate applies.)
|
||||
|
||||
### Task 3.2: Implement to the approved design
|
||||
|
||||
Do not start before the design is reviewed. Write the implementation plan from the approved design, as `.specs/` already does for every other subsystem.
|
||||
|
||||
### Task 3.3: Rewrite the observability paragraph in `README.md`
|
||||
|
||||
`README.md:246` currently reads "**No observability layer, either.**" and points at issue #10. When #10 lands, that paragraph is wrong and it is the single most load-bearing sentence in the CTO's assessment. Rewriting it is part of the work, not follow-up.
|
||||
|
||||
`AGENTS.md:83`: new public API needs a note in `README.md`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Split the documentation site
|
||||
|
||||
Verified before scheduling: `website/` is self-contained. 26 source files, no path escaping the directory, and the `@green-tea/core` mentions inside the `.md` files are example code, not build-time imports.
|
||||
|
||||
The coupling to core is five lines:
|
||||
|
||||
| Location | What |
|
||||
|---|---|
|
||||
| `.github/workflows/ci.yml:62-65` | `npm ci --prefix website`, `npm audit --prefix website`, `npm run docs:build` |
|
||||
| `package.json:100-101` | `docs:dev`, `docs:build` |
|
||||
|
||||
Plus two README references to update: `README.md:254` (the docs link) and `README.md:263` (`npm run docs:dev`).
|
||||
|
||||
**The real work is not the move.** No workflow anywhere in `.github/workflows/` deploys the site. `website/astro.config.mjs:6` points at `green-tea.expressive-tea.io` and the deploy happens by hand today. The new repository is where that pipeline gets built for the first time.
|
||||
|
||||
### Task 4.1: Create the repository and move `website/` with its history
|
||||
|
||||
Preserve commit history for the moved directory rather than landing it as one squashed import.
|
||||
|
||||
### Task 4.2: Build the deploy pipeline
|
||||
|
||||
The thing the docs never had. Build on push to the default branch, deploy to `green-tea.expressive-tea.io`.
|
||||
|
||||
### Task 4.3: Remove the website from core
|
||||
|
||||
Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`. Update `README.md:254` and `README.md:263`.
|
||||
|
||||
### Task 4.4: Guard the seam the split opens
|
||||
|
||||
The split trades CI coupling for drift risk: docs and code can now disagree without anything failing. #18 exists precisely because docs fell behind an API change. Decide what catches that — a link check against the published package, a docs job triggered from core releases, or an explicit accepted risk written down. Do not leave it unstated.
|
||||
|
||||
**Resolved 2026-08-17: accepted risk, stated where the rule is read rather than where it is published.** The first pass put it in both READMEs and stopped there, which satisfies the letter of "do not leave it unstated" and little else — the core README's copy sits in *Docs & development*, a section a user reads and a contributor changing an API does not.
|
||||
|
||||
What governs behaviour is `AGENTS.md:83` and the pre-PR checklist in `CONTRIBUTING.md`, both of which already carried *"New public API needs a note in `README.md`"* — written before the split and never updated for it, so the two documents that a contributor (or an assistant) actually reads mid-change said nothing about the new repository. Both now name it and say why the rule exists, since a rule without its reason is the first one dropped under time pressure.
|
||||
|
||||
**The link check was prototyped and then rejected, on measurement rather than taste.** It had been recommended here as the one worth building; building enough of it to decide showed otherwise.
|
||||
|
||||
- Every symbol the pages import is real: **24 distinct imports from `@green-tea/core` across 25 pages, all present** among the package's 101 exports. No bug for it to find today.
|
||||
- More decisively, **an import check could not have caught #18**. That issue was *"docs still describe `close()` without the timeout"* — the method existed; the **option** was undocumented. Imports are the part that does not drift. Options, option shapes and method signatures are.
|
||||
- Extending it to options and methods was tried and produced **17 findings, all 17 false** — a regex cannot tell a nested `tls: { key, cert }` from a top-level option, `app.example.com` in a CORS example from an `app.*` call, or prose describing Express's `app.use()` from a green-tea API. A check with that signal-to-noise trains people to ignore it, which is worse than not having one.
|
||||
- What would genuinely catch #18's class is **type-checking the code blocks** (twoslash / Expressive Code). That requires the documentation repository to depend on `@green-tea/core` and its examples to be complete and compilable — many are deliberately fragments. It buys the guarantee back by spending exactly the independence this split was for.
|
||||
|
||||
So the accepted risk stands, now as an informed choice rather than a default. A **docs job triggered from core releases** was the other option and remains the weaker one: it fires after the API has already shipped.
|
||||
|
||||
One page is covered by more than a rule: `test/circuit-breaker-recipe.test.ts` executes the recipe published in `guides/circuit-breaker.md`. That is one page of twenty-five, and is not a substitute for the check above.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4.5: Move the JSR gate off the tag — **run this before Task 2.5's code**
|
||||
|
||||
Numbered as an insertion because that is what it is, the same way Task 2.5 was. It is small, and its position is the whole point: **Task 2.5 adds public API** — `Hooks`, `TeardownFn`, `PluginApi.onShutdown` — and exported types are exactly what JSR's slow-types check polices. Writing that surface with no JSR gate on pull requests means learning at release time whether the shape is publishable.
|
||||
|
||||
Verified before writing this, because the first reading was wrong: `release.yml:42` **already** runs `deno publish --dry-run`, before publishing to either registry, and its comment already makes the argument — *"JSR checks things npm never looks at — slow types, module analysis — and learning about them after npm has published leaves the tag half-shipped."* Phase 1 already published to JSR, and a dry run passes today, slow-types check included.
|
||||
|
||||
The gap is not that the gate is missing. It is **when it runs**: only on a version tag. A change that breaks Deno's type-checker or introduces a slow type lands on `main` in silence and surfaces while cutting a release — the moment `release.yml`'s own npm-audit comment identifies as having the least time to judge a fix. The workflow makes that argument for advisories and not for JSR.
|
||||
|
||||
Worth stating plainly: `deno publish --dry-run` type-checks the four entry points with **Deno's** checker and lib, which is not the same pass as `tsc --noEmit -p tsconfig.json`. A second compiler over the same source is a real gate, not a formality — Task 1.1 exists because that second compiler found a hole the first one did not. And JSR serves `src/` directly, so anything it would reject is something a JSR user gets.
|
||||
|
||||
### Task 4.5.1: Run the JSR gate on every push and pull request
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
|
||||
Add `deno publish --dry-run` to the `runtimes` job's Deno leg, which already installs Deno. Measured at **0.68s** against 2.0s for the whole vitest suite — cheap enough that placing it anywhere else is over-thinking.
|
||||
|
||||
Leave `release.yml` alone. The tag-time gate stays: it is the one that protects an immutable JSR version, and a gate that runs twice is not a duplication worth removing.
|
||||
|
||||
### Task 4.5.2: One command for the whole matrix
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Modify: `README.md`
|
||||
|
||||
`npm test` is Node-only, deliberately — it is the fast local loop, 2s, and booting Deno, Bun and workerd into it would tax every run to catch what CI already catches on every push. The `runtimes` job means these suites are not unguarded; what is missing is a way for a contributor to run everything with one command before pushing.
|
||||
|
||||
Add `test:all` — `npm test` plus `test:deno`, `test:bun`, `test:edge`, and the JSR dry run. Say in `README.md` which one is the fast loop and which one is the pre-push check, so the split reads as a decision rather than an oversight.
|
||||
|
||||
### The decorator warning is expected — no task, and no new documentation
|
||||
|
||||
Every `deno publish --dry-run` prints:
|
||||
|
||||
```
|
||||
Warning experimentalDecorators compiler option is deprecated and may be removed at any time
|
||||
```
|
||||
|
||||
Whoever adds this gate to CI will see that warning arrive with it and should not treat it as something the gate found. It is **already documented, and better than a new note would manage**: `README.md:233` (*Why legacy decorators*) and `concepts/the-graph.md:43` in the docs repository both carry the reasoning — parameter decorators are deliberately absent from the TC39 Stage 3 proposal, so `handler(@param('id') id: string)` is only expressible with legacy decorators, and Stage 3 means the replacement is not finalized either.
|
||||
|
||||
An earlier draft of this phase claimed the framework "depends on `emitDecoratorMetadata`". That is **wrong**, and both documents already say so: argument positions are recorded explicitly, and `grep -rn 'design:type\|design:paramtypes' src/` returns nothing — the flag is set in `tsconfig.json` and `deno.json`, but no `design:*` reflection is read anywhere. Legacy parameter decorators are the only legacy surface this project actually depends on.
|
||||
|
||||
Do not turn the warning into an error to force the issue: that breaks releases on someone else's schedule.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Close #13 as documentation
|
||||
|
||||
### Task 5.1: Write the circuit-breaker recipe
|
||||
|
||||
**Files:**
|
||||
- Create: a guide page in the docs repository
|
||||
|
||||
The issue was opened to decide placement, not to commit to a core implementation, and it answers itself: core adding resilience policy would contradict the one-runtime-dependency rule. A circuit breaker fits a step — it needs whatever provides the client, it produces a guarded caller, and the graph already sequences it correctly.
|
||||
|
||||
Write it as a worked example, then close #13 pointing at the page. First real content in the new repository, which is also a live test of the deploy pipeline from Task 4.2.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: The stability contract
|
||||
|
||||
### Task 6.1: A stability paragraph in `Honest scope`
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
|
||||
Not a roadmap, and not the API freeze. A statement of which areas are volatile *today* — present state, no dates, no delivery commitment. This is spare-time work by one person and a roadmap it cannot keep would cost more trust than it earns.
|
||||
|
||||
`## Honest scope` (`README.md:240`) already carries exactly this voice: mesh is alpha, there is no observability layer, runtimes differ in what they can offer. The stability tiers belong in that section, in that register, as one paragraph.
|
||||
|
||||
Roughly the split the Trust Release report proposes in §8 — graph semantics, providers, steps and controllers as the stable candidates; decorator syntax, CLI and plugin APIs as beta; mesh and distributed capabilities as experimental. Verify each claim against the code before writing it down; a stability tier asserted and then broken is worse than none.
|
||||
|
||||
`README.md:266-276` keeps its `**next**` line unchanged. API freeze stays declared there and gets planned separately, near the RC.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
Per `AGENTS.md:28`, run before proposing any task as finished:
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run typecheck && npm test
|
||||
```
|
||||
|
||||
And from Phase 1 onward the runtime suites are no longer optional, because CI runs them:
|
||||
|
||||
```bash
|
||||
npm run test:deno && npm run test:bun && npm run test:edge
|
||||
```
|
||||
|
||||
Conventional Commits focused on the *why*, every commit signed off (`git commit -s`), no AI co-authoring attribution.
|
||||
@@ -0,0 +1,211 @@
|
||||
# Shutdown teardown — Design
|
||||
|
||||
**Task:** 2.5 in the [trust-release plan](./2026-08-16-trust-release-plan.md) · Trust Release §14, CTO P0-4 · **Status:** reviewed, D1–D8 settled · **Constraint:** no new runtime dependency
|
||||
|
||||
---
|
||||
|
||||
## The diagnosis
|
||||
|
||||
An application closing a database connection today writes `process.on('SIGTERM', …)` by hand, because the framework offers nowhere to put that. `closeApp` (`src/app/index.ts:1009`) closes mesh links, streams and the HTTP server, and knows nothing about plugins or providers. `LifecycleEvent` (`src/bus.ts:2`) has no shutdown event at all — a plugin cannot even *observe* that the app is closing, let alone act on it.
|
||||
|
||||
The framework owns the plumbing everywhere else. This is the hole.
|
||||
|
||||
### Why the existing `Bus` cannot carry it
|
||||
|
||||
`Bus.on` takes a synchronous listener (`src/bus.ts:62`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:85`). Both are deliberate: observers must never break the pipeline. A plugin closing a database connection needs shutdown to *wait for it*, and needs its failure to be visible.
|
||||
|
||||
The observability design already settled this rather than leaving it open — `D2` of [2026-08-16-observability-design.md](./2026-08-16-observability-design.md):
|
||||
|
||||
> **This is exactly why shutdown teardown does not belong here.** A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
|
||||
|
||||
Conceptually this is still an event — *"the app is closing, do you have anything to do first?"* — and callers may reasonably think of registering as subscribing. Mechanically it is a separate await-aware registry, because bending `Bus` to do both would cost the guarantee that makes `Bus` safe.
|
||||
|
||||
### What "isolation is structural" actually protects
|
||||
|
||||
`src/plugin.ts:26` reads *"Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural."* That sentence is load-bearing and it is easy to over-read, so this design states what it does and does not cover — verified against the code, because the answer surprised both people in the conversation that produced this document.
|
||||
|
||||
**Enforced today:**
|
||||
|
||||
- A plugin receives only `bus.on` and `scope.add` — no `emit`, so it cannot fabricate lifecycle events, and no reach into the registry.
|
||||
- `setRunner` (`src/app/index.ts:320`) throws on duplicate names, so a plugin cannot silently replace an existing provider or step.
|
||||
- Plugin nodes carry `origin: 'plugin'` and stay attributable in the graph.
|
||||
|
||||
**Not enforced today:**
|
||||
|
||||
- `runSteps` passes the live context object to every step and merges its output with `Object.assign(context, output)` (`src/pipeline.ts:73-74`). No collision check. A plugin's step can mutate the context directly and can overwrite any key another step provided.
|
||||
- `mountPlugins` (`src/app/index.ts:161`) runs *before* `provideBuiltins` (`:162`), and `provideBuiltins` skips anything already registered — so a plugin registering a node named `logger` or `rooms` replaces the builtin.
|
||||
|
||||
So the guarantee is about the **registration surface**, not about the **runtime context**. Teardown touches neither: it adds a third thing a plugin may register, and never sees a request context. The context-integrity question is real but pre-existing and out of scope here — it is recorded at the end so it is not lost.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1 — A teardown registry, not a `Bus` event
|
||||
|
||||
One list of callbacks, owned by the app, awaited on close. Not a `LifecycleEvent`, for the reason `D2` of the observability design already gives.
|
||||
|
||||
The registry is the entire mechanism. Everything below is a door into it.
|
||||
|
||||
### D2 — Three doors, one registry: one order, one failure policy
|
||||
|
||||
| Door | Who uses it | Shape |
|
||||
|---|---|---|
|
||||
| `hooks: [...]` in `createApp` | an application that wants lifecycle participation and nothing else | `onShutdown()` |
|
||||
| `PluginApi.onShutdown` | a plugin that also extends the graph | `onShutdown()` |
|
||||
| `dispose()` on a `@Provider` class | the provider that opened the resource | optional method |
|
||||
|
||||
Three entry points, **one** registry, **one** order, **one** failure policy. If they ever acquire separate ordering relative to each other, this design has failed and two mechanisms exist again.
|
||||
|
||||
The doors differ by intent, not by semantics. Today the only way into the lifecycle is to write a plugin, and a plugin means *"I want to extend the graph"* — someone who only wants to close a connection is forced to declare an extension they do not want.
|
||||
|
||||
### D3 — `PluginApi` gains a property; the `Plugin` signature does not change
|
||||
|
||||
`Plugin = (api: PluginApi) => void` is untouched. `onShutdown` joins `bus` and `scope` on the object a plugin already receives. Every existing plugin ignores it and behaves identically.
|
||||
|
||||
This is why the hooks framing is better than widening the plugin contract directly: it removes the only break the earlier sketch had. See "What breaks" below — the answer is now *nothing at runtime*.
|
||||
|
||||
### D4 — Teardown callbacks receive no arguments
|
||||
|
||||
```ts
|
||||
type TeardownFn = () => void | Promise<void>;
|
||||
```
|
||||
|
||||
State lives where the resource was created, and the closure already holds it:
|
||||
|
||||
```ts
|
||||
class MyPlugin {
|
||||
#db = new Pool();
|
||||
mount(api: PluginApi) {
|
||||
api.onShutdown(() => this.#db.end()); // the closure already has it
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A provider's `dispose()` is the same picture — the instance holds its own connection.
|
||||
|
||||
**Nothing needs to cross scopes**, which is what makes a container reference, an app reference, or any transport mechanism unnecessary here. A bus solves *"tell someone I do not know"*. Teardown is *"run this thing I registered"*. Handing a hook a resolver would make the container reachable from a hook and would be a genuine widening — declined.
|
||||
|
||||
If an argument is ever needed, adding one to a callback that receives none is additive. The reverse is not.
|
||||
|
||||
### D5 — Order is the reverse of boot
|
||||
|
||||
Providers boot in topological order (`bootProviders`, `src/app/index.ts:664`), so they tear down in reverse: if `cache` needs `db`, `cache` closes first. Registration order within the same tier is preserved.
|
||||
|
||||
Sequential, not parallel. Reverse-topological order only means something if it is respected, and parallel teardown discards it.
|
||||
|
||||
### D6 — A failing teardown is logged and shutdown continues
|
||||
|
||||
The failure goes to the injectable `Logger` and `close()` still resolves. One plugin's broken teardown must not strand the remaining ones or hang the process.
|
||||
|
||||
This mirrors `Bus`'s philosophy — a subscriber cannot break the system — but with the visibility `Bus` lacks. `Bus` swallows silently because no logger existed when it was written; one exists now.
|
||||
|
||||
The counter-argument was weighed and rejected: a `close()` that reports success after losing data is arguably worse than one that fails loudly. It loses because the alternative is worse in the common case — a process that will not exit is a worse operational failure than one that exited with a warning in the log, and the warning is not silent.
|
||||
|
||||
### D7 — Triggered from each runtime's real close
|
||||
|
||||
`app.close()` returns at its `if (!server)` guard on Deno, Bun and the edge (`src/app/index.ts:1026`). Hanging teardown off `app.close()` would make behaviour differ per runtime, which the multi-runtime constraint forbids.
|
||||
|
||||
| Runtime | Entry point |
|
||||
|---|---|
|
||||
| Node | `app.close()` → `closeApp` |
|
||||
| Deno | `serveDeno(app).close()` → `closeWithDeadline` |
|
||||
| Bun | `serveBun(app).close()` → `closeWithDeadline` |
|
||||
| edge (workerd) | **none — no shutdown exists** |
|
||||
|
||||
`serveDeno` and `serveBun` already receive the app, so their `close()` can run its teardown without the user calling two things. `closeWithDeadline` (`src/http/shutdown.ts`) is already shared by both *"so the two adapters cannot drift into different meanings of the same `timeoutMs`"* — the same argument applies here, and it is why teardown belongs in that shared function rather than in each adapter.
|
||||
|
||||
Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**: workerd never closes, so there is nothing to intercept. A plugin that depends on teardown for correctness is broken there. This is a runtime capability difference and belongs in the `runtimes.md` table beside `@Html` file mode and mesh, not in a footnote.
|
||||
|
||||
### D8 — Teardown shares the close budget, and `close()` never exceeds `timeoutMs`
|
||||
|
||||
`timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for.
|
||||
|
||||
- Drain runs first. Teardown runs after, within the same budget.
|
||||
- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one.
|
||||
- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
|
||||
- `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped.
|
||||
|
||||
An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement.
|
||||
|
||||
Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run.
|
||||
|
||||
---
|
||||
|
||||
## The contract
|
||||
|
||||
```ts
|
||||
/** A teardown callback. Receives nothing: state lives in the closure that registered it. */
|
||||
export type TeardownFn = () => void | Promise<void>;
|
||||
|
||||
/** Lifecycle participation without extending the graph. Methods are optional so later
|
||||
* stages (onBoot, onReady) can join without a breaking change. */
|
||||
export interface Hooks {
|
||||
onShutdown?: TeardownFn;
|
||||
}
|
||||
|
||||
/** Unchanged except for the third capability. `Plugin` keeps its signature. */
|
||||
export interface PluginApi {
|
||||
bus: { on: Bus['on'] };
|
||||
scope: ScopeApi;
|
||||
onShutdown(fn: TeardownFn): void;
|
||||
}
|
||||
|
||||
createApp({
|
||||
modules: [...],
|
||||
plugins: [...],
|
||||
hooks: [...], // new
|
||||
shutdownTimeoutMs: 10_000, // existing
|
||||
teardownTimeoutMs: 2_000, // new, optional; <= shutdownTimeoutMs
|
||||
});
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() { /* ... */ }
|
||||
async dispose() { /* optional; called if present */ }
|
||||
}
|
||||
```
|
||||
|
||||
### What this costs internally
|
||||
|
||||
`collectProviders` (`src/app/index.ts:345`) constructs each provider with `new ProviderClass()` and captures the instance in a closure. **The instance is never stored anywhere reachable**, and `Container.bindings` is private with no iteration, so there is no handle to call `dispose()` on today.
|
||||
|
||||
Keeping provider instances requires a new field on `Registry`. That is internal, not public API, and it is the part nobody sees coming from reading "add `onShutdown` to `PluginApi`".
|
||||
|
||||
### What breaks
|
||||
|
||||
**At runtime: nothing.** `Plugin`'s signature is unchanged, `Hooks` methods are optional, and `dispose()` is called only if present.
|
||||
|
||||
**At compile time: nothing either**, given D3. Widening `PluginApi` would have broken anyone constructing one as a literal — typically a test mock — but `onShutdown` is a required property on an object the framework builds and hands out, never one a user implements. Should that turn out to be wrong for some consumer, it goes in the CHANGELOG with the reason: making it optional would force every plugin to check for it and would turn a capability into a conditional forever.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope, deliberately
|
||||
|
||||
- **`onBoot` / `onReady`.** `Hooks` is shaped as an object of optional methods so they can be added without a breaking change, but only `onShutdown` ships. The shape accommodates them; this design does not build them.
|
||||
- **Request-scope cleanup.** Request values are recomputed per resolve (`src/container.ts`) and are garbage, not resources. Only app-scope teardown is in scope.
|
||||
- **Edge teardown.** Not possible. Documented, not worked around.
|
||||
- **A context argument for teardown callbacks.** D4. Additive later if a real case appears.
|
||||
- **Context integrity.** A plugin's step can overwrite context keys and can replace the `logger` and `rooms` builtins. Real, pre-existing, unrelated to teardown, and recorded here only so the finding is not lost with this conversation.
|
||||
|
||||
---
|
||||
|
||||
## Verification this design must survive
|
||||
|
||||
1. A plugin registering `onShutdown` has it awaited before `close()` resolves — on Node, Deno and Bun, asserted per runtime rather than once.
|
||||
2. A provider with `dispose()` has it called; one without is skipped.
|
||||
3. Reverse-topological order: `cache` needing `db` tears down first.
|
||||
4. A throwing teardown is logged and the remaining ones still run; `close()` resolves.
|
||||
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
|
||||
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
|
||||
8. `close()` on an app with no teardown registered costs nothing measurable — this is not a request path, but it is still on the shutdown path of every app that uses none of it.
|
||||
|
||||
## Documentation this design changes
|
||||
|
||||
All of these now live in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs):
|
||||
|
||||
- `guides/plugins.md:7` — states plugins have exactly two capabilities. Becomes three, and the isolation wording needs the precision from the diagnosis above rather than a restatement.
|
||||
- `guides/runtimes.md:44` — the shutdown table gains teardown, and edge gains its exception.
|
||||
- `guides/dependency-injection.md:56` — describes what `close()` does; it now does one more thing.
|
||||
- `README.md` — new public API, per `AGENTS.md:83`.
|
||||
@@ -0,0 +1,141 @@
|
||||
# Shutdown teardown — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Design:** [2026-08-17-shutdown-teardown-design.md](./2026-08-17-shutdown-teardown-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
|
||||
|
||||
**Goal:** Give plugins, providers and applications somewhere to put teardown, so closing a database connection stops meaning `process.on('SIGTERM', …)` by hand. Closes Task 2.5 of the [trust-release plan](./2026-08-16-trust-release-plan.md); Trust Release §14, CTO P0-4.
|
||||
|
||||
**Architecture:** A new `src/lifecycle.ts` holds the registry and nothing else. `src/plugin.ts` and `src/app/index.ts` gain doors into it; `src/app/index.ts` (`closeApp`) and `src/http/shutdown.ts` (`closeWithDeadline`) gain the call that drains it. No new runtime dependency — `reflect-metadata` stays the only one.
|
||||
|
||||
**The thing to keep hold of:** three doors, one registry, one order, one failure policy. Any task that gives a door its own ordering or its own error handling has broken D2, whatever the tests say.
|
||||
|
||||
---
|
||||
|
||||
## Order
|
||||
|
||||
Tasks 1–3 build the mechanism and the doors; nothing observable changes until Task 4 wires it into `close()`. Task 5 is the runtime parity that D7 demands and is the one most likely to surface a surprise, so it does not go last. Documentation is Task 7 because it should describe the finished API rather than be rewritten twice.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: The registry
|
||||
|
||||
**Files:**
|
||||
- Create: `src/lifecycle.ts`
|
||||
- Create: `test/lifecycle.test.ts`
|
||||
|
||||
The whole mechanism, with no knowledge of plugins, providers, apps or HTTP.
|
||||
|
||||
```ts
|
||||
export type TeardownFn = () => void | Promise<void>;
|
||||
```
|
||||
|
||||
It needs: register a callback, and run everything registered — sequentially, in reverse registration order (D5), awaiting each, catching each (D6), never throwing. A failing callback is reported through the injectable `Logger` and the next one still runs.
|
||||
|
||||
Keep the timeout **out** of here. Bounding is the caller's job, and it is already solved twice over by `closeApp` and `closeWithDeadline`; a third implementation is how the three drift into different meanings of the same number.
|
||||
|
||||
Tests: order is reverse of registration; a throwing callback is logged and does not stop the rest; a rejecting async callback is treated the same; an empty registry resolves; running twice does not re-run callbacks (`close()` is called twice by more real applications than anyone expects).
|
||||
|
||||
### Task 2: The plugin and hook doors
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugin.ts`
|
||||
- Modify: `src/app/index.ts` — `mountPlugins`, `createApp` options
|
||||
- Modify: `src/app/types.ts` — `Hooks` on the public options
|
||||
- Modify: `test/plugin.test.ts`
|
||||
|
||||
`PluginApi` gains `onShutdown(fn: TeardownFn): void`, bound to the app's registry. `mountPlugin`'s comment at `src/plugin.ts:26` currently says a plugin gets `on()` and `add()` and nothing else; it now gets three things, and the comment says which and why — the isolation wording in the design's diagnosis is the precise version, not "isolation is gone".
|
||||
|
||||
`createApp({ hooks })` takes `Hooks[]`, an object of optional methods so `onBoot`/`onReady` can join later without a breaking change. Only `onShutdown` exists now.
|
||||
|
||||
Tests: a plugin registering `onShutdown` lands in the registry; a plugin that never calls it behaves exactly as before (D3 — this is the no-break guarantee, so it gets an explicit test rather than an assumption); hooks and plugins interleave in one order rather than running as two groups.
|
||||
|
||||
### Task 3: Provider `dispose()`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/index.ts` — `collectProviders`, `Registry`
|
||||
- Modify: `test/app.test.ts`
|
||||
|
||||
`collectProviders` (`src/app/index.ts:345`) builds each provider with `new ProviderClass()` and captures the instance in a closure where nothing can reach it. Keep the instances on `Registry` so a `dispose()` can be called.
|
||||
|
||||
Registration order must follow boot order, not declaration order, so that D5's reverse-topological teardown falls out of the registry's reverse-registration rule rather than needing a second sort. That means registering a provider's `dispose()` as it boots in `bootProviders` (`:664`), not when it is collected.
|
||||
|
||||
A provider that failed to boot must not have `dispose()` called — it never provided anything. Optional providers that degraded (`degradedProviders`) are exactly this case and already tracked.
|
||||
|
||||
Tests: `dispose()` is called; a provider without one is skipped; `cache` needing `db` tears down first; a provider that failed to boot is not disposed.
|
||||
|
||||
### Task 4: Drain the registry on close — Node
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/index.ts` — `closeApp`
|
||||
- Modify: `test/app.test.ts`
|
||||
|
||||
Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining.
|
||||
|
||||
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
|
||||
|
||||
`closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering.
|
||||
|
||||
Tests: a registered teardown is awaited before `close()` resolves; a hanging teardown does not let `close()` exceed `timeoutMs`; a slow drain plus a set `teardownTimeoutMs` still leaves teardown its reserved slice; `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
|
||||
### Task 5: Runtime parity — Deno and Bun
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/shutdown.ts` — `closeWithDeadline`
|
||||
- Modify: `src/deno.ts`, `src/bun.ts`
|
||||
- Modify: `test/deno/*`, `test/bun/*`
|
||||
|
||||
`app.close()` returns at its `if (!server)` guard on Deno and Bun (`src/app/index.ts:1026`), so teardown cannot hang off it without behaviour differing per runtime — which the multi-runtime constraint forbids (D7).
|
||||
|
||||
`serveDeno(app)` and `serveBun(app)` already hold the app, so their `close()` runs the teardown and the user calls one thing, not two. It goes in `closeWithDeadline` rather than in each adapter, for the reason that function already exists: so the two cannot drift into different meanings of the same `timeoutMs`.
|
||||
|
||||
Deno cannot escalate from graceful to forced — its deadline bounds how long `close()` waits, not when connections die. That asymmetry already exists and this must not make it worse.
|
||||
|
||||
These suites are **not** in `npm test`. Run `npm run test:deno` and `npm run test:bun` explicitly, and do not report this task done on the strength of vitest passing.
|
||||
|
||||
Tests, per runtime rather than once: a teardown registered on a Deno/Bun app is awaited by that server's `close()`.
|
||||
|
||||
### Task 6: Edge — document the hole, do not paper over it
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/edge.ts` — doc comment only
|
||||
|
||||
workerd never closes, so there is nothing to intercept and no design fixes it. A plugin depending on teardown for correctness is broken there.
|
||||
|
||||
No shim, no fake `close()`, no best-effort call on an unload event that does not exist. The only change is a doc comment stating it, so someone reading `edgeHandler` learns it there rather than in production. The user-facing half is Task 7.
|
||||
|
||||
### Task 7: Documentation
|
||||
|
||||
**Files:** all in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)
|
||||
- Modify: `src/content/docs/guides/plugins.md` — line 7 says plugins have exactly two capabilities; it is three now, and the isolation sentence needs the design's precision rather than a restatement
|
||||
- Modify: `src/content/docs/guides/runtimes.md` — the shutdown table gains teardown, and edge gains its row
|
||||
- Modify: `src/content/docs/guides/dependency-injection.md` — line 56 describes what `close()` does
|
||||
- Modify: `README.md` in core — new public API, per `AGENTS.md:83`
|
||||
- Modify: `CHANGELOG.md` in core
|
||||
|
||||
Two repositories, one change. This is the first real test of the seam Phase 4 opened, and nothing fails if it is skipped — which is the point of doing it in the same session rather than leaving it to a follow-up.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope
|
||||
|
||||
- `onBoot` / `onReady`. `Hooks` is shaped to accommodate them; this plan does not build them.
|
||||
- Request-scope cleanup. Request values are recomputed per resolve and are garbage, not resources.
|
||||
- Edge teardown. Not possible.
|
||||
- A context argument for teardown callbacks (D4). Additive later if a real case appears.
|
||||
- Context integrity — a plugin's step can overwrite context keys and replace the `logger` and `rooms` builtins. Real, pre-existing, and recorded in the design's out-of-scope section so it is not lost.
|
||||
|
||||
## Verification
|
||||
|
||||
The design's list, restated as the gate for calling this done:
|
||||
|
||||
1. A plugin's `onShutdown` is awaited before `close()` resolves — asserted on Node, Deno and Bun separately.
|
||||
2. A provider with `dispose()` has it called; one without is skipped; one that failed to boot is not disposed.
|
||||
3. Reverse-topological order: `cache` needing `db` tears down first.
|
||||
4. A throwing teardown is logged, the rest still run, `close()` resolves.
|
||||
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
|
||||
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
|
||||
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
|
||||
8. `close()` on an app with no teardown registered costs nothing measurable.
|
||||
|
||||
Plus the gates every change here passes: `npm run lint`, `npm run complexity:check`, `npm run typecheck`, `npm test`, and — because Task 5 exists — `npm run test:deno`, `npm run test:bun`, `npm run test:edge`.
|
||||
@@ -0,0 +1,82 @@
|
||||
# A teapot that may be absent, declared per teapot
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
|
||||
**Mesh stays alpha.**
|
||||
|
||||
## The decision
|
||||
|
||||
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
|
||||
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
|
||||
away is a degraded checkout; an authorization provider being away is not a degraded anything.
|
||||
|
||||
```ts
|
||||
mesh: {
|
||||
teapots: [
|
||||
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
|
||||
{ url: authUrl, secret }, // 'fail' — the default
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Why `expects` is required for `'degrade'`, and not inferred
|
||||
|
||||
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
|
||||
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
|
||||
validation fails the boot anyway — degrading would fail identically, just later.
|
||||
|
||||
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
|
||||
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
|
||||
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
|
||||
loudly.
|
||||
|
||||
It also pushes the developer to state what a service depends on, which is the same discipline the
|
||||
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
|
||||
`expects`, naming the teapot.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
|
||||
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
|
||||
and throws `503`, naming the token and the teapot it belongs to.
|
||||
|
||||
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
|
||||
simply do not exist locally, because a route needs a method and a pattern we were never told. A
|
||||
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
|
||||
silent.
|
||||
|
||||
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
|
||||
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
|
||||
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
|
||||
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
|
||||
logged and emitted.
|
||||
|
||||
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
|
||||
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
|
||||
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
|
||||
|
||||
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
|
||||
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
|
||||
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
|
||||
instead of a boot manifest.
|
||||
|
||||
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
|
||||
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
|
||||
wrong, not a reason to write a second one.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
|
||||
`expects`.
|
||||
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
|
||||
3. `degraded()` reporting per D3, plus the warn and the event.
|
||||
4. Background attempt loop per D4, and adoption per D5/D6.
|
||||
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
|
||||
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
|
||||
refused, and `'degrade'` without `expects` fails at `createApp`.
|
||||
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
|
||||
|
||||
## Size
|
||||
|
||||
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
|
||||
three runtimes. Not a follow-up to squeeze into another change.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Mesh reconnection, with a refusing manifest policy
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
|
||||
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
|
||||
unusable in production; it does not move the label, because the label is a statement about how much
|
||||
we know, and we will know more once this runs somewhere real.
|
||||
|
||||
## The problem
|
||||
|
||||
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
|
||||
serially and throwing on any failure (`src/app/index.ts:631`):
|
||||
|
||||
- a teapot down at boot → the teacup does not start;
|
||||
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
|
||||
|
||||
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
|
||||
load-bearing. That is a worse operational property than any gap currently written in the docs.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
|
||||
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
|
||||
words must not be used interchangeably in code, CHANGELOG or docs.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
|
||||
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
|
||||
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
|
||||
`connectLink` becomes "establish, then keep established".
|
||||
|
||||
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
|
||||
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
|
||||
configured" with "this dependency is temporarily away".
|
||||
|
||||
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
|
||||
heartbeat, so reconnection never holds a process open on its own.
|
||||
|
||||
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
|
||||
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
|
||||
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
|
||||
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
|
||||
|
||||
Rationale: the graph was validated at boot against the old manifest and is already running. A token
|
||||
that vanished cannot be validated away after the fact, and serving requests against a manifest that
|
||||
no longer backs the graph is how you get a 500 that looks like application code.
|
||||
|
||||
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
|
||||
not spliced in. Documented, not silent.
|
||||
|
||||
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
|
||||
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
|
||||
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
|
||||
|
||||
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
|
||||
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
|
||||
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
|
||||
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
|
||||
place to be breaking.
|
||||
|
||||
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
|
||||
provider is resolved once at boot and frozen into the container as `() => value`
|
||||
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
|
||||
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
|
||||
call on the reconnect path, where its failure has nowhere to go. This closes the documented
|
||||
"app-scope export survives its teapot with a stale value" gap.
|
||||
|
||||
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
|
||||
inline in the reconnect handler — that function is what reconciliation will reuse.
|
||||
|
||||
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
|
||||
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
|
||||
cannot exit.
|
||||
|
||||
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
|
||||
not a wait for `timeoutMs`.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
|
||||
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
|
||||
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
|
||||
`mesh:connect` on success (existing events; no new bus contract in alpha).
|
||||
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
|
||||
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
|
||||
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
|
||||
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
|
||||
Reconnect defaults **on**. Validate at boot like the other mesh options.
|
||||
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
|
||||
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
|
||||
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
|
||||
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
|
||||
where a swappable socket can break.
|
||||
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
|
||||
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
|
||||
a defect, not a feature.
|
||||
|
||||
## Not in this plan
|
||||
|
||||
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
|
||||
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
|
||||
@@ -1,516 +0,0 @@
|
||||
# green-tea — Quickstart
|
||||
|
||||
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
|
||||
graph**. You declare what you need; the framework computes the order, validates it at boot,
|
||||
and can extend the graph over time (streams) and across machines (mesh).
|
||||
|
||||
See [architecture.md](./architecture.md) for the mental map.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core reflect-metadata
|
||||
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
|
||||
npm install ws # optional
|
||||
```
|
||||
|
||||
`tsconfig.json` must enable decorator metadata:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"target": "es2017",
|
||||
"module": "commonjs"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Import `reflect-metadata` once at your entrypoint.
|
||||
|
||||
## 1. A route with dependency injection
|
||||
|
||||
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
|
||||
context. A handler's **argument decorators are its dependency declaration** — ask for what
|
||||
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
|
||||
not an `undefined` at runtime.
|
||||
|
||||
```typescript
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Database {
|
||||
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx: any) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
|
||||
return { user }; // return = continue, merge into ctx
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Get('/:id')
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { requested: id, you: user }; // auto-serialized as JSON
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
await app.listen(3000);
|
||||
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
|
||||
|
||||
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
|
||||
```
|
||||
|
||||
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
|
||||
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
|
||||
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
|
||||
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
|
||||
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
|
||||
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
|
||||
> that don't declare it.
|
||||
|
||||
### Argument decorators
|
||||
|
||||
| Decorator | Reads from | Adds a graph dependency? |
|
||||
|---|---|---|
|
||||
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
|
||||
| `@ctx()` | the whole accumulated context | no |
|
||||
| `@param('id')` | route params | no |
|
||||
| `@query('q')` | parsed query string | no |
|
||||
| `@body()` | parsed JSON body | no |
|
||||
| `@headers('x')` | request headers | no |
|
||||
| `@inbound()` | the incoming WS message channel | no (WS only) |
|
||||
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
|
||||
|
||||
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
|
||||
`@query(['q','date'])` (subset).
|
||||
|
||||
## 2. Compile-time guarantee with `flow`
|
||||
|
||||
The decorator layer validates the graph at boot. The functional core `flow` validates it in
|
||||
the **type checker**:
|
||||
|
||||
```typescript
|
||||
import { flow } from '@green-tea/core';
|
||||
|
||||
const pipeline = flow()
|
||||
.step('db', () => ({ find: (id: string) => id }))
|
||||
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
|
||||
```
|
||||
|
||||
## 3. Streaming — SSE
|
||||
|
||||
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
|
||||
transport frames it, handles backpressure, and cleans up on disconnect).
|
||||
|
||||
```typescript
|
||||
import { Route, Sse } from '@green-tea/core';
|
||||
|
||||
@Route('/feed')
|
||||
class FeedController {
|
||||
@Sse('/ticks')
|
||||
ticks() {
|
||||
return (async function* () {
|
||||
for (let n = 1; n <= 3; n++) yield { tick: n };
|
||||
})();
|
||||
}
|
||||
}
|
||||
// GET /feed/ticks (Accept: text/event-stream)
|
||||
// data: {"tick":1}
|
||||
// data: {"tick":2}
|
||||
// data: {"tick":3}
|
||||
```
|
||||
|
||||
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
|
||||
`Upgrade: websocket` → WS, else ndjson chunked).
|
||||
|
||||
## 4. Streaming — WebSocket duplex
|
||||
|
||||
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
|
||||
that consumes one channel and produces another.
|
||||
|
||||
```typescript
|
||||
import { Route, Ws, inbound, channel } from '@green-tea/core';
|
||||
|
||||
@Route('/chat')
|
||||
class ChatController {
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => {
|
||||
for await (const msg of incoming) out.push(`echo: ${msg}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
|
||||
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
|
||||
|
||||
## 5. Mesh — distributed dependency injection
|
||||
|
||||
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
|
||||
opt-in (`export: true`) and the control channel is gated by a shared secret.
|
||||
|
||||
**Node A — teapot (exposes `config`, `auth`, and a route):**
|
||||
|
||||
```typescript
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
|
||||
|
||||
@Route('/svc')
|
||||
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
|
||||
class TeapotModule {}
|
||||
|
||||
const teapot = createApp({ modules: [TeapotModule], mesh: { secret: 'shh' } });
|
||||
await teapot.listen(3002);
|
||||
```
|
||||
|
||||
**Node B — teacup (uses `config` + `auth` with no local providers):**
|
||||
|
||||
```typescript
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth }; // both resolved by RPC to the teapot
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
|
||||
});
|
||||
await teacup.listen(3003);
|
||||
// GET B:3003/api/local/who (x-token: abc)
|
||||
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
|
||||
```
|
||||
|
||||
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
|
||||
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
|
||||
request-scope (RPC per request, carrying the request envelope).
|
||||
|
||||
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
|
||||
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
|
||||
|
||||
## 6. Plugins & observability
|
||||
|
||||
```typescript
|
||||
const logger = (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
|
||||
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
|
||||
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
|
||||
};
|
||||
|
||||
const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
```
|
||||
|
||||
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
||||
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||
|
||||
## 7. Transport security
|
||||
|
||||
Four `createApp` options cover TLS, proxying, CORS, and response headers.
|
||||
|
||||
### TLS (native https/wss)
|
||||
|
||||
```typescript
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const app = createApp({
|
||||
modules: [App],
|
||||
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
||||
});
|
||||
```
|
||||
|
||||
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
|
||||
port — no other changes.
|
||||
|
||||
### `trustProxy`
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [App], trustProxy: true });
|
||||
```
|
||||
|
||||
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
|
||||
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
|
||||
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
|
||||
unconditionally; there's no CIDR allowlist yet.
|
||||
|
||||
### CORS
|
||||
|
||||
Off unless `origins` is set.
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [App],
|
||||
cors: { origins: 'https://app.example.com', credentials: true },
|
||||
});
|
||||
```
|
||||
|
||||
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||
request (with `Access-Control-Request-Method`) is auto-answered with 204.
|
||||
|
||||
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
|
||||
echoes the concrete allowed origin (or blocks the request).
|
||||
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
|
||||
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
|
||||
you truly intend an open credentialed API; prefer an explicit allowlist.
|
||||
|
||||
### `security` (headers, ON by default)
|
||||
|
||||
Applied to every HTTP response. Disable everything with `security: false`, or override
|
||||
individual headers with an options object.
|
||||
|
||||
| Header | Default |
|
||||
|---|---|
|
||||
| `X-Content-Type-Options` | `nosniff` |
|
||||
| `X-Frame-Options` | `SAMEORIGIN` |
|
||||
| `Referrer-Policy` | `no-referrer` |
|
||||
| `X-DNS-Prefetch-Control` | `off` |
|
||||
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
|
||||
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
|
||||
```
|
||||
|
||||
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
|
||||
to the WebSocket handshake (101/upgrade) response.
|
||||
|
||||
### Defaults
|
||||
|
||||
| Option | Default |
|
||||
|---|---|
|
||||
| `tls` | off (plain http/ws) |
|
||||
| `trustProxy` | off |
|
||||
| `cors` | off (same-origin only) |
|
||||
| `security` | ON (HSTS only when the connection is secure) |
|
||||
|
||||
## 8. File uploads / multipart
|
||||
|
||||
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
|
||||
instead of a plain object:
|
||||
|
||||
```typescript
|
||||
import { Route, Post, body } from '@green-tea/core';
|
||||
import type { MultipartBody } from '@green-tea/core';
|
||||
|
||||
@Route('/profile')
|
||||
class ProfileController {
|
||||
@Post('/avatar')
|
||||
upload(@body() form: MultipartBody) {
|
||||
const name = form.fields.name; // string | string[]
|
||||
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
|
||||
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
|
||||
in memory, no temp files.
|
||||
|
||||
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
|
||||
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
|
||||
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
|
||||
> itself with `@body('fields')` / `@body('files')`.
|
||||
|
||||
### Repeated fields — `bodyDuplicates`
|
||||
|
||||
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
|
||||
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
|
||||
this applies to **both** urlencoded and multipart text fields:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
|
||||
```
|
||||
|
||||
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
|
||||
`bodyDuplicates`.
|
||||
|
||||
### Per-endpoint override
|
||||
|
||||
```typescript
|
||||
@Post('/upload', { duplicates: 'array' })
|
||||
upload(@body() form: MultipartBody) { /* ... */ }
|
||||
```
|
||||
|
||||
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
|
||||
|
||||
### Limits
|
||||
|
||||
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
|
||||
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
|
||||
multipart parts per request:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||
```
|
||||
|
||||
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
|
||||
|
||||
## 9. Validation
|
||||
|
||||
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
|
||||
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
|
||||
and others). green-tea's core has **zero runtime dependency** on any of them — bring
|
||||
whichever validator you already use:
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
import { Route, Post, body } from '@green-tea/core';
|
||||
|
||||
const CreateUser = z.object({ email: z.string().email() });
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Post('/')
|
||||
create(@body(CreateUser) user: { email: string }) {
|
||||
return { created: user.email };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The value the handler receives is the schema's **parsed/coerced output**, not the raw
|
||||
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
|
||||
parsed. Query strings are always strings on the wire, so a schema is often the coercion
|
||||
point:
|
||||
|
||||
```typescript
|
||||
const ListQuery = z.object({ page: z.coerce.number() });
|
||||
|
||||
@Get('/list')
|
||||
list(@query(ListQuery) q: { page: number }) {
|
||||
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
|
||||
}
|
||||
```
|
||||
|
||||
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
|
||||
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
|
||||
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
|
||||
> the whole parsed object (all of `body`/`query`/`headers`).
|
||||
|
||||
A failing schema short-circuits the request with **422**:
|
||||
|
||||
```json
|
||||
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
|
||||
```
|
||||
|
||||
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
|
||||
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
|
||||
|
||||
**Caveats:**
|
||||
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
|
||||
the same handler are not checked in that request.
|
||||
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
|
||||
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
|
||||
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
|
||||
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
|
||||
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
|
||||
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
|
||||
|
||||
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
|
||||
mesh remote-route validation are all out of scope for this feature.
|
||||
|
||||
## Inspect & test the graph
|
||||
|
||||
### Visualize with Mermaid
|
||||
|
||||
```typescript
|
||||
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
||||
```
|
||||
|
||||
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devGraph: true });
|
||||
// GET /__graph__ → HTML viewer
|
||||
// GET /__graph__ (text/plain) → raw Mermaid source
|
||||
```
|
||||
|
||||
### Explain a route
|
||||
|
||||
```typescript
|
||||
const e = app.explain('/api/users/:id');
|
||||
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
|
||||
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
|
||||
// → ['provider:db', 'step:user', 'handler:getUser']
|
||||
```
|
||||
|
||||
### Override tokens in tests
|
||||
|
||||
Swap any provider or step token with a test double at construction time — no monkey-patching:
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
overrides: {
|
||||
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
|
||||
user: () => ({ user: { id: 'stub' } }), // function runner
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Overrides replace only the named token's runner; the rest of the graph is untouched.
|
||||
|
||||
## Runnable examples
|
||||
|
||||
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
||||
|
||||
### CRUD — methods, query, JSON & urlencoded body
|
||||
|
||||
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
||||
read the payload via `@body()` — the same handler accepts both `application/json` and
|
||||
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
||||
rows throw `NotFound` (→ 404).
|
||||
|
||||
See [`example/crud.ts`](../example/crud.ts).
|
||||
|
||||
### Chat — rooms + handshake auth
|
||||
|
||||
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
||||
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
|
||||
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
|
||||
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
|
||||
primitive (one instance app-wide).
|
||||
|
||||
See [`example/chat.ts`](../example/chat.ts).
|
||||
|
||||
### GraphQL — query/mutation over POST, subscription over SSE
|
||||
|
||||
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
||||
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
||||
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
||||
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
||||
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
||||
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
||||
|
||||
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
||||
|
||||
## The one rule to remember
|
||||
|
||||
```
|
||||
return a VALUE → buffered response (transformer → JSON)
|
||||
return an AsyncIterable → stream (SSE / WS)
|
||||
@needs a remote token → RPC to a teapot (mesh)
|
||||
```
|
||||
@@ -0,0 +1,34 @@
|
||||
import js from '@eslint/js';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist', 'node_modules', 'bench', 'coverage'] },
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
plugins: { '@stylistic': stylistic },
|
||||
rules: {
|
||||
// The request pipeline accumulates a dynamic context object by design;
|
||||
// `any` there is load-bearing, not laziness. Flag it as a warning so new
|
||||
// uses are visible without failing the build.
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
|
||||
// Breathing room around multi-line blocks (for/while/if/function/class) so
|
||||
// consecutive blocks don't read as one wall of code. Auto-fixable.
|
||||
'@stylistic/padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', prev: 'multiline-block-like', next: '*' },
|
||||
{ blankLine: 'always', prev: '*', next: 'multiline-block-like' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// 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' },
|
||||
},
|
||||
);
|
||||
+1
-1
@@ -101,7 +101,7 @@ class PingController {
|
||||
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
|
||||
class TeapotModule {}
|
||||
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } });
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
|
||||
|
||||
@Route('/remote')
|
||||
class TeacupController {
|
||||
|
||||
Generated
+4359
-327
File diff suppressed because it is too large.
Load diff
+130
-14
@@ -1,47 +1,163 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "0.0.0",
|
||||
"description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.",
|
||||
"version": "26.8.0-beta.1",
|
||||
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
||||
"license": "MIT",
|
||||
"author": "green-tea contributors <projects@expressive-tea.io>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/Expressive-Tea/green-tea/issues",
|
||||
"email": "projects@expressive-tea.io"
|
||||
},
|
||||
"homepage": "https://green-tea.expressive-tea.io/docs/",
|
||||
"keywords": [
|
||||
"http",
|
||||
"framework",
|
||||
"typescript",
|
||||
"dependency-injection",
|
||||
"decorators",
|
||||
"dependency-graph",
|
||||
"sse",
|
||||
"websocket",
|
||||
"streaming",
|
||||
"node"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./deno": {
|
||||
"import": {
|
||||
"types": "./dist/deno.d.mts",
|
||||
"default": "./dist/deno.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/deno.d.ts",
|
||||
"default": "./dist/deno.js"
|
||||
}
|
||||
},
|
||||
"./bun": {
|
||||
"import": {
|
||||
"types": "./dist/bun.d.mts",
|
||||
"default": "./dist/bun.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/bun.d.ts",
|
||||
"default": "./dist/bun.js"
|
||||
}
|
||||
},
|
||||
"./edge": {
|
||||
"import": {
|
||||
"types": "./dist/edge.d.mts",
|
||||
"default": "./dist/edge.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/edge.d.ts",
|
||||
"default": "./dist/edge.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"assets",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:dev": "vitest",
|
||||
"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",
|
||||
"bench": "tsx bench/run.ts"
|
||||
"lint": "eslint src",
|
||||
"lint:fix": "eslint src --fix",
|
||||
"format": "prettier --write \"src/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\"",
|
||||
"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",
|
||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
"dependencies": {
|
||||
"reflect-metadata": "0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"busboy": "^1.6.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"busboy": {
|
||||
"optional": true
|
||||
},
|
||||
"ws": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"overrides": {
|
||||
"find-my-way": "9.7.0",
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/common": "^11.1.27",
|
||||
"@nestjs/core": "^11.1.27",
|
||||
"@nestjs/platform-express": "^11.1.27",
|
||||
"@nestjs/platform-fastify": "^11.1.27",
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@nestjs/common": "^11.1.28",
|
||||
"@nestjs/core": "^11.1.28",
|
||||
"@nestjs/platform-express": "^11.1.28",
|
||||
"@nestjs/platform-fastify": "^11.1.28",
|
||||
"@stylistic/eslint-plugin": "^5.10.0",
|
||||
"@types/autocannon": "^7.12.7",
|
||||
"@types/busboy": "^1.5.4",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"autocannon": "^8.0.0",
|
||||
"busboy": "^1.6.0",
|
||||
"cognitive-complexity-ts": "^0.8.2",
|
||||
"eslint": "^9.39.5",
|
||||
"esbuild": "0.27.2",
|
||||
"express": "^5.2.1",
|
||||
"fastify": "^5.10.0",
|
||||
"fastify": "^5.11.0",
|
||||
"graphql": "^16.9.0",
|
||||
"miniflare": "^4.20260730.0",
|
||||
"prettier": "^3.9.6",
|
||||
"rxjs": "^7.8.2",
|
||||
"tsx": "^4.23.0",
|
||||
"tsup": "^8.5.1",
|
||||
"tsx": "^4.23.5",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^6.4.3",
|
||||
"vitest": "^3.2.7",
|
||||
"ws": "^8.21.1"
|
||||
}
|
||||
}
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env node
|
||||
// Cognitive-complexity gate. Fails (exit 1) if any named function in src/ exceeds
|
||||
// the threshold, per cognitive-complexity-ts. Cyclomatic complexity is intentionally
|
||||
// NOT gated here — its `??`-chain false positives make it advisory only (npm run complexity:cyclomatic).
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
const THRESHOLD = Number(process.env.COMPLEXITY_MAX ?? 25);
|
||||
|
||||
let raw = '';
|
||||
try {
|
||||
raw = execSync('npx ccts-json src', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
} catch (error) {
|
||||
raw = error.stdout?.toString() ?? '';
|
||||
}
|
||||
|
||||
if (!raw.trim()) {
|
||||
console.error('check-complexity: no output from ccts-json');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const offenders = [];
|
||||
function walk(node) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (node.kind === 'function' && node.name && node.score > THRESHOLD) {
|
||||
offenders.push({ score: node.score, name: node.name });
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (key === 'inner' && Array.isArray(value)) value.forEach(walk);
|
||||
else if (value && typeof value === 'object') walk(value);
|
||||
}
|
||||
}
|
||||
walk(JSON.parse(raw));
|
||||
|
||||
if (offenders.length) {
|
||||
offenders.sort((a, b) => b.score - a.score);
|
||||
console.error(`\n✖ cognitive complexity: ${offenders.length} function(s) over ${THRESHOLD}\n`);
|
||||
for (const o of offenders) console.error(` ${String(o.score).padStart(4)} ${o.name}`);
|
||||
console.error('\nExtract helpers to bring them under the threshold (or raise COMPLEXITY_MAX).\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`✓ cognitive complexity: every function ≤ ${THRESHOLD}`);
|
||||
-387
@@ -1,387 +0,0 @@
|
||||
import http from 'http';
|
||||
import { Bus } from './bus';
|
||||
import { Container } from './container';
|
||||
import { topoSort, subgraphFor, GraphNode, nearest } from './graph';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
|
||||
import { runPipeline, PipelineStep } from './pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import { JsonTransformer } from './transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
||||
import {
|
||||
Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
|
||||
} from './metadata';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||
import { connectLink, type Link } from './mesh/link';
|
||||
import { Rooms } from './rooms';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
|
||||
import { buildRemote } from './mesh/teacup';
|
||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||
import type { MeshControl } from './http';
|
||||
import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
|
||||
|
||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
||||
export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] }
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
bus: Bus;
|
||||
}
|
||||
|
||||
interface RoutePlan {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
origin: string;
|
||||
providers: GraphNode[];
|
||||
steps: GraphNode[];
|
||||
handlerName: string;
|
||||
needs: string[];
|
||||
run: (ctx: any) => Promise<unknown>;
|
||||
transformer: typeof JsonTransformer;
|
||||
duplicates?: 'array' | 'last';
|
||||
}
|
||||
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
const streams = new Set<() => void>();
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
|
||||
|
||||
// collect declarations from modules
|
||||
const providerNodes: GraphNode[] = [];
|
||||
const stepNodes: GraphNode[] = [];
|
||||
const runners = new Map<string, (ctx: any) => any>(); // node name -> runtime fn
|
||||
const setRunner = (name: string, fn: (ctx: any) => any) => {
|
||||
if (runners.has(name)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
|
||||
runners.set(name, fn);
|
||||
};
|
||||
const providerMeta = new Map<string, { optional: boolean }>();
|
||||
const routePlans: RoutePlan[] = [];
|
||||
const exportedProviders: string[] = [];
|
||||
const exportedSteps: string[] = [];
|
||||
const exportedRoutes: RouteEntry[] = [];
|
||||
|
||||
for (const mod of opts.modules) {
|
||||
const m = getModuleMeta(mod);
|
||||
if (!m) throw new Error(`${mod.name} is not a @Module`);
|
||||
const origin = `module:${mod.name}`;
|
||||
|
||||
for (const P of m.providers ?? []) {
|
||||
const meta = getProviderMeta(P)!;
|
||||
providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
providerMeta.set(meta.provides, { optional: meta.optional });
|
||||
if (meta.export) exportedProviders.push(meta.provides);
|
||||
const inst: any = new P();
|
||||
setRunner(meta.provides, (ctx) => inst.provide(ctx));
|
||||
}
|
||||
for (const S of m.steps ?? []) {
|
||||
const meta = getStepMeta(S)!;
|
||||
stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
if (meta.export) exportedSteps.push(meta.provides);
|
||||
const inst: any = new S();
|
||||
setRunner(meta.provides, (ctx) => inst.run(ctx));
|
||||
}
|
||||
for (const C of m.controllers ?? []) {
|
||||
for (const route of getRoutes(C)) {
|
||||
const inst: any = new C();
|
||||
const argSpecs = getArgs(C, route.handlerName);
|
||||
const pattern = joinPath(m.mountpoint, route.path);
|
||||
if (route.export) {
|
||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||
exportedRoutes.push({ method: route.method, pattern });
|
||||
}
|
||||
routePlans.push({
|
||||
pattern,
|
||||
method: route.method,
|
||||
transport: route.transport,
|
||||
origin,
|
||||
providers: [],
|
||||
steps: [],
|
||||
handlerName: route.handlerName,
|
||||
needs: getHandlerNeeds(argSpecs),
|
||||
run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
|
||||
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
|
||||
duplicates: route.duplicates,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// plugin-added steps join the graph as their own scope
|
||||
for (const plugin of opts.plugins ?? []) mountPlugin(plugin, bus, scope);
|
||||
for (const n of extraSteps) {
|
||||
const node = { name: n.name, needs: n.needs, provides: n.provides, origin: 'plugin' };
|
||||
if (n.kind === 'provider') providerNodes.push(node); else stepNodes.push(node);
|
||||
setRunner(n.name, n.run);
|
||||
}
|
||||
|
||||
// built-in: auto-provide a shared Rooms instance (unless the user declares one)
|
||||
if (!runners.has('rooms')) {
|
||||
const roomsInstance = new Rooms();
|
||||
providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||
providerMeta.set('rooms', { optional: false });
|
||||
setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
|
||||
}
|
||||
|
||||
// For each route, resolve which providers/steps feed it via topo order.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
|
||||
let orderedProviders: GraphNode[] = [];
|
||||
let orderedSteps: GraphNode[] = [];
|
||||
let booted = false;
|
||||
const finalizeGraph = (): void => {
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
|
||||
orderedProviders = ordered.filter((n) => providerNodes.includes(n));
|
||||
orderedSteps = ordered.filter((n) => stepNodes.includes(n));
|
||||
const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins)
|
||||
const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route
|
||||
for (const plan of routePlans) {
|
||||
const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered);
|
||||
plan.providers = closure.filter((n) => providerNodes.includes(n));
|
||||
const sliced = new Set<GraphNode>([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]);
|
||||
plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped
|
||||
}
|
||||
|
||||
const producedKeys = new Set<string>([
|
||||
...providerNodes.flatMap((n) => n.provides),
|
||||
...stepNodes.flatMap((n) => n.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (!allowed.has(need)) {
|
||||
const hint = nearest(need, allowed);
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
booted = true;
|
||||
};
|
||||
if (!opts.mesh) finalizeGraph();
|
||||
|
||||
const inspect = (routePath: string): InspectLine[] => {
|
||||
if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
return [
|
||||
...plan.providers.map((p) => ({ name: p.name, kind: 'provider' as const, origin: p.origin })),
|
||||
...plan.steps.map((s) => ({ name: s.name, kind: 'step' as const, origin: s.origin })),
|
||||
{ name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
|
||||
];
|
||||
};
|
||||
|
||||
const graph = (): GraphView => {
|
||||
if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
|
||||
return {
|
||||
nodes: [
|
||||
...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
],
|
||||
routes: routePlans.map((p) => ({
|
||||
pattern: p.pattern, method: p.method, transport: p.transport,
|
||||
chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName],
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const explain = (routePath: string): Explain => {
|
||||
if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides });
|
||||
return {
|
||||
pattern: plan.pattern, method: plan.method, transport: plan.transport,
|
||||
chain: [
|
||||
...plan.providers.map((n) => nv(n, 'provider')),
|
||||
...plan.steps.map((n) => nv(n, 'step')),
|
||||
{ name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const providedSeed = async (plan: RoutePlan): Promise<Record<string, unknown>> => {
|
||||
const provided: Record<string, unknown> = {};
|
||||
for (const p of plan.providers) {
|
||||
if (container.has(p.name)) Object.assign(provided, (await container.resolve(p.name)) as Record<string, unknown>);
|
||||
}
|
||||
return provided;
|
||||
};
|
||||
const planSteps = (plan: RoutePlan): PipelineStep[] => plan.steps.map((s) => {
|
||||
const fn = runners.get(s.name);
|
||||
if (!fn) throw new Error(`no runner registered for step '${s.name}'`);
|
||||
return { name: s.name, origin: s.origin, run: fn };
|
||||
});
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
let meshControl: MeshControl | undefined;
|
||||
if (opts.mesh && !booted) {
|
||||
try {
|
||||
for (const t of opts.mesh.teapots ?? []) {
|
||||
const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus });
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link, t.url);
|
||||
for (const p of providers) {
|
||||
providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` });
|
||||
providerMeta.set(p.name, { optional: false });
|
||||
setRunner(p.name, p.run);
|
||||
}
|
||||
for (const s of steps) {
|
||||
stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` });
|
||||
setRunner(s.name, s.run);
|
||||
}
|
||||
for (const r of routes) {
|
||||
remoteRoutes.push({
|
||||
method: r.method, pattern: r.pattern, transport: 'buffer',
|
||||
handler: async (req) => r.handler(req as RequestEnvelope),
|
||||
});
|
||||
}
|
||||
}
|
||||
finalizeGraph();
|
||||
} catch (err) {
|
||||
for (const l of meshLinks) { try { l.close(); } catch { /* */ } }
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// apply overrides: swap any provider/step runner by token in one line
|
||||
if (opts.overrides) {
|
||||
const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides));
|
||||
for (const [token, val] of Object.entries(opts.overrides)) {
|
||||
if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
|
||||
const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val });
|
||||
runners.set(token, fn); // direct set (setRunner throws on dup); replaces the real runner
|
||||
}
|
||||
}
|
||||
|
||||
// run app-scoped providers in order (fail-fast for required)
|
||||
for (const node of orderedProviders) {
|
||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||
try {
|
||||
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
||||
container.register(node.name, 'app', () => value);
|
||||
await container.resolve(node.name); // warm the cache
|
||||
bus.emit('boot:provider:ok', { name: node.name });
|
||||
} catch (error) {
|
||||
bus.emit('boot:provider:fail', { name: node.name, error });
|
||||
if (!providerMeta.get(node.name)?.optional) {
|
||||
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// mesh teapot: expose declared exports over the control channel (lazy resolvers read live state)
|
||||
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
|
||||
if (hasExports && !opts.mesh?.secret) {
|
||||
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
|
||||
}
|
||||
if (opts.mesh?.secret && hasExports) {
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
||||
for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name));
|
||||
for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; }
|
||||
return ctx[name];
|
||||
};
|
||||
const resolveRoute = async (name: string, env: RequestEnvelope) => {
|
||||
const plan = routePlans.find((p) => p.pattern === name && p.method === env.method);
|
||||
if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; }
|
||||
const provided = await providedSeed(plan);
|
||||
const result = await runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; }
|
||||
return result;
|
||||
};
|
||||
meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus });
|
||||
}
|
||||
|
||||
const httpRoutes: RouteDef[] = [
|
||||
...routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
.map((plan): RouteDef => ({
|
||||
method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers,
|
||||
protocol: req.protocol, ip: req.ip },
|
||||
});
|
||||
},
|
||||
})),
|
||||
...remoteRoutes,
|
||||
];
|
||||
|
||||
if (opts.devGraph) {
|
||||
httpRoutes.push({
|
||||
method: 'GET', pattern: '/__graph__', transport: 'buffer',
|
||||
handler: async (req) => {
|
||||
const mermaid = toMermaid(graph());
|
||||
const accept = String(req.headers['accept'] ?? '');
|
||||
return accept.includes('text/plain')
|
||||
? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
|
||||
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const wsRoutes: WsRouteDef[] = routePlans
|
||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||
.map((plan) => ({
|
||||
pattern: plan.pattern,
|
||||
open: async ({ params, inbound, abort, req }) => {
|
||||
const provided = await providedSeed(plan);
|
||||
// ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
|
||||
let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
|
||||
headers: req.headers, inbound, abort,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
|
||||
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
|
||||
const out = await plan.run(ctx);
|
||||
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||
return out as AsyncIterable<unknown>;
|
||||
},
|
||||
}));
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates });
|
||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
return server;
|
||||
};
|
||||
|
||||
const close = (): Promise<void> => new Promise<void>((resolve) => {
|
||||
if (!server) return resolve();
|
||||
server.close(() => resolve()); // waits for in-flight buffered to drain
|
||||
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
|
||||
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||
});
|
||||
|
||||
return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus };
|
||||
}
|
||||
|
||||
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of needs) if (c.has(key)) Object.assign(out, (await c.resolve(key)) as Record<string, unknown>);
|
||||
return out;
|
||||
}
|
||||
+1381
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,86 @@
|
||||
import type { GraphNode } from '../graph';
|
||||
import type { GraphView } from '../graph-viz';
|
||||
import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types';
|
||||
|
||||
/** Lists the provider/step/handler chain for a route, in execution order. */
|
||||
export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
return [
|
||||
...plan.providers.map((provider) => ({
|
||||
name: provider.name,
|
||||
kind: 'provider' as const,
|
||||
origin: provider.origin,
|
||||
})),
|
||||
...plan.steps.map((step) => ({ name: step.name, kind: 'step' as const, origin: step.origin })),
|
||||
{ name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
|
||||
];
|
||||
}
|
||||
|
||||
/** Builds the full dependency-graph view: every provider/step node plus each route's chain. */
|
||||
export function buildGraphView(
|
||||
providerNodes: GraphNode[],
|
||||
stepNodes: GraphNode[],
|
||||
routePlans: RoutePlan[],
|
||||
booted: boolean,
|
||||
): GraphView {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
return {
|
||||
nodes: [
|
||||
...providerNodes.map((node) => ({
|
||||
name: node.name,
|
||||
kind: 'provider' as const,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
})),
|
||||
...stepNodes.map((node) => ({
|
||||
name: node.name,
|
||||
kind: 'step' as const,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
})),
|
||||
],
|
||||
routes: routePlans.map((plan) => ({
|
||||
pattern: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
chain: [...plan.providers.map((node) => node.name), ...plan.steps.map((node) => node.name), plan.handlerName],
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */
|
||||
export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({
|
||||
name: node.name,
|
||||
kind,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
});
|
||||
return {
|
||||
pattern: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
chain: [
|
||||
...plan.providers.map((node) => toExplainNode(node, 'provider')),
|
||||
...plan.steps.map((node) => toExplainNode(node, 'step')),
|
||||
{ name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
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';
|
||||
import type { ArgSpec } from '../params';
|
||||
import type { OpenApiDoc, OpenApiInfo } from '../openapi';
|
||||
import type { WsRequest, WsSocket } from '../http/ws-core';
|
||||
import { JsonTransformer } from '../transformers';
|
||||
|
||||
/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
|
||||
export interface InspectLine {
|
||||
name: string;
|
||||
kind: 'provider' | 'step' | 'handler';
|
||||
origin: string;
|
||||
}
|
||||
|
||||
/** A node in an {@link Explain} chain, annotated with the keys it needs and provides. */
|
||||
export interface ExplainNode {
|
||||
name: string;
|
||||
kind: 'provider' | 'step' | 'handler';
|
||||
origin: string;
|
||||
needs: string[];
|
||||
provides: string[];
|
||||
}
|
||||
|
||||
/** A full route explanation: its match criteria and the ordered provider/step/handler chain. */
|
||||
export interface Explain {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
chain: ExplainNode[];
|
||||
}
|
||||
|
||||
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/**
|
||||
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
|
||||
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
|
||||
* other app it is a no-op, so code holding an `App` can `await app.ready()` before
|
||||
* `inspect()`/`graph()`/`explain()` without caring which kind it was handed.
|
||||
*
|
||||
* Deliberately *not* a full boot: it does not run provider factories. Resolving the graph and
|
||||
* being ready to serve are different things, and drawing a diagram should not open your
|
||||
* database connections. Serving (`fetch`/`upgrade`/`listen`) boots the providers as well, and
|
||||
* shares this same memoized step — calling both never resolves the graph twice.
|
||||
*/
|
||||
ready(): 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. */
|
||||
upgrade(request: WsRequest, socket: WsSocket): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
/** Generate a structural OpenAPI 3.1 document from the registered routes. */
|
||||
openapi(info?: OpenApiInfo): OpenApiDoc;
|
||||
/** 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. */
|
||||
export interface RoutePlan {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
origin: string;
|
||||
declaration: string;
|
||||
providers: GraphNode[];
|
||||
steps: GraphNode[];
|
||||
handlerName: string;
|
||||
needs: string[];
|
||||
run: (ctx: any) => Promise<unknown>;
|
||||
transformer: typeof JsonTransformer;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
/** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Gap between heartbeat pings to each teapot (default: 15s). Two unanswered rounds close the
|
||||
* link, so a half-open connection surfaces as an immediate 503 instead of every request paying
|
||||
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
||||
*/
|
||||
heartbeatMs?: number;
|
||||
/**
|
||||
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
|
||||
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
|
||||
*
|
||||
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
|
||||
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
|
||||
* together do not come back in lockstep.
|
||||
*/
|
||||
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
|
||||
/**
|
||||
* What to do when a returning teapot's manifest no longer exports something the graph was
|
||||
* validated against at boot (default: `'refuse'`).
|
||||
*
|
||||
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
|
||||
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
|
||||
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
|
||||
* rather than left implicit so that arriving is additive rather than a change of default.
|
||||
*/
|
||||
onManifestChange?: 'refuse';
|
||||
/**
|
||||
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
|
||||
* so 30s). Attempts use the same backoff as reconnection.
|
||||
*
|
||||
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
|
||||
* has not settled — should not fail a deploy, and this is the grace for that. A teapot that is
|
||||
* genuinely absent still fails the boot when the deadline passes, because a provider the graph
|
||||
* depends on is not optional: booting without it would only move the failure to the first
|
||||
* request, where it is somebody else's 503 instead of your deploy's error.
|
||||
*
|
||||
* `0` restores the old behaviour of a single attempt.
|
||||
*/
|
||||
bootTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lifecycle participation for an application that does not want to be a plugin.
|
||||
*
|
||||
* Every method is optional, and the shape is an object rather than a single callback so later
|
||||
* stages (`onBoot`, `onReady`) can be added without a breaking change. Only `onShutdown` exists.
|
||||
*/
|
||||
export interface Hooks {
|
||||
/** Run before the app closes. Awaited, bounded by `close()`'s deadline, failures logged. */
|
||||
onShutdown?: TeardownFn;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import { channel } from './channel';
|
||||
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.
|
||||
interface BunServerWebSocket {
|
||||
data: unknown;
|
||||
readyState: number;
|
||||
send(data: string): number;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate?(): void;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||
}
|
||||
interface BunServer {
|
||||
port: number;
|
||||
// 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;
|
||||
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
|
||||
websocket?: BunWebSocketHandler;
|
||||
}
|
||||
type BunServeShortOptions = { port?: number; hostname?: string };
|
||||
declare const Bun: { serve(options: BunServeOptions): BunServer };
|
||||
|
||||
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
|
||||
interface BunConnData {
|
||||
wsReq: WsRequest;
|
||||
inbound: Channel<unknown>;
|
||||
ac: AbortController;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket
|
||||
* events to a server-level handler rather than the socket, so the channel and abort are
|
||||
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
||||
*/
|
||||
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
|
||||
return neutralSocket(ws, inbound, ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
|
||||
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
|
||||
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
||||
* Bun.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||
* the deployment platform or reverse proxy.
|
||||
*/
|
||||
export function serveBun(app: App, options?: BunServeShortOptions): BunServeResult {
|
||||
const server = Bun.serve({
|
||||
...options,
|
||||
fetch(request, server) {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
const inbound = channel();
|
||||
const ac = new AbortController();
|
||||
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
||||
const data: BunConnData = { wsReq, inbound, ac };
|
||||
if (server.upgrade(request, { data })) return undefined;
|
||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
},
|
||||
websocket: {
|
||||
open(ws) {
|
||||
const { wsReq } = ws.data as BunConnData;
|
||||
|
||||
void upgradeSafely(app, wsReq, bunSocket(ws));
|
||||
},
|
||||
message(ws, message) {
|
||||
const { inbound } = ws.data as BunConnData;
|
||||
|
||||
inbound.push(decodeMessage(message));
|
||||
},
|
||||
close(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
},
|
||||
error(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
|
||||
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
|
||||
return Object.assign(server, {
|
||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.stop(false).then(() => app.close()),
|
||||
() => void server.stop(true),
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(`graceful shutdown timed out after ${ms}ms — forcing remaining connections closed`, {
|
||||
timeoutMs: ms,
|
||||
runtime: 'bun',
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
+81
-13
@@ -1,30 +1,98 @@
|
||||
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
|
||||
export type LifecycleEvent =
|
||||
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
|
||||
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
|
||||
| 'stream:open' | 'stream:close' | 'stream:error'
|
||||
| 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error'
|
||||
| 'plugin:mounted';
|
||||
| 'boot:provider:start'
|
||||
| 'boot:provider:ok'
|
||||
| 'boot:provider:fail'
|
||||
| 'request:step:enter'
|
||||
| 'request:step:leave'
|
||||
| 'request:step:error'
|
||||
| 'stream:open'
|
||||
| 'stream:close'
|
||||
| 'stream:error'
|
||||
| 'mesh:connect'
|
||||
| 'mesh:disconnect'
|
||||
| 'mesh:rpc:error'
|
||||
// A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
|
||||
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
|
||||
// came up, and a deploy watching for trouble wants to tell those apart.
|
||||
| 'mesh:boot:retry'
|
||||
| 'plugin:mounted'
|
||||
| 'request:start'
|
||||
| 'request:end'
|
||||
| 'request:failed'
|
||||
| 'route:matched'
|
||||
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
|
||||
// misreport the other, and "no route ran" is the fact a consumer actually wants.
|
||||
| 'route:unmatched';
|
||||
|
||||
/**
|
||||
* Data carried by a lifecycle event: the subject's name plus optional scope, error, timing and
|
||||
* the fields that say which request it belongs to.
|
||||
*
|
||||
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
|
||||
* name, and requiring a shape they cannot fill would only mean inventing values for it.
|
||||
*/
|
||||
export interface EventPayload {
|
||||
name: string;
|
||||
scope?: string;
|
||||
error?: unknown;
|
||||
durationMs?: number;
|
||||
/** Correlates every event of one request. Adopted from `x-request-id` when a gateway sent one. */
|
||||
requestId?: string;
|
||||
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
|
||||
traceId?: string;
|
||||
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */
|
||||
route?: string;
|
||||
method?: string;
|
||||
transport?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of {@link EventPayload} that identifies a request, spread into each of its events.
|
||||
*
|
||||
* `route` carries the matched pattern rather than the URL that arrived, and that is load-bearing
|
||||
* rather than cosmetic: a metrics consumer that labels a counter with a concrete path gets one
|
||||
* label per distinct URL, and unbounded label cardinality takes down the metrics backend rather
|
||||
* than the application. Handing anyone that shape by default would be the framework's fault.
|
||||
*/
|
||||
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
|
||||
|
||||
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||
export class Bus {
|
||||
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
||||
|
||||
on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void {
|
||||
const set = this.listeners.get(event) ?? new Set();
|
||||
set.add(fn);
|
||||
this.listeners.set(event, set);
|
||||
return () => set.delete(fn);
|
||||
/** Subscribe `listener` to `event`; returns an unsubscribe function. */
|
||||
on(event: LifecycleEvent, listener: (p: EventPayload) => void): () => void {
|
||||
const listenerSet = this.listeners.get(event) ?? new Set();
|
||||
listenerSet.add(listener);
|
||||
this.listeners.set(event, listenerSet);
|
||||
return () => listenerSet.delete(listener);
|
||||
}
|
||||
|
||||
emit(event: LifecycleEvent, p: EventPayload): void {
|
||||
for (const fn of this.listeners.get(event) ?? []) {
|
||||
try { fn(p); } catch { /* observers must never break the pipeline */ }
|
||||
/**
|
||||
* 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) ?? []) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
/* observers must never break the pipeline */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-19
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* A push-driven async stream: producers call `push`/`close`/`fail`, consumers use `for await`.
|
||||
* Each `for await` gets its own independent subscription (fan-out).
|
||||
*/
|
||||
export interface Channel<T> extends AsyncIterable<T> {
|
||||
push(value: T): void;
|
||||
close(): void;
|
||||
@@ -5,15 +9,16 @@ export interface Channel<T> extends AsyncIterable<T> {
|
||||
readonly closed: boolean;
|
||||
}
|
||||
|
||||
/** Type guard: true when `x` implements the async-iterable protocol. */
|
||||
export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
|
||||
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
|
||||
}
|
||||
|
||||
interface Sub<T> {
|
||||
iterator: AsyncIterator<T>;
|
||||
push(v: T, cap: number): void;
|
||||
push(value: T, cap: number): void;
|
||||
end(): void;
|
||||
fail(e: unknown): void;
|
||||
fail(err: unknown): void;
|
||||
}
|
||||
|
||||
function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
@@ -23,29 +28,48 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
let failure: { err: unknown } | null = null;
|
||||
|
||||
return {
|
||||
push(v, cap) {
|
||||
push(value, cap) {
|
||||
if (ended) return;
|
||||
if (pending) { const p = pending; pending = null; p.resolve({ value: v, done: false }); return; }
|
||||
queue.push(v);
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.resolve({ value, done: false });
|
||||
return;
|
||||
}
|
||||
|
||||
queue.push(value);
|
||||
if (queue.length > cap) queue.shift(); // drop-oldest when buffer is full
|
||||
},
|
||||
end() {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
if (pending) { const p = pending; pending = null; p.resolve({ value: undefined as never, done: true }); }
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.resolve({ value: undefined as never, done: true });
|
||||
}
|
||||
},
|
||||
fail(e) {
|
||||
fail(err) {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
failure = { err: e };
|
||||
if (pending) { const p = pending; pending = null; p.reject(e); }
|
||||
failure = { err };
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.reject(err);
|
||||
}
|
||||
},
|
||||
iterator: {
|
||||
next(): Promise<IteratorResult<T>> {
|
||||
if (queue.length) return Promise.resolve({ value: queue.shift() as T, done: false });
|
||||
if (failure) return Promise.reject(failure.err);
|
||||
if (ended) return Promise.resolve({ value: undefined as never, done: true });
|
||||
return new Promise<IteratorResult<T>>((resolve, reject) => { pending = { resolve, reject }; });
|
||||
return new Promise<IteratorResult<T>>((resolve, reject) => {
|
||||
pending = { resolve, reject };
|
||||
});
|
||||
},
|
||||
return(): Promise<IteratorResult<T>> {
|
||||
ended = true;
|
||||
@@ -56,6 +80,10 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
|
||||
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
|
||||
*/
|
||||
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
const cap = opts.buffer ?? Infinity;
|
||||
const subs = new Set<Sub<T>>();
|
||||
@@ -63,27 +91,31 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
let closedFlag = false;
|
||||
|
||||
return {
|
||||
get closed() { return closedFlag; },
|
||||
get closed() {
|
||||
return closedFlag;
|
||||
},
|
||||
push(value) {
|
||||
if (done) return;
|
||||
for (const s of subs) s.push(value, cap);
|
||||
for (const sub of subs) sub.push(value, cap);
|
||||
},
|
||||
close() {
|
||||
if (done) return;
|
||||
done = true; closedFlag = true;
|
||||
for (const s of subs) s.end();
|
||||
done = true;
|
||||
closedFlag = true;
|
||||
for (const sub of subs) sub.end();
|
||||
subs.clear();
|
||||
},
|
||||
fail(err) {
|
||||
if (done) return;
|
||||
done = true; closedFlag = true;
|
||||
for (const s of subs) s.fail(err);
|
||||
done = true;
|
||||
closedFlag = true;
|
||||
for (const sub of subs) sub.fail(err);
|
||||
subs.clear();
|
||||
},
|
||||
[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
const s = newSub<T>(() => subs.delete(s));
|
||||
subs.add(s);
|
||||
return s.iterator;
|
||||
const sub = newSub<T>(() => subs.delete(sub));
|
||||
subs.add(sub);
|
||||
return sub.iterator;
|
||||
},
|
||||
};
|
||||
}
|
||||
+22
-6
@@ -1,27 +1,43 @@
|
||||
/** Lifetime of a binding: `app` values are memoized for the process, `request` values are recomputed per resolve. */
|
||||
export type Scope = 'app' | 'request';
|
||||
/** Produces a bound value from the current context; may be async. */
|
||||
export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknown>;
|
||||
|
||||
interface Binding { scope: Scope; factory: Factory; cached?: unknown; resolved?: boolean }
|
||||
interface Binding {
|
||||
scope: Scope;
|
||||
factory: Factory;
|
||||
cached?: unknown;
|
||||
resolved?: boolean;
|
||||
}
|
||||
|
||||
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
|
||||
export class Container {
|
||||
private readonly bindings = new Map<string, Binding>();
|
||||
|
||||
/** Bind `token` to `factory` under `scope`, replacing any existing binding. */
|
||||
register(token: string, scope: Scope, factory: Factory): void {
|
||||
this.bindings.set(token, { scope, factory });
|
||||
}
|
||||
|
||||
/** Whether `token` currently has a binding. */
|
||||
has(token: string): boolean {
|
||||
return this.bindings.has(token);
|
||||
}
|
||||
|
||||
/** Resolve `token`'s value; app-scoped results are cached, request-scoped ones re-run the factory. Throws on unknown tokens. */
|
||||
// ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
|
||||
// so a future remote transport (mesh) slots in without changing callers.
|
||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||
const b = this.bindings.get(token);
|
||||
if (!b) throw new Error(`unknown token: ${token}`);
|
||||
if (b.scope === 'app' && b.resolved) return b.cached;
|
||||
const value = await b.factory(ctx);
|
||||
if (b.scope === 'app') { b.cached = value; b.resolved = true; }
|
||||
const binding = this.bindings.get(token);
|
||||
if (!binding) throw new Error(`unknown token: ${token}`);
|
||||
if (binding.scope === 'app' && binding.resolved) return binding.cached;
|
||||
const value = await binding.factory(ctx);
|
||||
|
||||
if (binding.scope === 'app') {
|
||||
binding.cached = value;
|
||||
binding.resolved = true;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
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.
|
||||
interface WebSocket extends EventfulSocket {
|
||||
binaryType: string;
|
||||
}
|
||||
|
||||
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
|
||||
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
|
||||
interface DenoServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
signal?: AbortSignal;
|
||||
onListen?: (addr: { hostname: string; port: number }) => void;
|
||||
}
|
||||
interface DenoServeHandlerInfo {
|
||||
remoteAddr: { hostname: string; port: number; transport: string };
|
||||
}
|
||||
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;
|
||||
upgradeWebSocket(request: Request): { socket: WebSocket; response: Response };
|
||||
};
|
||||
|
||||
/**
|
||||
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
|
||||
* WebSocket messages flow through app.upgrade over the shared neutral core.
|
||||
* Deno.serve exposes no equivalent to Node's server.maxConnections; enforce connection caps at
|
||||
* the deployment platform or reverse proxy.
|
||||
*/
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
|
||||
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to
|
||||
// own one to offer a deadline at all. A caller-supplied signal still works and still aborts the
|
||||
// server — it is chained into ours rather than replaced, so neither party loses its control.
|
||||
const ac = new AbortController();
|
||||
options?.signal?.addEventListener('abort', () => ac.abort(), { once: true });
|
||||
|
||||
const server = Deno.serve({ ...options, signal: ac.signal }, (request, info) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
|
||||
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
|
||||
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
|
||||
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
|
||||
void upgradeSafely(app, wsRequest, eventSocket(socket));
|
||||
return response;
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
});
|
||||
|
||||
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
|
||||
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
|
||||
return Object.assign(server, {
|
||||
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
|
||||
closeWithDeadline(
|
||||
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
|
||||
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown
|
||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||
// and the deadline below already bounds the whole call.
|
||||
() => server.shutdown().then(() => app.close()),
|
||||
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
|
||||
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
|
||||
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
||||
// surfaces uncaught — not catchable at this call site, and fatal under `deno test`.
|
||||
// Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So Deno cannot
|
||||
// escalate from graceful to forced the way Node's closeAllConnections() and Bun's
|
||||
// stop(true) can, and the deadline here bounds how long `close()` waits, not when the
|
||||
// connections die. Exiting the process after `close()` resolves is what ends them.
|
||||
() => {},
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
app.logger.warn(
|
||||
`graceful shutdown timed out after ${ms}ms — returning anyway. Deno cannot force-close ` +
|
||||
'a server that is already draining, so remaining connections end when the process does.',
|
||||
{ timeoutMs: ms, runtime: 'deno' },
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
|
||||
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||
// Declares only what we call; mirrors the real workerd signatures.
|
||||
interface EdgeWebSocket extends EventfulSocket {
|
||||
accept(): void;
|
||||
}
|
||||
interface EdgeCtx {
|
||||
waitUntil(promise: Promise<unknown>): void;
|
||||
}
|
||||
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,
|
||||
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
|
||||
return (request, _env, ctx) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||
server.accept();
|
||||
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
|
||||
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||
else void lifecycle;
|
||||
|
||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
};
|
||||
}
|
||||
+9
-3
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* Serializes stream items into wire frames for a streaming transport (SSE, NDJSON).
|
||||
* `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive.
|
||||
*/
|
||||
export interface StreamEncoder {
|
||||
headers: Record<string, string>;
|
||||
encode(item: unknown): string | Buffer;
|
||||
@@ -5,17 +9,19 @@ export interface StreamEncoder {
|
||||
ping?(): string;
|
||||
}
|
||||
|
||||
const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
||||
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
||||
|
||||
/** 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`,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
||||
ping: () => ': ping\n\n',
|
||||
};
|
||||
|
||||
/** 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`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
||||
};
|
||||
+11
-3
@@ -1,18 +1,23 @@
|
||||
/** A single flow step: receives the accumulated context and returns the fields it contributes. */
|
||||
export type StepFn<In, Out> = (ctx: In) => Out | Promise<Out>;
|
||||
|
||||
/** A built flow ready to execute: its ordered steps, terminal handler, and a `run` entry point. */
|
||||
export interface CompiledFlow<Seed, Acc> {
|
||||
steps: { name: string; fn: StepFn<any, any> }[];
|
||||
handler: (ctx: Acc) => unknown;
|
||||
run(seed: Seed): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** Immutable builder that chains typed steps, each widening the accumulated context type. */
|
||||
export class Flow<Seed, Acc> {
|
||||
constructor(private readonly steps: { name: string; fn: StepFn<any, any> }[] = []) {}
|
||||
|
||||
/** Appends a step and returns a new Flow whose context now includes the step's output. */
|
||||
step<Out>(name: string, fn: StepFn<Acc, Out>): Flow<Seed, Acc & Out> {
|
||||
return new Flow<Seed, Acc & Out>([...this.steps, { name, fn }]);
|
||||
}
|
||||
|
||||
/** Seals the flow with a terminal handler, producing a runnable CompiledFlow. */
|
||||
handle(handler: (ctx: Acc) => unknown): CompiledFlow<Seed, Acc> {
|
||||
const steps = this.steps;
|
||||
return {
|
||||
@@ -20,16 +25,19 @@ export class Flow<Seed, Acc> {
|
||||
handler,
|
||||
async run(seed: Seed): Promise<unknown> {
|
||||
let ctx: any = { ...seed };
|
||||
for (const s of steps) {
|
||||
const out = await s.fn(ctx);
|
||||
ctx = { ...ctx, ...out };
|
||||
|
||||
for (const step of steps) {
|
||||
const output = await step.fn(ctx);
|
||||
ctx = { ...ctx, ...output };
|
||||
}
|
||||
|
||||
return handler(ctx);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts a new flow whose seed and initial context are the same type. */
|
||||
export function flow<Seed extends object>(): Flow<Seed, Seed> {
|
||||
return new Flow<Seed, Seed>();
|
||||
}
|
||||
+219
-26
@@ -1,45 +1,238 @@
|
||||
export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] }
|
||||
export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] }
|
||||
/** Renderable view of a graph node (provider or step). */
|
||||
export interface GraphNodeView {
|
||||
name: string;
|
||||
kind: 'provider' | 'step';
|
||||
origin: string;
|
||||
needs: string[];
|
||||
provides: string[];
|
||||
}
|
||||
/** Renderable view of a route and the chain of nodes feeding its handler. */
|
||||
export interface GraphRouteView {
|
||||
pattern: string;
|
||||
method: string;
|
||||
transport: string;
|
||||
chain: string[];
|
||||
}
|
||||
/** Full graph payload consumed by the diagram renderers. */
|
||||
export interface GraphView {
|
||||
nodes: GraphNodeView[];
|
||||
routes: GraphRouteView[];
|
||||
}
|
||||
|
||||
const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
/** Sanitizes a node name into a Mermaid/DOT-safe node id. */
|
||||
const nid = (name: string) => 'n_' + name.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
/** Sanitizes a route pattern into a Mermaid/DOT-safe node id. */
|
||||
const rid = (pattern: string) => 'r_' + pattern.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
|
||||
/** Renders the graph view as Mermaid `flowchart` source. */
|
||||
export function toMermaid(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const known = new Set(view.nodes.map((node) => node.name));
|
||||
const out: string[] = ['flowchart LR'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(n.kind === 'provider' ? ` ${nid(n.name)}(["${n.name}"])` : ` ${nid(n.name)}["${n.name}"]`);
|
||||
|
||||
for (const node of view.nodes) {
|
||||
out.push(
|
||||
node.kind === 'provider' ? ` ${nid(node.name)}(["${node.name}"])` : ` ${nid(node.name)}["${node.name}"]`,
|
||||
);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(n.name)}`);
|
||||
for (const r of view.routes) {
|
||||
out.push(` ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` ${nid(c)} --> ${rid(r.pattern)}`);
|
||||
|
||||
for (const node of view.nodes)
|
||||
for (const need of node.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(node.name)}`);
|
||||
|
||||
for (const route of view.routes) {
|
||||
out.push(` ${rid(route.pattern)}{{"${route.method} ${route.pattern}"}}`);
|
||||
for (const link of route.chain) if (known.has(link)) out.push(` ${nid(link)} --> ${rid(route.pattern)}`);
|
||||
}
|
||||
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
/** Renders the graph view as Graphviz DOT source. */
|
||||
export function toDOT(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const known = new Set(view.nodes.map((node) => node.name));
|
||||
const out: string[] = ['digraph green_tea {', ' rankdir=LR;'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(` "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||
|
||||
for (const node of view.nodes) {
|
||||
out.push(` "${node.name}" [shape=${node.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` "${need}" -> "${n.name}";`);
|
||||
for (const r of view.routes) {
|
||||
const label = `${r.method} ${r.pattern}`;
|
||||
|
||||
for (const node of view.nodes)
|
||||
for (const need of node.needs) if (known.has(need)) out.push(` "${need}" -> "${node.name}";`);
|
||||
|
||||
for (const route of view.routes) {
|
||||
const label = `${route.method} ${route.pattern}`;
|
||||
out.push(` "${label}" [shape=hexagon];`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` "${c}" -> "${label}";`);
|
||||
for (const link of route.chain) if (known.has(link)) out.push(` "${link}" -> "${label}";`);
|
||||
}
|
||||
|
||||
out.push('}');
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
export function graphHtml(mermaid: string): string {
|
||||
return [
|
||||
'<!doctype html><html><head><meta charset="utf-8"><title>green-tea graph</title>',
|
||||
'<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script></head>',
|
||||
'<body><pre class="mermaid">', mermaid, '</pre>',
|
||||
'<script>mermaid.initialize({ startOnLoad: true });</script></body></html>',
|
||||
].join('\n');
|
||||
/**
|
||||
* Renders the graph as a self-contained, interactive HTML page (Cytoscape.js +
|
||||
* dagre, both from a CDN — no runtime dependency is added). Clicking a route
|
||||
* lights up its exact transitive slice and dims everything else; clicking a
|
||||
* provider/step shows its blast radius (every route that depends on it).
|
||||
*
|
||||
* The whole {@link GraphView} is embedded as JSON, so all interaction is
|
||||
* client-side — the page needs nothing from the server after it loads.
|
||||
*/
|
||||
/** The Green Tea. mark (leaf whose venation is a dependency graph), inlined for the dev graph header. */
|
||||
const BRAND_LOGO =
|
||||
'<svg viewBox="0 0 611 620" fill="none" aria-hidden="true"> <path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/> <g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none"> <path d="M277 312 Q255 263 221 247"/> <path d="M338 276 Q382 305 393 340"/> <path d="M366 258 Q348 214 317 200"/> <path d="M443 186 Q469 204 475 224"/> </g> <g fill="#5FB88A"> <circle cx="221" cy="247" r="13"/> <circle cx="393" cy="340" r="13"/> <circle cx="475" cy="224" r="11"/> </g> <circle cx="317" cy="200" r="18" fill="#7C6CF0"/> </svg>';
|
||||
|
||||
export function graphHtml(view: GraphView): string {
|
||||
const data = JSON.stringify(view).replace(/</g, '\\u003c');
|
||||
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>green-tea graph</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape@3.30.2/dist/cytoscape.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/dagre@0.8.5/dist/dagre.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape-dagre@2.5.0/cytoscape-dagre.min.js"></script>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Zen+Maru+Gothic:wght@700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root { --bg:#fff; --ink:#1c2128; --dim:#57606a; --line:#d0d7de; --tea:#7c6cf0; --panel:#f6f8fa;
|
||||
--matcha:#3fa873; --prov:#1f9e8a; --step:#7c6cf0; --need:#2f81f7; --feed:#bf8700; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --ink:#e6edf3; --dim:#8b949e; --line:#30363d; --tea:#a78bfa; --panel:#161b22;
|
||||
--matcha:#5fb88a; --prov:#3fd0b8; --step:#a78bfa; --need:#58a6ff; --feed:#e3b341; } }
|
||||
* { box-sizing:border-box; } html,body { margin:0; height:100%; background:var(--bg); color:var(--ink);
|
||||
font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||
#cy { position:absolute; inset:0; }
|
||||
#bar { position:absolute; top:0; left:0; right:0; padding:10px 14px; z-index:2; pointer-events:none;
|
||||
background:linear-gradient(var(--bg),transparent); }
|
||||
#bar b { color:var(--tea); } #bar span { color:var(--dim); }
|
||||
#bar .brand { display:flex; align-items:center; gap:9px; margin-bottom:5px; }
|
||||
#bar .brand svg { height:27px; width:auto; }
|
||||
#bar .brand .wm { font-family:'Zen Maru Gothic',sans-serif; font-weight:700; font-size:18px; color:var(--matcha); }
|
||||
#bar .brand .wm .dot { color:var(--step); }
|
||||
#legend { margin-top:6px; color:var(--dim); font-size:12px; display:flex; gap:14px; flex-wrap:wrap; }
|
||||
#legend i { display:inline-block; vertical-align:middle; margin-right:5px; }
|
||||
#legend .sw { width:11px; height:11px; border-radius:3px; border:1.5px solid; }
|
||||
#legend .prov { background:var(--panel); border-color:var(--prov); }
|
||||
#legend .step { background:var(--panel); border-color:var(--step); border-radius:0; }
|
||||
#legend .route { background:var(--tea); border-color:var(--tea); }
|
||||
#legend .ln { width:16px; height:0; border-top:3px solid; border-radius:0; }
|
||||
#legend .need { border-color:var(--need); } #legend .feed { border-color:var(--feed); }
|
||||
#legend .tp { background:transparent; border-color:var(--dim); }
|
||||
#legend .tp-http { border-style:solid; } #legend .tp-sse { border-style:dashed; }
|
||||
#legend .tp-ws { border-style:double; border-width:3px; }
|
||||
#info { position:absolute; left:14px; bottom:14px; z-index:2; max-width:340px; padding:10px 12px;
|
||||
background:var(--panel); border:1px solid var(--line); border-radius:8px; white-space:pre-wrap; display:none; }
|
||||
#info .t { color:var(--tea); font-weight:700; } #info .k { color:var(--dim); }
|
||||
</style></head><body>
|
||||
<div id="bar"><div class="brand">${BRAND_LOGO}<span class="wm">Green Tea<span class="dot">.</span></span></div><span>click a <b>route</b> for its slice · click a <b>provider/step</b> for its blast radius · drag to rearrange · click canvas to reset</span>
|
||||
<div id="legend"><span><i class="sw prov"></i>provider</span><span><i class="sw step"></i>step</span><span><i class="ln need"></i>needs</span><span><i class="ln feed"></i>feeds endpoint</span><span><i class="sw tp tp-http"></i>HTTP</span><span><i class="sw tp tp-sse"></i>SSE</span><span><i class="sw tp tp-ws"></i>WS</span></div></div>
|
||||
<div id="cy"></div>
|
||||
<div id="info"></div>
|
||||
<script>
|
||||
var DATA = ${data};
|
||||
try { if (window.cytoscapeDagre) cytoscape.use(window.cytoscapeDagre); } catch (e) {}
|
||||
var css = getComputedStyle(document.documentElement);
|
||||
var C = function (n) { return css.getPropertyValue(n).trim(); };
|
||||
var nodeNames = new Set(DATA.nodes.map(function (n) { return n.name; }));
|
||||
var nid = function (s) { return 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
|
||||
var rid = function (s) { return 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
|
||||
|
||||
// HTTP method -> colour, so the endpoint type is visual, not just text.
|
||||
var METHOD_COLORS = { GET: '#3fb950', POST: '#a371f7', PUT: '#d29922', PATCH: '#db61a2', DELETE: '#f85149', HEAD: '#8b949e', OPTIONS: '#8b949e' };
|
||||
var methodColor = function (m) { return METHOD_COLORS[m] || '#8b949e'; };
|
||||
|
||||
var els = [];
|
||||
DATA.nodes.forEach(function (n) {
|
||||
els.push({ data: { id: nid(n.name), label: n.name, kind: n.kind, origin: n.origin,
|
||||
needs: (n.needs || []).join(', '), provides: (n.provides || []).join(', ') } });
|
||||
});
|
||||
DATA.routes.forEach(function (r) {
|
||||
var suffix = r.transport && r.transport !== 'buffer' ? ' · ' + r.transport : '';
|
||||
els.push({ data: { id: rid(r.pattern), label: r.method + ' ' + r.pattern + suffix, kind: 'route',
|
||||
method: r.method, transport: r.transport, color: methodColor(r.method) } });
|
||||
});
|
||||
DATA.nodes.forEach(function (n) {
|
||||
(n.needs || []).forEach(function (need) {
|
||||
if (nodeNames.has(need)) els.push({ data: { id: 'e' + nid(need) + nid(n.name), source: nid(need), target: nid(n.name), rel: 'need' } });
|
||||
});
|
||||
});
|
||||
DATA.routes.forEach(function (r) {
|
||||
(r.chain || []).forEach(function (name) {
|
||||
if (nodeNames.has(name)) els.push({ data: { id: 'e' + nid(name) + rid(r.pattern), source: nid(name), target: rid(r.pattern), rel: 'feed' } });
|
||||
});
|
||||
});
|
||||
|
||||
// Precomputed highlight sets (uses green-tea's real per-route slice).
|
||||
var routeChain = {}; DATA.routes.forEach(function (r) {
|
||||
routeChain[rid(r.pattern)] = (r.chain || []).filter(function (x) { return nodeNames.has(x); }).map(nid);
|
||||
});
|
||||
var nodeRoutes = {}; DATA.nodes.forEach(function (n) {
|
||||
nodeRoutes[nid(n.name)] = DATA.routes.filter(function (r) { return (r.chain || []).indexOf(n.name) >= 0; })
|
||||
.map(function (r) { return rid(r.pattern); });
|
||||
});
|
||||
|
||||
// Method colour chips in the legend — only for methods actually present.
|
||||
var legend = document.getElementById('legend'), seenMethod = {};
|
||||
DATA.routes.forEach(function (r) {
|
||||
if (seenMethod[r.method]) return; seenMethod[r.method] = 1;
|
||||
var s = document.createElement('span');
|
||||
s.innerHTML = '<i class="sw" style="background:' + methodColor(r.method) + ';border-color:' + methodColor(r.method) + '"></i>' + r.method;
|
||||
legend.appendChild(s);
|
||||
});
|
||||
|
||||
var cy = cytoscape({
|
||||
container: document.getElementById('cy'),
|
||||
elements: els,
|
||||
style: [
|
||||
{ selector: 'node', style: { 'label': 'data(label)', 'color': C('--ink'), 'font-family': 'ui-monospace,Menlo,monospace',
|
||||
'font-size': 12, 'text-valign': 'center', 'text-halign': 'center', 'width': 'label', 'height': 'label',
|
||||
'padding': '10px', 'background-color': C('--panel'), 'border-width': 1.5, 'border-color': C('--tea'), 'shape': 'round-rectangle' } },
|
||||
{ selector: 'node[kind = "provider"]', style: { 'shape': 'round-rectangle', 'background-color': C('--panel'), 'border-color': C('--prov') } },
|
||||
{ selector: 'node[kind = "step"]', style: { 'shape': 'rectangle', 'border-color': C('--step') } },
|
||||
{ selector: 'node[kind = "route"]', style: { 'shape': 'round-rectangle', 'background-color': 'data(color)', 'color': '#fff', 'border-width': 1.5, 'border-color': '#fff', 'border-style': 'solid', 'font-weight': 'bold' } },
|
||||
{ selector: 'node[transport = "sse"]', style: { 'border-style': 'dashed', 'border-width': 2.5 } },
|
||||
{ selector: 'node[transport = "negotiate"]', style: { 'border-style': 'dotted', 'border-width': 2.5 } },
|
||||
{ selector: 'node[transport = "ws"]', style: { 'border-style': 'double', 'border-width': 4 } },
|
||||
{ selector: 'edge', style: { 'width': 1, 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'arrow-scale': 0.75 } },
|
||||
{ selector: 'edge[rel = "need"]', style: { 'line-color': C('--need'), 'target-arrow-color': C('--need') } },
|
||||
{ selector: 'edge[rel = "feed"]', style: { 'line-color': C('--feed'), 'target-arrow-color': C('--feed') } },
|
||||
{ selector: '.dim', style: { 'opacity': 0.1 } },
|
||||
{ selector: 'node.hot', style: { 'border-width': 3 } },
|
||||
{ selector: 'edge.hot', style: { 'width': 1.9, 'opacity': 1 } }
|
||||
]
|
||||
});
|
||||
|
||||
var layout = { name: 'dagre', rankDir: 'LR', nodeSep: 36, rankSep: 90, edgeSep: 12 };
|
||||
try { cy.layout(layout).run(); } catch (e) { cy.layout({ name: 'breadthfirst', directed: true }).run(); }
|
||||
|
||||
function highlight(idSet) {
|
||||
cy.batch(function () {
|
||||
cy.elements().removeClass('hot').addClass('dim');
|
||||
idSet.forEach(function (id) { cy.getElementById(id).removeClass('dim').addClass('hot'); });
|
||||
cy.edges().forEach(function (e) {
|
||||
if (idSet.has(e.source().id()) && idSet.has(e.target().id())) e.removeClass('dim').addClass('hot');
|
||||
});
|
||||
});
|
||||
}
|
||||
function reset() { cy.batch(function () { cy.elements().removeClass('dim hot'); }); }
|
||||
|
||||
var info = document.getElementById('info');
|
||||
function showInfo(el) {
|
||||
var k = el.data('kind');
|
||||
var body = k === 'route'
|
||||
? '<span class="k">' + el.data('transport') + ' route</span>'
|
||||
: '<span class="k">kind</span> ' + k + '\\n<span class="k">needs</span> ' + (el.data('needs') || '—')
|
||||
+ '\\n<span class="k">provides</span> ' + (el.data('provides') || '—')
|
||||
+ '\\n<span class="k">origin</span> ' + (el.data('origin') || '—');
|
||||
info.style.display = 'block';
|
||||
info.innerHTML = '<span class="t">' + el.data('label') + '</span>\\n' + body;
|
||||
}
|
||||
|
||||
cy.on('tap', 'node', function (evt) {
|
||||
var el = evt.target, id = el.id();
|
||||
var ids = el.data('kind') === 'route'
|
||||
? new Set([id].concat(routeChain[id] || []))
|
||||
: new Set([id].concat(nodeRoutes[id] || []));
|
||||
highlight(ids);
|
||||
showInfo(el);
|
||||
});
|
||||
cy.on('mouseover', 'node', function (evt) { showInfo(evt.target); });
|
||||
cy.on('tap', function (evt) { if (evt.target === cy) { reset(); info.style.display = 'none'; } });
|
||||
</script></body></html>`;
|
||||
}
|
||||
+52
-27
@@ -1,21 +1,40 @@
|
||||
function levenshtein(a: string, b: string): number {
|
||||
const m = a.length, n = b.length;
|
||||
const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
||||
for (let i = 0; i <= m; i++) d[i][0] = i;
|
||||
for (let j = 0; j <= n; j++) d[0][j] = j;
|
||||
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
|
||||
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
}
|
||||
return d[m][n];
|
||||
const aLen = a.length,
|
||||
bLen = b.length;
|
||||
const matrix: number[][] = Array.from({ length: aLen + 1 }, () => Array(bLen + 1).fill(0));
|
||||
for (let i = 0; i <= aLen; i++) matrix[i][0] = i;
|
||||
for (let j = 0; j <= bLen; j++) matrix[0][j] = j;
|
||||
|
||||
for (let i = 1; i <= aLen; i++)
|
||||
for (let j = 1; j <= bLen; j++) {
|
||||
matrix[i][j] = Math.min(
|
||||
matrix[i - 1][j] + 1,
|
||||
matrix[i][j - 1] + 1,
|
||||
matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
|
||||
);
|
||||
}
|
||||
|
||||
return matrix[aLen][bLen];
|
||||
}
|
||||
|
||||
/** Returns the candidate within edit distance 2 of `token`, for "did you mean?" hints. */
|
||||
export function nearest(token: string, candidates: Iterable<string>): string | undefined {
|
||||
let best: string | undefined;
|
||||
let bestD = 3; // only suggest edit distance <= 2
|
||||
for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } }
|
||||
let bestDistance = 3; // only suggest edit distance <= 2
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const distance = levenshtein(token, candidate);
|
||||
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A node in the dependency graph: what it provides, what it needs, and where it came from. */
|
||||
export interface GraphNode {
|
||||
name: string;
|
||||
needs: string[];
|
||||
@@ -23,15 +42,16 @@ export interface GraphNode {
|
||||
origin: string;
|
||||
}
|
||||
|
||||
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const n of nodes) for (const key of n.provides) producedBy.set(key, n);
|
||||
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
||||
|
||||
// validate dependencies exist
|
||||
for (const n of nodes) {
|
||||
for (const key of n.needs) {
|
||||
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 ${n.name}`);
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,28 +59,32 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
const ordered: GraphNode[] = [];
|
||||
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
||||
|
||||
const visit = (n: GraphNode, trail: string[]): void => {
|
||||
const s = state.get(n);
|
||||
if (s === 'done') return;
|
||||
if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`);
|
||||
state.set(n, 'visiting');
|
||||
for (const key of n.needs) {
|
||||
const dep = producedBy.get(key);
|
||||
if (dep && dep !== n) visit(dep, [...trail, n.name]);
|
||||
const visit = (node: GraphNode, trail: string[]): void => {
|
||||
const visitState = state.get(node);
|
||||
if (visitState === 'done') return;
|
||||
if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`);
|
||||
state.set(node, 'visiting');
|
||||
|
||||
for (const key of node.needs) {
|
||||
const dependency = producedBy.get(key);
|
||||
if (dependency && dependency !== node) visit(dependency, [...trail, node.name]);
|
||||
}
|
||||
state.set(n, 'done');
|
||||
ordered.push(n);
|
||||
|
||||
state.set(node, 'done');
|
||||
ordered.push(node);
|
||||
};
|
||||
|
||||
for (const n of nodes) visit(n, []);
|
||||
for (const node of nodes) visit(node, []);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
/** 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>();
|
||||
for (const n of ordered) for (const k of n.provides) producedBy.set(k, n);
|
||||
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
||||
const inClosure = new Set<GraphNode>();
|
||||
const work = [...needs];
|
||||
|
||||
while (work.length) {
|
||||
const token = work.pop() as string;
|
||||
const node = producedBy.get(token);
|
||||
@@ -68,5 +92,6 @@ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[]
|
||||
inClosure.add(node);
|
||||
work.push(...node.needs);
|
||||
}
|
||||
return ordered.filter((n) => inClosure.has(n));
|
||||
|
||||
return ordered.filter((node) => inClosure.has(node));
|
||||
}
|
||||
-316
@@ -1,316 +0,0 @@
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { HttpError, isHttpError } from './signals';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
import type { Transport } from './metadata';
|
||||
import type { Bus } from './bus';
|
||||
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart';
|
||||
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
}
|
||||
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }
|
||||
|
||||
export type RouteHandler = (req: {
|
||||
method: string; url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' }
|
||||
export interface MatchedRoute { params: Record<string, string>; def: RouteDef }
|
||||
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: http.IncomingMessage;
|
||||
}
|
||||
export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>> }
|
||||
|
||||
export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void }
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
const segs = path.split('/').filter(Boolean);
|
||||
const pat = pattern.split('/').filter(Boolean);
|
||||
if (pat.length !== segs.length) return undefined;
|
||||
const params: Record<string, string> = {};
|
||||
for (let i = 0; i < pat.length; i++) {
|
||||
if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]);
|
||||
else if (pat[i] !== segs[i]) return undefined;
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
for (const r of routes) {
|
||||
if (r.method !== method) continue;
|
||||
const params = matchPattern(r.pattern, path);
|
||||
if (params) return { params, def: r };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
const qs = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of new URLSearchParams(qs)) out[k] = v;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
function firstToken(v: string | string[] | undefined): string | undefined {
|
||||
const s = Array.isArray(v) ? v[0] : v;
|
||||
return s?.split(',')[0].trim();
|
||||
}
|
||||
function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
|
||||
if (trustProxy) { const p = firstToken(req.headers['x-forwarded-proto']); if (p) return p === 'https'; }
|
||||
return (req.socket as any).encrypted === true;
|
||||
}
|
||||
function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
|
||||
if (trustProxy) { const f = firstToken(req.headers['x-forwarded-for']); if (f) return f; }
|
||||
return req.socket.remoteAddress ?? '';
|
||||
}
|
||||
|
||||
function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||
if (transport === 'sse') return sseEncoder;
|
||||
if (transport === 'ndjson') return ndjsonEncoder;
|
||||
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
|
||||
}
|
||||
|
||||
async function pipeStream(
|
||||
res: http.ServerResponse, stream: AsyncIterable<unknown>, encoder: StreamEncoder,
|
||||
bus?: Bus, name = '', streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
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 });
|
||||
const it = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); }
|
||||
const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); };
|
||||
res.on('close', stop);
|
||||
const closer = () => { try { res.destroy(); } catch { /* */ } };
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await it.next();
|
||||
if (done) break;
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, 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 });
|
||||
}
|
||||
}
|
||||
|
||||
function loadWss(): any | null {
|
||||
try { return require('ws').WebSocketServer; } catch { return null; }
|
||||
}
|
||||
|
||||
function attachWs(
|
||||
server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WSS = loadWss();
|
||||
const wss = WSS ? new WSS({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
if (meshControl && path === meshControl.path) {
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
|
||||
return;
|
||||
}
|
||||
const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params);
|
||||
if (!route) { socket.destroy(); return; }
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, async (ws: any) => {
|
||||
const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } };
|
||||
streams?.add(closer);
|
||||
ws.on('close', () => streams?.delete(closer));
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (d: Buffer) => inbound.push(d.toString()));
|
||||
ws.on('close', () => { inbound.close(); ac.abort(); });
|
||||
ws.on('error', (e: unknown) => inbound.fail(e));
|
||||
|
||||
const name = route.r.pattern;
|
||||
let it: AsyncIterator<unknown> | undefined;
|
||||
ws.on('close', () => { void Promise.resolve(it?.return?.()).catch(() => {}); }); // force-cancel outbound
|
||||
bus?.emit('stream:open', { name });
|
||||
try {
|
||||
const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req });
|
||||
it = out[Symbol.asyncIterator]();
|
||||
while (true) {
|
||||
const { value, done } = await it.next();
|
||||
if (done) break;
|
||||
if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone
|
||||
ws.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
try { ws.close(); } catch { /* already closed */ }
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
if (isHttpError(err)) {
|
||||
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
|
||||
try { ws.close(4000 + err.status, reason); } catch { /* already closed */ }
|
||||
} else {
|
||||
try { ws.close(1011); } catch { /* already closed */ }
|
||||
}
|
||||
} finally {
|
||||
ac.abort();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const trustProxy = opts?.trustProxy ?? false;
|
||||
const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
// 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) };
|
||||
const orig = res.writeHead.bind(res);
|
||||
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||
// normalize (statusMessage?, headers?) overloads
|
||||
const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||
// injected (security/CORS) is authoritative. Node's writeHead does NOT dedupe case-variant
|
||||
// keys — both lines would ship and a browser honors the first — so drop any handler header
|
||||
// whose name case-insensitively collides with an injected one before merging.
|
||||
const merged: Record<string, any> = {};
|
||||
const injectedLower = new Set(Object.keys(injected).map((k) => k.toLowerCase()));
|
||||
let handlerVary: string | undefined;
|
||||
if (hdrs) for (const k of Object.keys(hdrs)) {
|
||||
const lk = k.toLowerCase();
|
||||
if (lk === 'vary') { handlerVary = hdrs[k]; continue; } // merged separately below
|
||||
if (!injectedLower.has(lk)) merged[k] = hdrs[k];
|
||||
}
|
||||
Object.assign(merged, injected);
|
||||
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
|
||||
return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
|
||||
};
|
||||
// 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));
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
const pf = corsPreflightHeaders(opts.cors, req);
|
||||
res.writeHead(204, pf);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||
if (!matched) {
|
||||
res.writeHead(404, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||
return;
|
||||
}
|
||||
let buf: Buffer | undefined;
|
||||
try {
|
||||
buf = await readBody(req, maxBody);
|
||||
} catch (error) {
|
||||
const r = errorToResponse(error);
|
||||
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
||||
res.end(r.body);
|
||||
return;
|
||||
}
|
||||
let body: unknown;
|
||||
const ct = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
if (buf !== undefined && ct.includes('application/json')) {
|
||||
try { body = JSON.parse(buf.toString('utf8')); }
|
||||
catch {
|
||||
res.writeHead(400, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||
return;
|
||||
}
|
||||
} else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) {
|
||||
body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates);
|
||||
} else if (buf !== undefined && ct.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(ct);
|
||||
if (!boundary) {
|
||||
res.writeHead(400, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Invalid multipart body' }));
|
||||
return;
|
||||
}
|
||||
try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); }
|
||||
catch {
|
||||
res.writeHead(400, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Invalid multipart body' }));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const s = buf?.toString('utf8');
|
||||
body = s === '' ? undefined : s;
|
||||
}
|
||||
let result: PipelineResult;
|
||||
try {
|
||||
result = await matched.def.handler({
|
||||
method: req.method ?? 'GET', url, headers: req.headers,
|
||||
params: matched.params, query: parseQuery(url), body,
|
||||
protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
} catch (error) {
|
||||
result = errorToResponse(error);
|
||||
}
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
|
||||
return;
|
||||
}
|
||||
const r: ResponseShape = result;
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
};
|
||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||
const server: http.Server = (opts?.tls
|
||||
? https.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: http.createServer(handler)) as unknown as http.Server;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
|
||||
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
|
||||
// the caller as a {@link BodyReader}.
|
||||
import { HttpError, isHttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import type { MatchedRoute, HttpOptions } from './types';
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
export interface BodyFailure {
|
||||
fail: { status: number; headers: Record<string, string>; body: string };
|
||||
}
|
||||
|
||||
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
|
||||
export type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
|
||||
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
return value instanceof Promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the raw request body, enforcing `limit`.
|
||||
*
|
||||
* The adapter owns this and nothing else about the body, because enforcement is the one place the
|
||||
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
|
||||
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
|
||||
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
|
||||
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
|
||||
* without bound first.
|
||||
*
|
||||
* The failure branch is opaque on purpose: Node answers an over-limit request with
|
||||
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
|
||||
* That header means nothing on the fetch side, and is a forbidden response header on some
|
||||
* runtimes, so the adapter that needs it is the one that attaches it.
|
||||
*
|
||||
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
|
||||
* reader can be built **once per server** instead of once per request: a closure capturing the
|
||||
* request measured at 250 ns per request together with the error-context object it captured —
|
||||
* more than the duplicate route resolution this whole indirection removes.
|
||||
*/
|
||||
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
export async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
|
||||
*
|
||||
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
|
||||
* character for character, because each adapter had to route the request itself in order to know
|
||||
* whether to read a body — and so ended up owning every policy that depends on the matched route.
|
||||
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
|
||||
* runtimes quietly disagree about limits.
|
||||
*/
|
||||
export function acquireBody(
|
||||
read: BodyReader,
|
||||
source: unknown,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const acquired = read(source, limit);
|
||||
|
||||
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
|
||||
// this whole path without a single promise, and an `async` wrapper here would allocate one
|
||||
// regardless. Same reason `handle()` is not async.
|
||||
return isPromise(acquired)
|
||||
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
|
||||
: parseAcquired(acquired, matched, opts, req);
|
||||
}
|
||||
|
||||
function parseAcquired(
|
||||
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
): MaybePromise<{ body: unknown } | BodyFailure> {
|
||||
if ('fail' in acquired) return acquired;
|
||||
|
||||
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
|
||||
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
|
||||
// off the promise path entirely.
|
||||
if (acquired.bytes === undefined) return { body: undefined };
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
|
||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
||||
'error' in parsed
|
||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
|
||||
: { body: parsed.body },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch.
|
||||
import { HttpError, NotFound } from '../signals';
|
||||
import { renderError } from '../transformers';
|
||||
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';
|
||||
|
||||
/**
|
||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
||||
*
|
||||
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
|
||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
||||
*
|
||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
||||
* why that job is pinned to the floor rather than to the current release.
|
||||
*
|
||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the
|
||||
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`.
|
||||
*/
|
||||
const randomUUID: () => string = (() => {
|
||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
|
||||
})();
|
||||
|
||||
/**
|
||||
* A runtime-neutral inbound request.
|
||||
*
|
||||
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
|
||||
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
|
||||
* body, it first had to route the request itself — a body is only read for a request that reaches
|
||||
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
|
||||
* a four-route app walked its table two and a half times per request. Handing over the *ability*
|
||||
* to read instead of the result moves that decision here, where the route is known anyway.
|
||||
*/
|
||||
export interface NeutralRequest {
|
||||
method: string;
|
||||
url: string; // path + query, e.g. "/users/9?x=1"
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
/** 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;
|
||||
/** 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 {
|
||||
injected: Record<string, string>;
|
||||
outcome: NeutralOutcome;
|
||||
}
|
||||
|
||||
/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */
|
||||
export interface Preflight {
|
||||
preflight: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the security + CORS headers that get injected into every response for a request — the same
|
||||
* authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts)
|
||||
* so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's
|
||||
* `patchResponseHeaders` would have installed up-front.
|
||||
*/
|
||||
export function computeInjected(
|
||||
opts: HttpOptions | undefined,
|
||||
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));
|
||||
return injected;
|
||||
}
|
||||
|
||||
function errorOutcome(
|
||||
error: unknown,
|
||||
req: NeutralRequest,
|
||||
injected: Record<string, string>,
|
||||
opts: HttpOptions | undefined,
|
||||
headers: Record<string, string> = {},
|
||||
): HandleResult {
|
||||
const rendered = renderError(error, req, opts?.onError);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: rendered.status,
|
||||
headers: { ...rendered.headers, ...headers },
|
||||
body: req.method === 'HEAD' ? '' : rendered.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function unmatchedOutcome(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
path: string,
|
||||
injected: Record<string, string>,
|
||||
): Promise<HandleResult> {
|
||||
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
||||
const hit = await opts.static(path);
|
||||
|
||||
if (hit) {
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: 200,
|
||||
headers: { 'content-type': hit.contentType },
|
||||
body: req.method === 'HEAD' ? '' : hit.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const allow = allowedMethods(routes, path);
|
||||
|
||||
if (req.method === 'OPTIONS' && allow.length) {
|
||||
return {
|
||||
injected,
|
||||
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
|
||||
};
|
||||
}
|
||||
|
||||
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
||||
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||
}
|
||||
|
||||
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
||||
interface Trace {
|
||||
route?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
||||
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
|
||||
*
|
||||
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
|
||||
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
|
||||
* here in milliseconds while its connection may live for hours, and ending the span at close would put
|
||||
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
|
||||
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
|
||||
*/
|
||||
export function handle(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const bus = opts?.bus;
|
||||
|
||||
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
|
||||
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
|
||||
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
|
||||
if (
|
||||
bus === undefined ||
|
||||
!(
|
||||
bus.hasListeners('request:start') ||
|
||||
bus.hasListeners('request:end') ||
|
||||
bus.hasListeners('route:matched') ||
|
||||
bus.hasListeners('route:unmatched')
|
||||
)
|
||||
) {
|
||||
return dispatch(routes, opts, req, undefined, undefined);
|
||||
}
|
||||
|
||||
return observedDispatch(routes, opts, req, bus);
|
||||
}
|
||||
|
||||
async function observedDispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const watchingEnd = bus.hasListeners('request:end');
|
||||
const startedAt = watchingEnd ? performance.now() : 0;
|
||||
const trace: Trace = {};
|
||||
|
||||
if (bus.hasListeners('request:start'))
|
||||
bus.emit('request:start', {
|
||||
name: `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
const result = await dispatch(routes, opts, req, bus, trace);
|
||||
|
||||
if (watchingEnd) {
|
||||
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
||||
// by the time anything is piped.
|
||||
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
|
||||
bus.emit('request:end', {
|
||||
name: trace.route ?? `${req.method} ${req.url}`,
|
||||
method: req.method,
|
||||
route: trace.route,
|
||||
status,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function dispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
bus: Bus | undefined,
|
||||
trace: Trace | undefined,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const injected = computeInjected(opts, req);
|
||||
let path: string;
|
||||
|
||||
try {
|
||||
path = normalizeRequestPath(req.url.split('?')[0]);
|
||||
} catch {
|
||||
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
|
||||
}
|
||||
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||
}
|
||||
|
||||
const matched = resolveRoute(routes, req.method, path);
|
||||
|
||||
if (!matched) {
|
||||
if (bus?.hasListeners('route:unmatched'))
|
||||
bus.emit('route:unmatched', {
|
||||
name: `${req.method} ${path}`,
|
||||
method: req.method,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
}
|
||||
|
||||
if (trace) trace.route = matched.def.pattern;
|
||||
|
||||
if (bus?.hasListeners('route:matched'))
|
||||
bus.emit('route:matched', {
|
||||
name: matched.def.pattern,
|
||||
route: matched.def.pattern,
|
||||
method: req.method,
|
||||
transport: matched.def.transport,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
|
||||
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
|
||||
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
|
||||
// object per request bought nothing.
|
||||
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
|
||||
|
||||
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
|
||||
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
|
||||
// caller merges `injected` into it exactly as it does for every other outcome.
|
||||
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
|
||||
|
||||
let result: PipelineResult;
|
||||
|
||||
try {
|
||||
result = await matched.def.handler({
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: req.headers,
|
||||
params: matched.params,
|
||||
query: parseQuery(req.url),
|
||||
body: acquired.body,
|
||||
protocol: req.secure ? 'https' : 'http',
|
||||
ip: req.ip,
|
||||
requestId: req.requestId,
|
||||
traceId: req.traceId,
|
||||
});
|
||||
} catch (error) {
|
||||
result = renderError(error, req, opts?.onError);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'stream',
|
||||
headers: encoder.headers,
|
||||
stream: result.stream,
|
||||
encoder,
|
||||
route: matched.def.pattern,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: result.status,
|
||||
headers: result.headers,
|
||||
body: req.method === 'HEAD' ? '' : result.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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.
|
||||
* Extracted from the Node writeHead patch so app.fetch shares the exact logic.
|
||||
*/
|
||||
export function mergeInjectedHeaders(
|
||||
handlerHeaders: Record<string, any> | undefined,
|
||||
injected: Record<string, string>,
|
||||
): Record<string, any> {
|
||||
const merged: Record<string, any> = {};
|
||||
let handlerVary: string | undefined;
|
||||
|
||||
if (handlerHeaders)
|
||||
for (const key of Object.keys(handlerHeaders)) {
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === 'vary') {
|
||||
handlerVary = handlerHeaders[key];
|
||||
continue;
|
||||
}
|
||||
|
||||
// `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);
|
||||
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Public surface of the HTTP module. Internal helpers (request parsing, streaming,
|
||||
// ws upgrade) live in sibling files and are composed by ./server.
|
||||
export type {
|
||||
RequestLimits,
|
||||
HttpOptions,
|
||||
RouteHandler,
|
||||
RouteDef,
|
||||
MatchedRoute,
|
||||
WsOpenCtx,
|
||||
WsRouteDef,
|
||||
MeshControl,
|
||||
} from './types';
|
||||
export { matchPattern, matchRoute, parseQuery } from './router';
|
||||
export { createHttpServer } from './server';
|
||||
@@ -0,0 +1,42 @@
|
||||
import type http from 'http';
|
||||
import { HttpError } from '../signals';
|
||||
|
||||
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
||||
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
|
||||
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/** Returns the first comma-separated token of a header value (handles array-valued headers). */
|
||||
function firstToken(value: string | string[] | undefined): string | undefined {
|
||||
const first = Array.isArray(value) ? value[0] : value;
|
||||
return first?.split(',')[0].trim();
|
||||
}
|
||||
|
||||
/** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */
|
||||
export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
|
||||
if (trustProxy) {
|
||||
const proto = firstToken(req.headers['x-forwarded-proto']);
|
||||
if (proto) return proto === 'https';
|
||||
}
|
||||
|
||||
return (req.socket as any).encrypted === true;
|
||||
}
|
||||
|
||||
/** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */
|
||||
export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
|
||||
if (trustProxy) {
|
||||
const forwarded = firstToken(req.headers['x-forwarded-for']);
|
||||
if (forwarded) return forwarded;
|
||||
}
|
||||
|
||||
return req.socket.remoteAddress ?? '';
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
import type { RouteDef, MatchedRoute } from './types';
|
||||
|
||||
export type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||
| { kind: 'catchAll'; name: string };
|
||||
|
||||
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
|
||||
export interface CompiledPattern {
|
||||
source: string;
|
||||
normalized: string;
|
||||
shape: string;
|
||||
segments: CompiledSegment[];
|
||||
kinds: number[];
|
||||
catchAll: boolean;
|
||||
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
|
||||
allStatic: boolean;
|
||||
}
|
||||
|
||||
const compiledCache = new Map<string, CompiledPattern>();
|
||||
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
const MAX_CONSTRAINT_LENGTH = 128;
|
||||
|
||||
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
||||
export class InvalidRequestPathError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'InvalidRequestPathError';
|
||||
}
|
||||
}
|
||||
|
||||
interface ConstraintToken {
|
||||
length: number;
|
||||
unbounded: boolean;
|
||||
separator: boolean;
|
||||
}
|
||||
|
||||
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
|
||||
function readConstraintToken(source: string): ConstraintToken | undefined {
|
||||
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
|
||||
if (!atom) return undefined;
|
||||
|
||||
const rest = source.slice(atom.length);
|
||||
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
||||
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
||||
|
||||
return {
|
||||
length: atom.length + quantifier.length,
|
||||
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
|
||||
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
|
||||
};
|
||||
}
|
||||
|
||||
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
|
||||
function assertBoundedQuantifier(quantifier: string): void {
|
||||
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
||||
const min = Number(minText);
|
||||
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
|
||||
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
|
||||
}
|
||||
|
||||
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
|
||||
function assertSafeConstraint(source: string): void {
|
||||
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
|
||||
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
|
||||
|
||||
let offset = 0;
|
||||
let previousUnbounded = false;
|
||||
|
||||
while (offset < source.length) {
|
||||
const token = readConstraintToken(source.slice(offset));
|
||||
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
|
||||
if (previousUnbounded && token.unbounded)
|
||||
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
|
||||
previousUnbounded = token.separator ? false : token.unbounded;
|
||||
offset += token.length;
|
||||
}
|
||||
}
|
||||
|
||||
function assertParamName(name: string, pattern: string): void {
|
||||
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
|
||||
}
|
||||
|
||||
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
|
||||
const constraintStart = segment.indexOf('(');
|
||||
|
||||
if (constraintStart < 0) {
|
||||
const name = segment.slice(1);
|
||||
assertParamName(name, pattern);
|
||||
return { kind: 'param', name };
|
||||
}
|
||||
|
||||
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
|
||||
const name = segment.slice(1, constraintStart);
|
||||
const constraintSource = segment.slice(constraintStart + 1, -1);
|
||||
assertParamName(name, pattern);
|
||||
assertSafeConstraint(constraintSource);
|
||||
return {
|
||||
kind: 'param',
|
||||
name,
|
||||
constraintSource,
|
||||
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
|
||||
};
|
||||
}
|
||||
|
||||
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
|
||||
const names = new Set<string>();
|
||||
const compiled: CompiledSegment[] = [];
|
||||
|
||||
for (let index = 0; index < rawSegments.length; index++) {
|
||||
const raw = rawSegments[index];
|
||||
let segment: CompiledSegment;
|
||||
|
||||
if (raw.startsWith(':') && raw.endsWith('*')) {
|
||||
const name = raw.slice(1, -1);
|
||||
assertParamName(name, pattern);
|
||||
if (index !== rawSegments.length - 1)
|
||||
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
|
||||
segment = { kind: 'catchAll', name };
|
||||
} else if (raw.startsWith(':')) {
|
||||
segment = compileParam(raw, pattern);
|
||||
} else {
|
||||
segment = { kind: 'static', value: raw };
|
||||
}
|
||||
|
||||
if (segment.kind !== 'static') {
|
||||
if (names.has(segment.name))
|
||||
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
|
||||
names.add(segment.name);
|
||||
}
|
||||
|
||||
compiled.push(segment);
|
||||
}
|
||||
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function segmentShape(segment: CompiledSegment): string {
|
||||
if (segment.kind === 'static') return `s:${segment.value}`;
|
||||
if (segment.kind === 'catchAll') return 'c';
|
||||
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||
}
|
||||
|
||||
/** Compiles and validates one route pattern. Results are cached by source string. */
|
||||
export function compilePattern(pattern: string): CompiledPattern {
|
||||
const cached = compiledCache.get(pattern);
|
||||
if (cached) return cached;
|
||||
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
||||
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
||||
|
||||
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
||||
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
||||
const segments = compileSegments(pattern, rawSegments);
|
||||
const compiled: CompiledPattern = {
|
||||
source: pattern,
|
||||
normalized,
|
||||
shape: segments.map(segmentShape).join('/'),
|
||||
segments,
|
||||
kinds: segments
|
||||
.filter((segment) => segment.kind !== 'catchAll')
|
||||
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||
allStatic: segments.every((segment) => segment.kind === 'static'),
|
||||
};
|
||||
compiledCache.set(pattern, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
|
||||
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
|
||||
|
||||
/**
|
||||
* Classifies one path segment as `.`, `..`, or neither.
|
||||
*
|
||||
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
|
||||
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
|
||||
* plain form resolves away from.
|
||||
*/
|
||||
function dotSegment(segment: string): '.' | '..' | undefined {
|
||||
if (segment === '.' || segment === '..') return segment;
|
||||
if (segment.length > 6 || !segment.includes('%')) return undefined;
|
||||
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
|
||||
return decoded === '.' || decoded === '..' ? decoded : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
|
||||
*
|
||||
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
|
||||
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
|
||||
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
|
||||
* simply not recoverable there, so rejecting dot segments outright — which is what this module
|
||||
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
|
||||
* runtimes. Resolving is the only rule all four can agree on.
|
||||
*
|
||||
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
|
||||
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
|
||||
*/
|
||||
function resolveDotSegments(path: string): string {
|
||||
const out: string[] = [];
|
||||
|
||||
for (const segment of path.split('/').slice(1)) {
|
||||
const dots = dotSegment(segment);
|
||||
if (dots === '.') continue;
|
||||
|
||||
if (dots === '..') {
|
||||
out.pop();
|
||||
continue;
|
||||
}
|
||||
|
||||
out.push(segment);
|
||||
}
|
||||
|
||||
return `/${out.join('/')}`;
|
||||
}
|
||||
|
||||
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||
export function normalizeRequestPath(path: string): string {
|
||||
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a request path into its non-empty segments.
|
||||
*
|
||||
* Called once per request by the scanning functions below, not once per candidate route. It used to
|
||||
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
|
||||
* registered route on every request, always producing the same array.
|
||||
*/
|
||||
function splitPath(path: string): string[] {
|
||||
return path.split('/').filter(Boolean);
|
||||
}
|
||||
|
||||
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let index = 0; index < compiled.segments.length; index++) {
|
||||
const segment = compiled.segments[index];
|
||||
|
||||
if (segment.kind === 'catchAll') {
|
||||
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
||||
return params;
|
||||
}
|
||||
|
||||
if (index >= pathSegs.length) return undefined;
|
||||
|
||||
if (segment.kind === 'static') {
|
||||
if (segment.value !== pathSegs[index]) return undefined;
|
||||
continue;
|
||||
}
|
||||
|
||||
const value = decodeSegment(pathSegs[index]);
|
||||
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||
params[segment.name] = value;
|
||||
}
|
||||
|
||||
return compiled.segments.length === pathSegs.length ? params : undefined;
|
||||
}
|
||||
|
||||
/** 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), 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);
|
||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||
|
||||
for (let index = 0; index < length; index++) {
|
||||
const kindA = scoreA.kinds[index] ?? -1;
|
||||
const kindB = scoreB.kinds[index] ?? -1;
|
||||
if (kindA !== kindB) return kindA - kindB;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
const pathSegs = splitPath(path);
|
||||
let best: MatchedRoute | undefined;
|
||||
let bestPattern = '';
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.method !== method) continue;
|
||||
const compiled = compilePattern(route.pattern);
|
||||
const params = matchCompiled(compiled, pathSegs);
|
||||
if (!params) continue;
|
||||
|
||||
// An all-static match ends the scan. Specificity ranks a literal segment above every other
|
||||
// kind, so no pattern that also matches this path can outrank one made only of literals — and
|
||||
// an equal rank keeps registration order, which is this route. Finishing the scan would
|
||||
// re-derive the answer already in hand.
|
||||
//
|
||||
// The scan used to run to the end regardless: `/hello` cost the same whether it was declared
|
||||
// first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per
|
||||
// registered route on every request, and it grows with the route table.
|
||||
if (compiled.allStatic) return { params, def: route };
|
||||
|
||||
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||
best = { params, def: route };
|
||||
bestPattern = route.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||
export interface ResolvedRoute extends MatchedRoute {
|
||||
implicitHead: boolean;
|
||||
}
|
||||
|
||||
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
|
||||
const explicit = matchRoute(routes, method, path);
|
||||
if (explicit) return { ...explicit, implicitHead: false };
|
||||
if (method !== 'HEAD') return undefined;
|
||||
|
||||
const fallback = matchRoute(
|
||||
routes.filter((route) => route.transport === 'buffer'),
|
||||
'GET',
|
||||
path,
|
||||
);
|
||||
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
||||
}
|
||||
|
||||
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 (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
|
||||
methods.add(route.method);
|
||||
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
||||
}
|
||||
|
||||
if (methods.size) methods.add('OPTIONS');
|
||||
return [...methods].sort((a, b) => {
|
||||
const indexA = METHOD_ORDER.indexOf(a);
|
||||
const indexB = METHOD_ORDER.indexOf(b);
|
||||
return (
|
||||
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** 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;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { handle, correlateRequest } from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
bus?: Bus;
|
||||
opts?: HttpOptions;
|
||||
trustProxy: boolean;
|
||||
}
|
||||
|
||||
/** 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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||
* @param routes HTTP route definitions.
|
||||
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
|
||||
* @param bus Optional event bus for stream lifecycle events.
|
||||
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
|
||||
* @param opts Limits, TLS, security, CORS, and body-parsing options.
|
||||
*/
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[],
|
||||
wsRoutes: WsRouteDef[] = [],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const trustProxy = opts?.trustProxy ?? false;
|
||||
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');
|
||||
|
||||
// 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;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
|
||||
* 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, trustProxy } = cfg;
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||
const correlation = correlateRequest(req.headers);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
// 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));
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
|
||||
if ('preflight' in result) {
|
||||
res.writeHead(204, result.preflight);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||
res.end(result.outcome.body);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
): Promise<{ bytes: Buffer | undefined } | BodyFailure> {
|
||||
const req = source as http.IncomingMessage;
|
||||
|
||||
return readBodyBytes(req, limit).then(
|
||||
(bytes) => ({ bytes }),
|
||||
(error: unknown) => {
|
||||
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response.
|
||||
* Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged.
|
||||
* Reads `injected` by reference, so CORS keys added after installation still land.
|
||||
*/
|
||||
function patchResponseHeaders(res: http.ServerResponse, injected: Record<string, string>): void {
|
||||
const origWriteHead = res.writeHead.bind(res);
|
||||
|
||||
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||
const merged = mergeInjectedHeaders(handlerHeaders, injected);
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
@@ -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,88 @@
|
||||
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';
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Stream encoder per transport, or `null` for transports that never produce an HTTP stream.
|
||||
* A new transport must add a row — the compiler fails until it does, so it can't silently
|
||||
* inherit ndjson framing.
|
||||
*/
|
||||
const STREAM_ENCODERS: Record<Transport, ((accept: string) => StreamEncoder) | null> = {
|
||||
buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here
|
||||
ws: null, // not an HTTP response; ws routes are served via upgrade, not handle()
|
||||
sse: () => sseEncoder,
|
||||
ndjson: () => ndjsonEncoder,
|
||||
negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder),
|
||||
};
|
||||
|
||||
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */
|
||||
export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||
const pick = STREAM_ENCODERS[transport];
|
||||
if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
|
||||
|
||||
return pick(accept);
|
||||
}
|
||||
|
||||
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
|
||||
export async function pipeStream(
|
||||
res: http.ServerResponse,
|
||||
stream: AsyncIterable<unknown>,
|
||||
encoder: StreamEncoder,
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
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 });
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
if (encoder.ping) {
|
||||
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
||||
ping.unref?.();
|
||||
}
|
||||
|
||||
const stop = () => {
|
||||
if (ping) clearInterval(ping);
|
||||
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
res.on('close', stop);
|
||||
|
||||
const closer = () => {
|
||||
try {
|
||||
res.destroy();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, 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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import type { StaticResolver } from '../views';
|
||||
import type { Bus } from '../bus';
|
||||
|
||||
/** Per-request and per-server resource ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
export interface HttpOptions {
|
||||
/**
|
||||
* Lifecycle events go here. Carried on the options rather than as a parameter so `handle()` —
|
||||
* the one place both the Node and Fetch adapters meet — can emit without either adapter growing
|
||||
* a separate channel for it.
|
||||
*/
|
||||
bus?: Bus;
|
||||
limits?: RequestLimits;
|
||||
streams?: Set<() => void>;
|
||||
tls?: TlsOptions;
|
||||
trustProxy?: boolean;
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
onError?: ErrorRenderer;
|
||||
static?: StaticResolver;
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
export type RouteHandler = (req: {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
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. */
|
||||
export interface RouteDef {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
handler: RouteHandler;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number; // per-route override of the server's maxBodyBytes
|
||||
maxParts?: number; // per-route override of the server's multipart maxParts
|
||||
}
|
||||
|
||||
/** Result of matching a request path against a route: extracted params plus the matched definition. */
|
||||
export interface MatchedRoute {
|
||||
params: Record<string, string>;
|
||||
def: RouteDef;
|
||||
}
|
||||
|
||||
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: WsRequest;
|
||||
}
|
||||
|
||||
/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */
|
||||
export interface WsRouteDef {
|
||||
pattern: string;
|
||||
open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>>;
|
||||
}
|
||||
|
||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||
export interface MeshControl {
|
||||
path: string;
|
||||
/**
|
||||
* Serves one control connection over the neutral socket — the same capability every other ws
|
||||
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
|
||||
* Resolves when the connection ends, like `runWsConnection`.
|
||||
*/
|
||||
handle(socket: WsSocket): Promise<void>;
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
|
||||
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
|
||||
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
||||
const iterator = source[Symbol.asyncIterator]();
|
||||
const te = new TextEncoder();
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const { value, done } = await iterator.next();
|
||||
|
||||
if (done) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const encoded = encoder.encode(value);
|
||||
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
||||
controller.enqueue(bytes);
|
||||
} catch (err) {
|
||||
controller.error(err);
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
await iterator.return?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */
|
||||
function headersToRecord(headers: Headers): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
headers.forEach((value, key) => {
|
||||
out[key] = value;
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 readFetchBytes(
|
||||
source: unknown,
|
||||
limit: number,
|
||||
opts: HttpOptions | undefined,
|
||||
): MaybePromise<{ bytes: Buffer | undefined } | BodyFailure> {
|
||||
const request = source as Request;
|
||||
// Not `async`: a bodiless request answers without allocating a promise at all.
|
||||
if (!request.body) return { bytes: undefined };
|
||||
|
||||
return request.arrayBuffer().then((arrayBuffer) => {
|
||||
if (arrayBuffer.byteLength > limit) {
|
||||
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
|
||||
// a `url`/`headers` pair captured up-front cost more than the work it saved.
|
||||
const url = new URL(request.url);
|
||||
const errReq: ErrorRequest = {
|
||||
method: request.method,
|
||||
url: url.pathname + url.search,
|
||||
headers: headersToRecord(request.headers),
|
||||
};
|
||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
|
||||
}
|
||||
|
||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
type ResponseBody = ConstructorParameters<typeof Response>[0];
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
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 = [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:
|
||||
* 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) {
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname + url.search;
|
||||
const headers = headersToRecord(request.headers);
|
||||
// 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 });
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
readBody,
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
});
|
||||
|
||||
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
|
||||
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
|
||||
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
|
||||
}
|
||||
|
||||
return outcomeToResponse(result);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
|
||||
/**
|
||||
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
|
||||
* to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose:
|
||||
* that module *runs* a connection, this one *builds* one from a host runtime's socket.
|
||||
*/
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
||||
|
||||
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
|
||||
export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string {
|
||||
return typeof data === 'string' ? data : decoder.decode(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives
|
||||
* url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in.
|
||||
*/
|
||||
export function toWsRequest(request: Request, ip: string): WsRequest {
|
||||
const url = new URL(request.url);
|
||||
const headers: Record<string, string> = {};
|
||||
request.headers.forEach((value, key) => {
|
||||
headers[key] = value;
|
||||
});
|
||||
|
||||
return {
|
||||
url: url.pathname + url.search,
|
||||
headers,
|
||||
protocol: url.protocol === 'https:' ? 'https' : 'http',
|
||||
ip,
|
||||
};
|
||||
}
|
||||
|
||||
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
||||
export interface EventfulSocket {
|
||||
readonly readyState: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
addEventListener(
|
||||
type: 'open' | 'message' | 'close' | 'error',
|
||||
listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void,
|
||||
): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}:
|
||||
* creates the inbound channel and abort controller and wires message/close/error into them.
|
||||
* Bun does not use this — its socket events are delivered to a server-level handler rather
|
||||
* than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`.
|
||||
*/
|
||||
export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
|
||||
host.addEventListener('message', (event) => {
|
||||
inbound.push(decodeMessage(event.data as string | ArrayBuffer));
|
||||
});
|
||||
host.addEventListener('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
host.addEventListener('error', () => {
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
});
|
||||
|
||||
return neutralSocket(host, inbound, ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an
|
||||
* already-wired channel and abort controller. `close`/`terminate` swallow throws so
|
||||
* callers never have to guard an already-closed socket.
|
||||
*/
|
||||
export function neutralSocket(
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||
inbound: ReturnType<typeof channel<unknown>>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
return {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return host.readyState === OPEN;
|
||||
},
|
||||
send: (data) => {
|
||||
host.send(data);
|
||||
},
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
host.close(code, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
terminate: () => {
|
||||
try {
|
||||
(host.terminate ?? host.close).call(host);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||
|
||||
/**
|
||||
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
|
||||
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
|
||||
*
|
||||
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
|
||||
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
|
||||
* browser-compatible event API alongside its EventEmitter one.
|
||||
*/
|
||||
export function loadWebSocketCtor(): SocketCtor {
|
||||
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
||||
|
||||
if (platform) return platform;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws') as SocketCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once
|
||||
* the socket is live (the caller's cue to send its first frame) and rejects if it never opens.
|
||||
*
|
||||
* `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI
|
||||
* on a single Node version would silently cover only one of the two paths.
|
||||
*/
|
||||
export function connectSocket(
|
||||
url: string,
|
||||
Ctor: SocketCtor = loadWebSocketCtor(),
|
||||
): { socket: WsSocket; opened: Promise<void> } {
|
||||
const host = new Ctor(url);
|
||||
// registered before eventSocket's own error listener, so a connect failure rejects `opened`
|
||||
// with the host's real error rather than eventSocket's generic one
|
||||
const opened = new Promise<void>((resolve, reject) => {
|
||||
host.addEventListener('open', () => resolve());
|
||||
host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`)));
|
||||
});
|
||||
|
||||
return { socket: eventSocket(host), opened };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before*
|
||||
* `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded,
|
||||
* that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so
|
||||
* edge can hand it to `ctx.waitUntil`.
|
||||
*/
|
||||
export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise<void> {
|
||||
return app.upgrade(request, socket).catch(() => {
|
||||
socket.close(1011, 'internal error'); // neutral close already swallows throws
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */
|
||||
export interface WsSocket {
|
||||
readonly inbound: AsyncIterable<unknown>;
|
||||
readonly abort: AbortSignal;
|
||||
readonly isOpen: boolean;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
export function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
path: string,
|
||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
||||
return wsRoutes
|
||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||
.find((entry) => entry.params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `connection` with the socket registered for force-close on shutdown, unregistering it
|
||||
* when the connection ends. Without this a long-lived socket keeps `server.close()` waiting for
|
||||
* a peer that has no reason to hang up — the mesh control channel is exactly that shape.
|
||||
*/
|
||||
export async function trackUntil(
|
||||
socket: WsSocket,
|
||||
connection: Promise<void>,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
|
||||
try {
|
||||
await connection;
|
||||
} finally {
|
||||
streams?.delete(closer);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
||||
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
|
||||
const closer = () => {
|
||||
try {
|
||||
socket.terminate();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
return { closer };
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (!socket.isOpen) break;
|
||||
socket.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes with 4000+status for HttpErrors, 1011 otherwise. */
|
||||
function closeOnError(socket: WsSocket, err: unknown): void {
|
||||
if (isHttpError(err)) {
|
||||
const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
|
||||
|
||||
try {
|
||||
socket.close(4000 + err.status, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
socket.close(1011);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the full per-connection lifecycle over a neutral socket capability. */
|
||||
export async function runWsConnection(
|
||||
socket: WsSocket,
|
||||
request: WsRequest,
|
||||
route: { def: WsRouteDef; params: Record<string, string> | undefined },
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
|
||||
const onAbort = () => {
|
||||
streams?.delete(closer);
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||
bus?.emit('stream:open', { name });
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({
|
||||
params: route.params ?? {},
|
||||
inbound: socket.inbound,
|
||||
abort: socket.abort,
|
||||
req: request,
|
||||
});
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(socket, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
closeOnError(socket, err);
|
||||
} finally {
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import type http from 'http';
|
||||
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';
|
||||
|
||||
/** 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;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
|
||||
function reject501(socket: any): void {
|
||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
/** Handles the mesh-control upgrade path; returns true when the request was for the mesh control endpoint. */
|
||||
function handleMeshUpgrade(
|
||||
wss: any,
|
||||
meshControl: MeshControl,
|
||||
path: string,
|
||||
req: http.IncomingMessage,
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
streams?: Set<() => void>,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return true;
|
||||
}
|
||||
|
||||
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
||||
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
||||
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
|
||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
||||
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
const neutral = nodeSocket(ws);
|
||||
|
||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
||||
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||
return {
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
||||
ip: req.socket.remoteAddress ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */
|
||||
function nodeSocket(ws: any): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
return {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return ws.readyState === 1; // 1 = OPEN
|
||||
},
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
ws.close(code, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
terminate: () => (ws.terminate ?? ws.close).call(ws),
|
||||
};
|
||||
}
|
||||
|
||||
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
|
||||
export function attachWs(
|
||||
server: http.Server,
|
||||
wsRoutes: WsRouteDef[],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
});
|
||||
}
|
||||
+67
-10
@@ -1,32 +1,89 @@
|
||||
/**
|
||||
* @green-tea/core — a decorator-driven, type-safe HTTP framework.
|
||||
* Public API barrel: application bootstrap, routing/DI decorators, streaming,
|
||||
* request validation, security helpers, and the cross-server mesh.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
|
||||
export const VERSION = '0.0.0';
|
||||
/** Package version, replaced at publish time. */
|
||||
export const VERSION = '26.8.0-beta.0';
|
||||
|
||||
// Application
|
||||
export { createApp } from './app';
|
||||
export type { App, InspectLine, Explain } from './app';
|
||||
export type { App, InspectLine, Explain, MeshConfig } from './app';
|
||||
|
||||
// Graph visualization
|
||||
export { toMermaid, toDOT } from './graph-viz';
|
||||
export type { GraphView } from './graph-viz';
|
||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
||||
export { buildOpenApi } from './openapi';
|
||||
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
|
||||
|
||||
// Views
|
||||
export { render } from './views';
|
||||
|
||||
// Routing & decorators
|
||||
export {
|
||||
Provider,
|
||||
Step,
|
||||
Route,
|
||||
Get,
|
||||
Head,
|
||||
Module,
|
||||
Transformer,
|
||||
Sse,
|
||||
Ws,
|
||||
Stream,
|
||||
Post,
|
||||
Put,
|
||||
Patch,
|
||||
Delete,
|
||||
Options,
|
||||
Html,
|
||||
} from './metadata';
|
||||
export type { Transport, HttpMethod, RouteDecorator } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
|
||||
// Transformers & error signals
|
||||
export { JsonTransformer } from './transformers';
|
||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
|
||||
export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers';
|
||||
export {
|
||||
HttpError,
|
||||
Unauthorized,
|
||||
NotFound,
|
||||
Redirect,
|
||||
NotModified,
|
||||
ValidationError,
|
||||
TransportMismatchError,
|
||||
} from './signals';
|
||||
|
||||
// Bus & flow
|
||||
export { Bus } from './bus';
|
||||
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
|
||||
export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
export { needs, ctx, param, query, body, headers } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec } from './params';
|
||||
|
||||
// Parameter decorators
|
||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } 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 { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export { inbound, abort } from './params';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export type { MeshConfig } from './app';
|
||||
|
||||
// HTTP, security & validation
|
||||
export type { RequestLimits } from './http';
|
||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||
export type { UploadedFile, MultipartBody } from './multipart';
|
||||
export type { StandardSchemaV1 } from './standard-schema';
|
||||
|
||||
// Mesh
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
+479
-67
@@ -1,99 +1,511 @@
|
||||
import type { Bus } from '../bus';
|
||||
import type { Logger } from '../logger';
|
||||
import { HttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
|
||||
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';
|
||||
|
||||
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
|
||||
export interface Link {
|
||||
manifest: Manifest;
|
||||
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function loadWs(): any {
|
||||
return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class
|
||||
/** 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 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.
|
||||
*/
|
||||
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
|
||||
for (const [, entry] of pending) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(new HttpError(503, reason));
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
||||
function sendRpc(
|
||||
socket: WsSocket | undefined,
|
||||
pending: Map<string, PendingEntry>,
|
||||
id: string,
|
||||
kind: 'scope' | 'route',
|
||||
name: string,
|
||||
ctx: RequestEnvelope,
|
||||
timeoutMs: number,
|
||||
): 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. 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}'`));
|
||||
}
|
||||
|
||||
return new Promise((resolveCall, rejectCall) => {
|
||||
// 504: the link is alive but the teapot did not answer in time — a gateway timeout,
|
||||
// which is a different operational story from a link that is down.
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
|
||||
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
|
||||
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
}
|
||||
|
||||
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
||||
function settleRpcResponse(
|
||||
pending: Map<string, PendingEntry>,
|
||||
frame: Extract<Frame, { type: 'rpc-res' }>,
|
||||
bus?: Bus,
|
||||
): void {
|
||||
const entry = pending.get(frame.id);
|
||||
if (!entry) return;
|
||||
pending.delete(frame.id);
|
||||
clearTimeout(entry.timer);
|
||||
|
||||
if (frame.ok) {
|
||||
entry.resolve(frame.result);
|
||||
} else {
|
||||
// `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));
|
||||
}
|
||||
}
|
||||
|
||||
/** Default gap between heartbeat pings. Two missed rounds close the link. */
|
||||
const HEARTBEAT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Close code for a link we hang up on because its teapot went quiet.
|
||||
*
|
||||
* Not 1011: a *client* may only send 1000 or 3000-4999 — anything else throws `invalid code`,
|
||||
* and our neutral close swallows throws, so a reserved code would leave the link open while
|
||||
* looking like it closed. 4000+ is the application range, so 4011 mirrors 1011's meaning.
|
||||
*/
|
||||
const CLOSE_HEARTBEAT_TIMEOUT = 4011;
|
||||
|
||||
/**
|
||||
* Pings the teapot on an interval and closes the link if a round goes unanswered.
|
||||
*
|
||||
* 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, emits `mesh:disconnect`, and starts
|
||||
* the reconnect backoff.
|
||||
*
|
||||
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
||||
*/
|
||||
function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void; markAlive: () => void } {
|
||||
let answered = true;
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (!answered) {
|
||||
socket.close(CLOSE_HEARTBEAT_TIMEOUT, 'mesh heartbeat timeout'); // aborts -> disconnect + reject pending
|
||||
return;
|
||||
}
|
||||
|
||||
answered = false;
|
||||
socket.send(encode({ type: 'ping' }));
|
||||
}, everyMs);
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
stop: () => clearInterval(timer),
|
||||
markAlive: () => {
|
||||
answered = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 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>;
|
||||
bus?: Bus;
|
||||
resolve: (session: Session) => void;
|
||||
reject: (error: unknown) => void;
|
||||
onManifest: (socket: WsSocket) => Session['heartbeat'];
|
||||
onPong: () => void;
|
||||
}
|
||||
|
||||
/** 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(
|
||||
refused(
|
||||
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
|
||||
),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const heartbeat = hs.onManifest(hs.socket);
|
||||
|
||||
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
|
||||
// the graph is refused after this point, and announcing a connection we are about to hang up on
|
||||
// would tell an operator the opposite of what happened.
|
||||
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
|
||||
}
|
||||
|
||||
/** Consume the 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;
|
||||
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
continue; // undecodable frames are ignored
|
||||
}
|
||||
|
||||
if (frame.type === 'manifest') settleManifest(frame, hs);
|
||||
else if (frame.type === 'pong') hs.onPong();
|
||||
else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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;
|
||||
pending: Map<string, PendingEntry>;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
onEnd: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}`));
|
||||
}, args.timeoutMs);
|
||||
|
||||
const hs: Handshake = {
|
||||
url: args.url,
|
||||
socket,
|
||||
pending: args.pending,
|
||||
bus: args.bus,
|
||||
resolve,
|
||||
reject,
|
||||
onManifest: (established) => {
|
||||
handshook = true;
|
||||
clearTimeout(connectTimer);
|
||||
// started only once authenticated: an unauthenticated peer should not be pinging
|
||||
heartbeat = startHeartbeat(established, args.heartbeatMs);
|
||||
|
||||
return heartbeat;
|
||||
},
|
||||
onPong: () => heartbeat?.markAlive(),
|
||||
};
|
||||
|
||||
opened.then(
|
||||
() => {
|
||||
accepted = true;
|
||||
socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }));
|
||||
},
|
||||
(error) => reject(error),
|
||||
);
|
||||
|
||||
// abort fires on close *and* on error (see eventSocket), covering both paths the raw
|
||||
// 'close' listener used to: a refused handshake and a dropped link.
|
||||
socket.abort.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(connectTimer);
|
||||
heartbeat?.stop();
|
||||
|
||||
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 },
|
||||
);
|
||||
|
||||
void readFrames(hs).catch(() => {
|
||||
/* inbound failed; the abort listener above reports it */
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
|
||||
function scopeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
|
||||
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
|
||||
*/
|
||||
function routeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the boot manifest had that a returning one does not.
|
||||
*
|
||||
* The graph was validated at boot against the first manifest and is already serving. A token that
|
||||
* vanished cannot be validated away after the fact, so a manifest missing anything this link
|
||||
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
|
||||
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
|
||||
*/
|
||||
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||
const scopes = scopeKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const scope of booted.scopes) {
|
||||
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
|
||||
}
|
||||
|
||||
for (const route of booted.routes) {
|
||||
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
|
||||
missing.push(`route '${route.method} ${route.pattern}'`);
|
||||
}
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
|
||||
function backoffBounds(
|
||||
reconnect: boolean | ReconnectOptions | undefined,
|
||||
): { initial: number; max: number } | undefined {
|
||||
if (reconnect === false) return undefined;
|
||||
const opts = typeof reconnect === 'object' ? reconnect : {};
|
||||
|
||||
return {
|
||||
initial: opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS,
|
||||
max: opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. The returned `Link` outlives any single socket: when a session drops, the link keeps its
|
||||
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
|
||||
*
|
||||
* `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
/** Reconnect after a dropped session (default: on). `false` restores the old fail-once behaviour. */
|
||||
reconnect?: boolean | ReconnectOptions;
|
||||
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
|
||||
onManifestChange?: ManifestPolicy;
|
||||
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
|
||||
onReconnect?: () => void;
|
||||
logger?: Logger;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const WS = loadWs();
|
||||
const ws = new WS(args.url);
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType<typeof setTimeout> }
|
||||
>();
|
||||
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||
const bounds = backoffBounds(args.reconnect);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
|
||||
let refusalLogged = '';
|
||||
|
||||
const link: Link = {
|
||||
// replaced with the real manifest before this object escapes; a reconnect never changes it,
|
||||
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
|
||||
manifest: { scopes: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
close: () => {
|
||||
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||
// the application hung up would leave a process that cannot exit.
|
||||
state.closed = true;
|
||||
clearTimeout(state.retry);
|
||||
state.socket?.close();
|
||||
},
|
||||
};
|
||||
// ids only need to be unique within this link: `pending` is per-link, so a per-link counter
|
||||
// suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
const connId = `c${connSeq++}`;
|
||||
let manifest: Manifest | undefined;
|
||||
|
||||
return new Promise<Link>((resolve, reject) => {
|
||||
const connectTimer = setTimeout(() => {
|
||||
ws.close();
|
||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||
}, timeoutMs);
|
||||
const sessionArgs = (onEnd: () => void): SessionArgs => ({
|
||||
url: args.url,
|
||||
secret: args.secret,
|
||||
timeoutMs,
|
||||
heartbeatMs,
|
||||
pending,
|
||||
bus: args.bus,
|
||||
Ctor: args.Ctor,
|
||||
onEnd,
|
||||
});
|
||||
|
||||
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
|
||||
ws.on('error', (e: unknown) => reject(e));
|
||||
ws.on('close', () => {
|
||||
clearTimeout(connectTimer);
|
||||
/** 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 });
|
||||
for (const [, p] of pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(new Error('mesh link closed'));
|
||||
}
|
||||
pending.clear();
|
||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
});
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
scheduleRetry(attempt);
|
||||
};
|
||||
|
||||
ws.on('message', (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
return;
|
||||
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
|
||||
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => {
|
||||
const missing = missingFromManifest(link.manifest, session.manifest);
|
||||
|
||||
if (missing.length > 0) {
|
||||
session.heartbeat.stop();
|
||||
session.socket.close();
|
||||
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
|
||||
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
|
||||
// link keeps retrying rather than giving up.
|
||||
const fingerprint = missing.join('|');
|
||||
|
||||
if (fingerprint !== refusalLogged) {
|
||||
refusalLogged = fingerprint;
|
||||
args.logger?.warn(
|
||||
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
|
||||
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
|
||||
);
|
||||
}
|
||||
|
||||
if (frame.type === 'manifest') {
|
||||
manifest = { scopes: frame.scopes, routes: frame.routes };
|
||||
clearTimeout(connectTimer);
|
||||
return false;
|
||||
}
|
||||
|
||||
refusalLogged = '';
|
||||
state.socket = session.socket;
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
resolve({
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = `${connId}:${counter++}`;
|
||||
return new Promise((res, rej) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
rej(new Error(`mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve: res, reject: rej, timer });
|
||||
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
},
|
||||
close() {
|
||||
ws.close();
|
||||
},
|
||||
});
|
||||
if (reconnected) args.onReconnect?.();
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const attemptReconnect = async (attempt: number): Promise<void> => {
|
||||
if (state.closed) return;
|
||||
|
||||
try {
|
||||
const session = await openSession(sessionArgs(() => endSession(attempt)));
|
||||
|
||||
if (state.closed) {
|
||||
session.socket.close(); // hung up while this attempt was in flight
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === 'rpc-res') {
|
||||
const p = pending.get(frame.id);
|
||||
if (!p) return;
|
||||
pending.delete(frame.id);
|
||||
clearTimeout(p.timer);
|
||||
if (frame.ok) {
|
||||
p.resolve(frame.result);
|
||||
} else {
|
||||
args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
||||
p.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
|
||||
} catch {
|
||||
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
|
||||
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
|
||||
if (!state.socket && !state.retry) scheduleRetry(attempt);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return openSession(sessionArgs(() => endSession(0))).then((session) => {
|
||||
link.manifest = session.manifest;
|
||||
adopt(session, 0, false);
|
||||
|
||||
return link;
|
||||
});
|
||||
}
|
||||
+207
-14
@@ -1,32 +1,225 @@
|
||||
/**
|
||||
* 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. Peers refuse each other on mismatch rather
|
||||
* than misparsing downstream.
|
||||
*
|
||||
* **This is a compatibility boundary, not a changelog.** Bump it only when a peer running the
|
||||
* old version would *misparse a frame or misbehave silently*:
|
||||
*
|
||||
* - removing or renaming a field, or changing its type or meaning;
|
||||
* - adding a **required** field;
|
||||
* - adding a frame type that expects an answer — an old peer cannot decode it, drops it as
|
||||
* undecodable, and the sender waits for a reply that will never come.
|
||||
*
|
||||
* Adding an **optional** field is not one of those: `decode` validates only the fields a frame
|
||||
* type requires and passes extras through untouched, so an old peer ignores what it does not
|
||||
* know and keeps answering. That is degraded, not broken, and does not earn a bump.
|
||||
*
|
||||
* Bumping per change would make the number mean "work happened" rather than "we are
|
||||
* incompatible", which is the one thing it is here to say.
|
||||
*/
|
||||
export const MESH_PROTOCOL_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Serialized request context sent across the mesh for a scope or route RPC.
|
||||
*
|
||||
* `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 };
|
||||
}
|
||||
|
||||
export interface ScopeEntry { token: string; scope: 'app' | 'request' }
|
||||
export interface RouteEntry { method: string; pattern: string }
|
||||
export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
/** 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. */
|
||||
export interface Manifest {
|
||||
scopes: ScopeEntry[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated union of every message on the mesh wire. The handshake frames carry `v`.
|
||||
*
|
||||
* `ping`/`pong` are application frames rather than WebSocket protocol pings on purpose: the `ws`
|
||||
* package exposes `ws.ping()`, but the platform `WebSocket` that Deno and Bun provide does not,
|
||||
* so a protocol-level heartbeat could not work on every runtime mesh claims to support.
|
||||
*/
|
||||
export type Frame =
|
||||
| { type: 'hello'; secret: string }
|
||||
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
| { type: 'hello'; v: number; secret: string }
|
||||
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; 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 } };
|
||||
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
|
||||
| { type: 'ping' }
|
||||
| { type: 'pong' };
|
||||
|
||||
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
|
||||
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;
|
||||
|
||||
export function encode(f: Frame): string {
|
||||
return JSON.stringify(f);
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed
|
||||
* straight to the scope/route resolvers, so a bad shape must die here rather than surface as a
|
||||
* confusing failure downstream. A new frame type must add a row — the compiler fails until it does.
|
||||
*/
|
||||
const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
||||
hello: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!isString(frame.secret)) bad('secret must be a string');
|
||||
},
|
||||
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');
|
||||
},
|
||||
'rpc-req': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'");
|
||||
if (!isString(frame.name)) bad('name must be a string');
|
||||
if (!isObject(frame.ctx)) bad('ctx must be an object');
|
||||
},
|
||||
'rpc-res': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
if (typeof frame.ok !== 'boolean') bad('ok must be a boolean');
|
||||
if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false');
|
||||
},
|
||||
ping: () => {
|
||||
/* the tag is the whole frame */
|
||||
},
|
||||
pong: () => {
|
||||
/* the tag is the whole frame */
|
||||
},
|
||||
};
|
||||
|
||||
/** 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';
|
||||
}
|
||||
|
||||
export function decode(s: string): Frame {
|
||||
const f = JSON.parse(s) as { type?: unknown };
|
||||
if (typeof f.type !== 'string' || !TYPES.has(f.type)) {
|
||||
throw new Error(`unknown frame type: ${String(f.type)}`);
|
||||
/**
|
||||
* 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 });
|
||||
}
|
||||
return f as Frame;
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */
|
||||
export function decode(json: string): Frame {
|
||||
const parsed = JSON.parse(json) as Record<string, unknown>;
|
||||
const type = parsed.type;
|
||||
// own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor']
|
||||
// would otherwise resolve up the prototype chain to a truthy non-check.
|
||||
const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type);
|
||||
const check = known ? SHAPE[type as Frame['type']] : undefined;
|
||||
|
||||
if (!check) throw new Error(`unknown frame type: ${String(type)}`);
|
||||
|
||||
check(parsed, (why) => {
|
||||
throw new Error(`malformed ${String(type)} frame: ${why}`);
|
||||
});
|
||||
|
||||
return parsed as unknown as Frame;
|
||||
}
|
||||
+40
-12
@@ -2,34 +2,62 @@ import type { Link } from './link';
|
||||
import type { RequestEnvelope } from './protocol';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
|
||||
export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise<Record<string, unknown>> }
|
||||
export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise<ResponseShape> }
|
||||
/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */
|
||||
export interface RemoteScopeNode {
|
||||
name: string;
|
||||
run: (ctx: any) => Promise<Record<string, unknown>>;
|
||||
}
|
||||
/** Local proxy for a remote route: forwards the request envelope over the link. */
|
||||
export interface RemoteRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRemote(link: Link, origin: string): {
|
||||
providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[];
|
||||
/** 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 s of link.manifest.scopes) {
|
||||
|
||||
for (const scope of link.manifest.scopes) {
|
||||
const node: RemoteScopeNode = {
|
||||
name: s.token,
|
||||
run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }),
|
||||
name: scope.token,
|
||||
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
|
||||
};
|
||||
(s.scope === 'app' ? providers : steps).push(node);
|
||||
(scope.scope === 'app' ? providers : steps).push(node);
|
||||
}
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({
|
||||
method: r.method, pattern: r.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape,
|
||||
|
||||
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 };
|
||||
}
|
||||
+226
-46
@@ -1,11 +1,48 @@
|
||||
import crypto from 'crypto';
|
||||
// node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare
|
||||
// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve
|
||||
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
||||
import crypto from 'node:crypto';
|
||||
import type { Bus } from '../bus';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
import { isHttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
|
||||
import {
|
||||
encode,
|
||||
decode,
|
||||
untransportable,
|
||||
MESH_PROTOCOL_VERSION,
|
||||
type Manifest,
|
||||
type RequestEnvelope,
|
||||
type RouteEntry,
|
||||
type Frame,
|
||||
} from './protocol';
|
||||
|
||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
/**
|
||||
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
||||
*
|
||||
* The teacup has always bounded its side of the handshake; the teapot had no equivalent, so a peer
|
||||
* could connect and simply never send `hello`, holding a socket indefinitely without proving
|
||||
* anything. Generous on purpose — this is a deadline against silence, not a latency budget.
|
||||
*/
|
||||
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Largest control frame the teapot will parse, in characters.
|
||||
*
|
||||
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
|
||||
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
|
||||
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
|
||||
* documented ceiling on the platform sockets Deno and Bun provide).
|
||||
*
|
||||
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
|
||||
* overhead of the envelope around it.
|
||||
*/
|
||||
const MAX_FRAME_CHARS = 4_000_000;
|
||||
|
||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||
export function buildManifest(args: {
|
||||
providers: string[]; // exported provider tokens (app-scope)
|
||||
steps: string[]; // exported step tokens (request-scope)
|
||||
@@ -20,13 +57,14 @@ export function buildManifest(args: {
|
||||
};
|
||||
}
|
||||
|
||||
function safeEqual(a: string, b: string): boolean {
|
||||
const ba = Buffer.from(a);
|
||||
const bb = Buffer.from(b);
|
||||
if (ba.length !== bb.length) return false;
|
||||
return crypto.timingSafeEqual(ba, bb);
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
const leftBuf = Buffer.from(left);
|
||||
const rightBuf = Buffer.from(right);
|
||||
if (leftBuf.length !== rightBuf.length) return false;
|
||||
return crypto.timingSafeEqual(leftBuf, rightBuf);
|
||||
}
|
||||
|
||||
/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */
|
||||
export interface MeshControlDeps {
|
||||
secret: string;
|
||||
manifest: Manifest;
|
||||
@@ -35,48 +73,190 @@ export interface MeshControlDeps {
|
||||
bus?: Bus;
|
||||
}
|
||||
|
||||
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token));
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`));
|
||||
/** The rpc-req member of the {@link Frame} union. */
|
||||
type RpcReqFrame = Extract<Frame, { type: 'rpc-req' }>;
|
||||
|
||||
/** Build a 403 "not exported" error for an unknown scope/route token. */
|
||||
function notExported(name: string): Error {
|
||||
const error: any = new Error(`not exported: ${name}`);
|
||||
error.status = 403;
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch.
|
||||
* The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it
|
||||
* "wrong secret" would send its operator hunting the wrong bug.
|
||||
*/
|
||||
function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean {
|
||||
if (frame.type !== 'hello') {
|
||||
socket.close(1008);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||
socket.close(
|
||||
1008,
|
||||
`mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!safeEqual(frame.secret, deps.secret)) {
|
||||
socket.close(1008);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
socket.send(
|
||||
encode({
|
||||
type: 'manifest',
|
||||
v: MESH_PROTOCOL_VERSION,
|
||||
scopes: deps.manifest.scopes,
|
||||
routes: deps.manifest.routes,
|
||||
}),
|
||||
);
|
||||
deps.bus?.emit('mesh:connect', { name: 'teapot' });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */
|
||||
function resolveRpc(
|
||||
frame: RpcReqFrame,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<unknown> {
|
||||
const { kind, name, ctx } = frame;
|
||||
|
||||
if (kind === 'scope') {
|
||||
if (!exportedScopes.has(name)) throw notExported(name);
|
||||
|
||||
return deps.resolveScope(name, ctx);
|
||||
}
|
||||
|
||||
if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name);
|
||||
|
||||
return deps.resolveRoute(name, ctx);
|
||||
}
|
||||
|
||||
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
|
||||
async function handleRpc(
|
||||
socket: WsSocket,
|
||||
frame: RpcReqFrame,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<void> {
|
||||
const { id, name } = frame;
|
||||
|
||||
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) {
|
||||
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
|
||||
|
||||
deps.bus?.emit('mesh:rpc:error', { name, error: err });
|
||||
socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
|
||||
}
|
||||
}
|
||||
|
||||
/** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */
|
||||
async function serveFrames(
|
||||
socket: WsSocket,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
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(raw);
|
||||
} catch {
|
||||
continue; // undecodable frames are ignored, as before
|
||||
}
|
||||
|
||||
if (!authed) {
|
||||
authed = handleHandshake(socket, frame, deps);
|
||||
if (authed) clearTimeout(handshakeTimer);
|
||||
continue;
|
||||
}
|
||||
|
||||
// answered only after the handshake: an unauthenticated peer gets no signal at all
|
||||
if (frame.type === 'ping') {
|
||||
socket.send(encode({ type: 'pong' }));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (frame.type !== 'rpc-req') continue;
|
||||
|
||||
// deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')`
|
||||
// listener. The id-keyed `pending` map on the peer exists to allow in-flight concurrency —
|
||||
// awaiting here would silently serialize every mesh call.
|
||||
void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes);
|
||||
}
|
||||
} 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' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
|
||||
export function createMeshControl(deps: MeshControlDeps): {
|
||||
path: string;
|
||||
handle: (socket: WsSocket) => Promise<void>;
|
||||
} {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||
|
||||
return {
|
||||
path: MESH_CONTROL_PATH,
|
||||
handle(ws: any) {
|
||||
let authed = false;
|
||||
ws.on('message', async (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try { frame = decode(String(data)); } catch { return; }
|
||||
|
||||
if (!authed) {
|
||||
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
|
||||
deps.bus?.emit('mesh:connect', { name: 'teapot' });
|
||||
} else {
|
||||
ws.close(1008);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type !== 'rpc-req') return;
|
||||
const { id, kind, name, ctx } = frame;
|
||||
try {
|
||||
let result: unknown;
|
||||
if (kind === 'scope') {
|
||||
if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveScope(name, ctx);
|
||||
} else {
|
||||
if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveRoute(name, ctx);
|
||||
}
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
} catch (err) {
|
||||
const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500;
|
||||
deps.bus?.emit('mesh:rpc:error', { name, error: err });
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
|
||||
}
|
||||
});
|
||||
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
|
||||
/**
|
||||
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
|
||||
* the control channel's lifetime the same way it awaits a regular ws route's.
|
||||
* `channel` is fan-out and subscribes when the async iterator is created, which `for await`
|
||||
* does synchronously, so the loop is live before any frame can arrive.
|
||||
*/
|
||||
handle(socket: WsSocket): Promise<void> {
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
|
||||
},
|
||||
};
|
||||
}
|
||||
+163
-26
@@ -1,15 +1,50 @@
|
||||
import 'reflect-metadata';
|
||||
|
||||
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
|
||||
export type Ctor = new (...args: any[]) => any;
|
||||
/** Serializes a handler's return value into an HTTP response envelope. */
|
||||
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
|
||||
|
||||
export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
|
||||
export interface HtmlMeta {
|
||||
path?: string;
|
||||
template?: boolean;
|
||||
}
|
||||
/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */
|
||||
export interface ProviderMeta {
|
||||
provides: string;
|
||||
needs: string[];
|
||||
optional: boolean;
|
||||
export: boolean;
|
||||
}
|
||||
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
|
||||
export interface StepMeta {
|
||||
provides: string;
|
||||
needs: string[];
|
||||
optional: boolean;
|
||||
export: boolean;
|
||||
}
|
||||
/** HTTP verbs supported by the route decorators. */
|
||||
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||
/** Wire transport a route responds with. */
|
||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' }
|
||||
/** Metadata attached by a route decorator to a single handler method. */
|
||||
export interface RouteMeta {
|
||||
method: HttpMethod;
|
||||
path: string;
|
||||
handlerName: string;
|
||||
transport: Transport;
|
||||
export: boolean;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
}
|
||||
/** Options accepted by the `@Module` decorator. */
|
||||
export interface ModuleOptions {
|
||||
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
||||
mountpoint: string;
|
||||
providers?: Ctor[];
|
||||
steps?: Ctor[];
|
||||
controllers?: Ctor[];
|
||||
}
|
||||
|
||||
const K = {
|
||||
@@ -19,73 +54,175 @@ const K = {
|
||||
routes: Symbol('gt:routes'),
|
||||
module: Symbol('gt:module'),
|
||||
transformer: Symbol('gt:transformer'),
|
||||
html: Symbol('gt:html'),
|
||||
};
|
||||
|
||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
/** 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 {
|
||||
return (target) => {
|
||||
const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
const meta: ProviderMeta = {
|
||||
provides: opts.provides,
|
||||
needs: opts.needs ?? [],
|
||||
optional: opts.optional ?? false,
|
||||
export: opts.export ?? false,
|
||||
};
|
||||
Reflect.defineMetadata(K.provider, meta, target);
|
||||
};
|
||||
}
|
||||
|
||||
export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
/** Marks a class as a step: a per-request unit that runs in dependency order and contributes to the context. */
|
||||
export function Step(opts: {
|
||||
provides: string;
|
||||
needs?: string[];
|
||||
optional?: boolean;
|
||||
export?: boolean;
|
||||
}): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
const meta: StepMeta = {
|
||||
provides: opts.provides,
|
||||
needs: opts.needs ?? [],
|
||||
optional: opts.optional ?? false,
|
||||
export: opts.export ?? false,
|
||||
};
|
||||
Reflect.defineMetadata(K.step, meta, target);
|
||||
};
|
||||
}
|
||||
|
||||
/** Sets the shared path prefix for every route declared on the decorated controller. */
|
||||
export function Route(prefix: string): ClassDecorator {
|
||||
return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); };
|
||||
return (target) => {
|
||||
Reflect.defineMetadata(K.routePrefix, prefix, target);
|
||||
};
|
||||
}
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator =>
|
||||
(target, propertyKey) => {
|
||||
/**
|
||||
* 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 });
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
||||
export const Get = routeDecorator('GET', 'buffer');
|
||||
export const Post = routeDecorator('POST', 'buffer');
|
||||
export const Put = routeDecorator('PUT', 'buffer');
|
||||
export const Patch = routeDecorator('PATCH', 'buffer');
|
||||
export const Delete = routeDecorator('DELETE', 'buffer');
|
||||
export const Sse = routeDecorator('GET', 'sse');
|
||||
export const Stream = routeDecorator('GET', 'negotiate');
|
||||
export const Ws = routeDecorator('GET', 'ws');
|
||||
/** Declares a buffered `GET` route. */
|
||||
export const Get: RouteDecorator = routeDecorator('GET', 'buffer');
|
||||
/** Declares a buffered `HEAD` route. */
|
||||
export const Head: RouteDecorator = routeDecorator('HEAD', 'buffer');
|
||||
/** Declares a buffered `POST` route. */
|
||||
export const Post: RouteDecorator = routeDecorator('POST', 'buffer');
|
||||
/** Declares a buffered `PUT` route. */
|
||||
export const Put: RouteDecorator = routeDecorator('PUT', 'buffer');
|
||||
/** Declares a buffered `PATCH` route. */
|
||||
export const Patch: RouteDecorator = routeDecorator('PATCH', 'buffer');
|
||||
/** Declares a buffered `DELETE` route. */
|
||||
export const Delete: RouteDecorator = routeDecorator('DELETE', 'buffer');
|
||||
/** Declares a buffered `OPTIONS` route. */
|
||||
export const Options: RouteDecorator = routeDecorator('OPTIONS', 'buffer');
|
||||
/** Declares a `GET` route streamed as Server-Sent Events. */
|
||||
export const Sse: RouteDecorator = routeDecorator('GET', 'sse');
|
||||
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
||||
export const Stream: RouteDecorator = routeDecorator('GET', 'negotiate');
|
||||
/** Declares a `GET` route upgraded to a WebSocket. */
|
||||
export const Ws: RouteDecorator = routeDecorator('GET', 'ws');
|
||||
|
||||
/** Attaches a response transformer to a handler method. */
|
||||
export function Transformer(fn: TransformerFn): MethodDecorator {
|
||||
return (target, propertyKey) => {
|
||||
Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey));
|
||||
};
|
||||
}
|
||||
|
||||
/** Marks a class as a module and records its providers, steps, controllers, and mountpoint. */
|
||||
export function Module(opts: ModuleOptions): ClassDecorator {
|
||||
return (target) => { Reflect.defineMetadata(K.module, opts, target); };
|
||||
return (target) => {
|
||||
Reflect.defineMetadata(K.module, opts, target);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as
|
||||
* `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })`
|
||||
* renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only).
|
||||
*/
|
||||
export function Html(path: string, opts?: { template?: boolean }): MethodDecorator;
|
||||
export function Html(target: object, propertyKey: string | symbol): void;
|
||||
|
||||
export function Html(a: unknown, b?: unknown): MethodDecorator | void {
|
||||
if (typeof a !== 'string') {
|
||||
// Bare usage: TS calls (prototype, propertyKey, descriptor?).
|
||||
Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b));
|
||||
return;
|
||||
}
|
||||
|
||||
const path = a;
|
||||
const opts = b as { template?: boolean } | undefined;
|
||||
|
||||
return (target, propertyKey) => {
|
||||
const meta: HtmlMeta = { path, template: opts?.template };
|
||||
Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey));
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the `@Html` metadata registered for a handler method, if any. */
|
||||
export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined {
|
||||
return Reflect.getMetadata(K.html, cls, methodName);
|
||||
}
|
||||
|
||||
/** Reads the `@Provider` metadata off a class, if any. */
|
||||
export function getProviderMeta(cls: Ctor): ProviderMeta | undefined {
|
||||
return Reflect.getMetadata(K.provider, cls);
|
||||
}
|
||||
|
||||
/** Reads the `@Step` metadata off a class, if any. */
|
||||
export function getStepMeta(cls: Ctor): StepMeta | undefined {
|
||||
return Reflect.getMetadata(K.step, cls);
|
||||
}
|
||||
|
||||
/** Reads the `@Module` metadata off a class, if any. */
|
||||
export function getModuleMeta(cls: Ctor): ModuleOptions | undefined {
|
||||
return Reflect.getMetadata(K.module, cls);
|
||||
}
|
||||
|
||||
/** Reads the response transformer registered for a handler method, if any. */
|
||||
export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined {
|
||||
return Reflect.getMetadata(K.transformer, cls, methodName);
|
||||
}
|
||||
|
||||
/** Returns every route on a controller with its path resolved against the class prefix. */
|
||||
export function getRoutes(cls: Ctor): RouteMeta[] {
|
||||
const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? '';
|
||||
const routes: RouteMeta[] = Reflect.getMetadata(K.routes, cls) ?? [];
|
||||
return routes.map((r) => ({ ...r, path: joinPath(prefix, r.path) }));
|
||||
return routes.map((route) => ({ ...route, path: joinPath(prefix, route.path) }));
|
||||
}
|
||||
|
||||
export function joinPath(a: string, b: string): string {
|
||||
return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
||||
/** Joins two path segments with exactly one slash, collapsing any duplicates. */
|
||||
export function joinPath(base: string, segment: string): string {
|
||||
return `${base.replace(/\/$/, '')}/${segment.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
||||
}
|
||||
+97
-89
@@ -1,122 +1,130 @@
|
||||
// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps.
|
||||
export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number }
|
||||
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
|
||||
import { Readable } from 'stream';
|
||||
import { HttpError } from './signals';
|
||||
|
||||
/** A single uploaded file part decoded from a multipart body. */
|
||||
export interface UploadedFile {
|
||||
filename: string;
|
||||
contentType: string;
|
||||
data: Buffer;
|
||||
size: number;
|
||||
}
|
||||
|
||||
/** Decoded multipart body: text fields and file uploads, keyed by part name. */
|
||||
export interface MultipartBody {
|
||||
fields: Record<string, string | string[]>;
|
||||
files: Record<string, UploadedFile | UploadedFile[]>;
|
||||
}
|
||||
export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' }
|
||||
|
||||
const CRLF = Buffer.from('\r\n');
|
||||
/** Parser limits and duplicate-key policy for {@link parseMultipart}. */
|
||||
export interface MultipartOpts {
|
||||
maxParts: number;
|
||||
duplicates: 'array' | 'last';
|
||||
}
|
||||
|
||||
// boundary token from a Content-Type value; supports quoted form.
|
||||
/**
|
||||
* Extracts the boundary token from a Content-Type value (supports the quoted form).
|
||||
* @returns The boundary, or undefined when absent.
|
||||
*/
|
||||
export function extractBoundary(contentType: string): string | undefined {
|
||||
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
|
||||
const b = (m?.[1] ?? m?.[2])?.trim();
|
||||
return b || undefined;
|
||||
const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
|
||||
const boundary = (match?.[1] ?? match?.[2])?.trim();
|
||||
return boundary || undefined;
|
||||
}
|
||||
|
||||
// order-independent, quoted-or-unquoted param lookup within a header value.
|
||||
// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT
|
||||
// match the tail of `filename=`, and `filename=` does not match `filename*=`.
|
||||
function param(header: string, key: string): string | undefined {
|
||||
const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header);
|
||||
if (q) return q[1];
|
||||
const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header);
|
||||
return u ? u[1].trim() : undefined;
|
||||
}
|
||||
|
||||
function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void {
|
||||
if (dup === 'array') {
|
||||
const ex = fields[name];
|
||||
if (Array.isArray(ex)) ex.push(value);
|
||||
function addField(fields: MultipartBody['fields'], name: string, value: string, duplicates: 'array' | 'last'): void {
|
||||
if (duplicates === 'array') {
|
||||
const existing = fields[name];
|
||||
if (Array.isArray(existing)) existing.push(value);
|
||||
else fields[name] = [value];
|
||||
} else {
|
||||
fields[name] = value; // last-wins
|
||||
}
|
||||
}
|
||||
|
||||
// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams)
|
||||
// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields.
|
||||
/**
|
||||
* Collapses an iterable of [key, value] pairs (e.g. URLSearchParams) into an object,
|
||||
* applying the same duplicate-key policy as multipart fields so urlencoded bodies behave identically.
|
||||
*/
|
||||
export function collapseDuplicates(
|
||||
pairs: Iterable<[string, string]>, dup: 'array' | 'last',
|
||||
pairs: Iterable<[string, string]>,
|
||||
duplicates: 'array' | 'last',
|
||||
): Record<string, string | string[]> {
|
||||
const out: Record<string, string | string[]> = {};
|
||||
for (const [k, v] of pairs) addField(out, k, v, dup);
|
||||
for (const [key, value] of pairs) addField(out, key, value, duplicates);
|
||||
return out;
|
||||
}
|
||||
|
||||
function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
|
||||
const ex = files[name];
|
||||
if (ex === undefined) files[name] = file;
|
||||
else if (Array.isArray(ex)) ex.push(file);
|
||||
else files[name] = [ex, file];
|
||||
const existing = files[name];
|
||||
if (existing === undefined) files[name] = file;
|
||||
else if (Array.isArray(existing)) existing.push(file);
|
||||
else files[name] = [existing, file];
|
||||
}
|
||||
|
||||
// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is
|
||||
// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the
|
||||
// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case.
|
||||
function findDelim(buf: Buffer, delim: Buffer, from: number): number {
|
||||
let i = buf.indexOf(delim, from);
|
||||
while (i !== -1) {
|
||||
const a = i + delim.length;
|
||||
if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i;
|
||||
i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching
|
||||
/** Lazily loads the optional `busboy` peer dependency, or null when it is not installed. */
|
||||
function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEmitter) | null {
|
||||
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');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody {
|
||||
const fields: MultipartBody['fields'] = {};
|
||||
const files: MultipartBody['files'] = {};
|
||||
const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary
|
||||
// Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no
|
||||
// leading CRLF) is also preceded by the delimiter and isn't dropped as preamble.
|
||||
const buf = Buffer.concat([CRLF, raw]);
|
||||
/**
|
||||
* Parses a raw multipart/form-data buffer into decoded fields and files, using `busboy`.
|
||||
* @param raw The full (already size-capped) request body.
|
||||
* @param boundary The boundary token (see {@link extractBoundary}).
|
||||
* @throws HttpError 501 when the optional `busboy` peer dependency is not installed.
|
||||
* @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded.
|
||||
*/
|
||||
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise<MultipartBody> {
|
||||
const busboy = loadBusboy();
|
||||
|
||||
let pos = findDelim(buf, delim, 0);
|
||||
if (pos === -1) throw new Error('Invalid multipart body');
|
||||
let count = 0;
|
||||
while (true) {
|
||||
let start = pos + delim.length;
|
||||
// terminator "--" immediately after the boundary → done
|
||||
if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break;
|
||||
// skip the CRLF that ends the boundary line
|
||||
if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2;
|
||||
const next = findDelim(buf, delim, start);
|
||||
if (next === -1) throw new Error('Invalid multipart body');
|
||||
if (++count > opts.maxParts) throw new Error('Invalid multipart body');
|
||||
const part = buf.subarray(start, next);
|
||||
const sep = part.indexOf('\r\n\r\n');
|
||||
if (sep === -1) throw new Error('Invalid multipart body');
|
||||
const headerText = part.subarray(0, sep).toString('utf8');
|
||||
const partBody = part.subarray(sep + 4);
|
||||
|
||||
let disposition = '';
|
||||
let contentType = '';
|
||||
for (const line of headerText.split('\r\n')) {
|
||||
const c = line.indexOf(':');
|
||||
if (c === -1) continue;
|
||||
const k = line.slice(0, c).trim().toLowerCase();
|
||||
const v = line.slice(c + 1).trim();
|
||||
if (k === 'content-disposition') disposition = v;
|
||||
else if (k === 'content-type') contentType = v;
|
||||
if (!busboy) {
|
||||
throw new HttpError(501, 'multipart/form-data requires the optional "busboy" peer dependency — run `npm i busboy`');
|
||||
}
|
||||
|
||||
const name = param(disposition, 'name');
|
||||
if (name === undefined) throw new Error('Invalid multipart body');
|
||||
const filename = param(disposition, 'filename');
|
||||
if (filename !== undefined) {
|
||||
if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input
|
||||
addFile(files, name, {
|
||||
filename,
|
||||
contentType: contentType || 'application/octet-stream',
|
||||
data: Buffer.from(partBody), // copy out of the shared buffer
|
||||
size: partBody.length,
|
||||
return new Promise<MultipartBody>((resolve, reject) => {
|
||||
const body: MultipartBody = { fields: {}, files: {} };
|
||||
const fail = () => reject(new Error('Invalid multipart body'));
|
||||
let bb: NodeJS.WritableStream & NodeJS.EventEmitter;
|
||||
|
||||
try {
|
||||
bb = busboy({
|
||||
headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
|
||||
limits: { parts: opts.maxParts },
|
||||
});
|
||||
} else {
|
||||
addField(fields, name, partBody.toString('utf8'), opts.duplicates);
|
||||
} catch {
|
||||
return fail();
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return { fields, files };
|
||||
|
||||
bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates));
|
||||
|
||||
bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => {
|
||||
const chunks: Buffer[] = [];
|
||||
stream.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
stream.on('close', () => {
|
||||
const data = Buffer.concat(chunks);
|
||||
const filename = info.filename ?? '';
|
||||
if (filename === '' && data.length === 0) return; // unselected file input
|
||||
|
||||
addFile(body.files, name, {
|
||||
filename,
|
||||
contentType: info.mimeType || 'application/octet-stream',
|
||||
data,
|
||||
size: data.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
bb.on('partsLimit', fail); // more parts than maxParts → treat as malformed (matches prior behavior)
|
||||
bb.on('error', fail);
|
||||
bb.on('close', () => resolve(body));
|
||||
|
||||
Readable.from(raw).pipe(bb);
|
||||
});
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import type { ArgSpec } from './params';
|
||||
import type { Transport } from './metadata';
|
||||
import { compilePattern } from './http/router';
|
||||
|
||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||
export interface OpenApiRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** `info` block overrides for the generated document. */
|
||||
export interface OpenApiInfo {
|
||||
title?: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** A generated OpenAPI 3.1 document (structural: paths, params, and error responses; body/response schemas are generic). */
|
||||
export interface OpenApiDoc {
|
||||
openapi: string;
|
||||
info: { title: string; version: string; description?: string };
|
||||
paths: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
type Parameter = {
|
||||
name: string;
|
||||
in: 'path' | 'query' | 'header';
|
||||
required: boolean;
|
||||
schema: { type: 'string'; pattern?: string };
|
||||
};
|
||||
|
||||
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||
function templatePath(pattern: string): string {
|
||||
const segments = compilePattern(pattern).segments.map((segment) =>
|
||||
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
|
||||
);
|
||||
return `/${segments.join('/')}`;
|
||||
}
|
||||
|
||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||
function pathParams(pattern: string): Parameter[] {
|
||||
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
|
||||
if (segment.kind === 'static') return [];
|
||||
return [
|
||||
{
|
||||
name: segment.name,
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: {
|
||||
type: 'string',
|
||||
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||
function argParams(args: ArgSpec[]): Parameter[] {
|
||||
const params: Parameter[] = [];
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg.source !== 'query' && arg.source !== 'headers') continue;
|
||||
const location = arg.source === 'query' ? 'query' : 'header';
|
||||
const names = arg.keys ?? (arg.key ? [arg.key] : []);
|
||||
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* The documented `200` per transport. `ws` is absent by construction — ws routes are not
|
||||
* HTTP request/response and are filtered out before this runs. A new transport adds a row,
|
||||
* and the compiler fails until it does.
|
||||
*/
|
||||
type HttpTransport = Exclude<Transport, 'ws'>;
|
||||
|
||||
const TRANSPORT_OK: Record<HttpTransport, Record<string, unknown>> = {
|
||||
buffer: { description: 'OK', content: { 'application/json': { schema: {} } } },
|
||||
sse: { description: 'Event stream', content: { 'text/event-stream': {} } },
|
||||
ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } },
|
||||
negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } },
|
||||
};
|
||||
|
||||
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */
|
||||
function responses(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = { '200': TRANSPORT_OK[transport] };
|
||||
|
||||
if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
|
||||
result['500'] = { description: 'Internal Server Error' };
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Builds a single OpenAPI operation object for a route. */
|
||||
function operation(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
|
||||
const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
|
||||
const op: Record<string, unknown> = { responses: responses(route, transport) };
|
||||
|
||||
if (parameters.length) op.parameters = parameters;
|
||||
|
||||
if (route.args.some((arg) => arg.source === 'body')) {
|
||||
op.requestBody = { content: { 'application/json': { schema: {} } } };
|
||||
}
|
||||
|
||||
return op;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects the route graph into a structural OpenAPI 3.1 document: paths, methods, path/query/header
|
||||
* parameters, which routes take a body, and the systematic error responses. Body and response *schemas*
|
||||
* are generic — Standard Schema doesn't expose JSON Schema (see the roadmap). WebSocket routes are omitted.
|
||||
*/
|
||||
export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenApiDoc {
|
||||
const paths: Record<string, Record<string, unknown>> = {};
|
||||
|
||||
for (const route of routes) {
|
||||
const transport = route.transport;
|
||||
if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below
|
||||
const path = templatePath(route.pattern);
|
||||
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport);
|
||||
}
|
||||
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: info?.title ?? 'green-tea API',
|
||||
version: info?.version ?? '0.0.0',
|
||||
...(info?.description ? { description: info.description } : {}),
|
||||
},
|
||||
paths,
|
||||
};
|
||||
}
|
||||
+72
-30
@@ -3,12 +3,22 @@ import type { Ctor } from './metadata';
|
||||
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
|
||||
import { ValidationError } from './signals';
|
||||
|
||||
/** Parsed URL query string as flat key/value pairs. */
|
||||
export type Query = Record<string, string>;
|
||||
/** Incoming request headers; a header may repeat, hence the array variant. */
|
||||
export type Headers = Record<string, string | string[] | undefined>;
|
||||
/** Per-request bag that accumulates values produced by steps and providers. */
|
||||
export type Context = Record<string, unknown>;
|
||||
|
||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
||||
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 }
|
||||
/** Describes how a single handler parameter is sourced and (optionally) validated. */
|
||||
export interface ArgSpec {
|
||||
index: number;
|
||||
source: ArgSource;
|
||||
key?: string;
|
||||
keys?: string[];
|
||||
schema?: StandardSchemaV1;
|
||||
}
|
||||
|
||||
const ARGS = Symbol('gt:args');
|
||||
|
||||
@@ -22,81 +32,113 @@ 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) => {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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`);
|
||||
|
||||
if (schema !== undefined) {
|
||||
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||
spec.schema = schema;
|
||||
}
|
||||
|
||||
record(target, methodKey, spec);
|
||||
};
|
||||
}
|
||||
|
||||
export const param = envelope('params');
|
||||
export const query = envelope('query');
|
||||
export const body = envelope('body');
|
||||
export const headers = envelope('headers');
|
||||
/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */
|
||||
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: ArgDecorator = envelope('query');
|
||||
/** Inject the request body; pass a schema to validate it. */
|
||||
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: ArgDecorator = envelope('headers');
|
||||
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
|
||||
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 {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key });
|
||||
}
|
||||
|
||||
/** Inject the whole request context bag. */
|
||||
export function ctx(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' });
|
||||
}
|
||||
|
||||
/** Inject the inbound stream (for streaming/upload handlers). */
|
||||
export function inbound(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'inbound' });
|
||||
}
|
||||
|
||||
/** Inject the request's abort signal. */
|
||||
export function abort(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'abort' });
|
||||
}
|
||||
|
||||
/** Read the recorded parameter specs for a handler method, ordered by parameter index. */
|
||||
export function getArgs(cls: Ctor, methodName: string): ArgSpec[] {
|
||||
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, cls) ?? {};
|
||||
return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index);
|
||||
}
|
||||
|
||||
/** Extract the `@needs` keys a handler depends on, for dependency resolution. */
|
||||
export function getHandlerNeeds(specs: ArgSpec[]): string[] {
|
||||
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
|
||||
return specs.filter((spec) => spec.source === 'needs' && spec.key).map((spec) => spec.key as string);
|
||||
}
|
||||
|
||||
/** Build the positional argument array for a handler by sourcing and validating each spec. */
|
||||
export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<unknown[]> {
|
||||
if (specs.length === 0) return [];
|
||||
const max = Math.max(...specs.map((s) => s.index));
|
||||
const args: unknown[] = new Array(max + 1).fill(undefined);
|
||||
for (const s of specs) {
|
||||
let value = resolveOne(s, context);
|
||||
if (s.schema) {
|
||||
const result = await s.schema['~standard'].validate(value);
|
||||
if (result.issues) throw new ValidationError([...result.issues], s.source);
|
||||
const maxIndex = Math.max(...specs.map((spec) => spec.index));
|
||||
const args: unknown[] = new Array(maxIndex + 1).fill(undefined);
|
||||
|
||||
for (const spec of specs) {
|
||||
let value = resolveOne(spec, context);
|
||||
|
||||
if (spec.schema) {
|
||||
const result = await spec.schema['~standard'].validate(value);
|
||||
if (result.issues) throw new ValidationError([...result.issues], spec.source);
|
||||
value = result.value;
|
||||
}
|
||||
args[s.index] = value;
|
||||
|
||||
args[spec.index] = value;
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function resolveOne(s: ArgSpec, context: Context): unknown {
|
||||
if (s.source === 'ctx') return context;
|
||||
if (s.source === 'needs') return context[s.key as string];
|
||||
if (s.source === 'inbound') return context.inbound;
|
||||
if (s.source === 'abort') return context.abort;
|
||||
const bag = context[s.source];
|
||||
function resolveOne(spec: ArgSpec, context: Context): unknown {
|
||||
if (spec.source === 'ctx') return context;
|
||||
if (spec.source === 'needs') return context[spec.key as string];
|
||||
if (spec.source === 'inbound') return context.inbound;
|
||||
if (spec.source === 'abort') return context.abort;
|
||||
const bag = context[spec.source];
|
||||
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
|
||||
const record = bag as Record<string, unknown>;
|
||||
if (s.keys) {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of s.keys) out[k] = record[k];
|
||||
return out;
|
||||
const values = bag as Record<string, unknown>;
|
||||
|
||||
if (spec.keys) {
|
||||
const picked: Record<string, unknown> = {};
|
||||
for (const key of spec.keys) picked[key] = values[key];
|
||||
return picked;
|
||||
}
|
||||
if (s.key !== undefined) return record[s.key];
|
||||
return record;
|
||||
|
||||
if (spec.key !== undefined) return values[spec.key];
|
||||
return values;
|
||||
}
|
||||
+134
-21
@@ -1,39 +1,152 @@
|
||||
import { Bus } from './bus';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { Bus, type Correlation } from './bus';
|
||||
import { renderError, type ErrorRenderer } from './transformers';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import type { TransformerFn, Transport } from './metadata';
|
||||
import { TransportMismatchError } from './signals';
|
||||
|
||||
export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any }
|
||||
export interface ResponseShape { status: number; headers: Record<string, string>; body: string }
|
||||
export interface StreamResult { stream: AsyncIterable<unknown> }
|
||||
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
||||
export interface PipelineStep {
|
||||
name: string;
|
||||
origin: string;
|
||||
run: (ctx: any) => any;
|
||||
}
|
||||
/** A fully materialized HTTP response produced by a transformer. */
|
||||
export interface ResponseShape {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
|
||||
export interface StreamResult {
|
||||
stream: AsyncIterable<unknown>;
|
||||
}
|
||||
/** The outcome of {@link runPipeline}: either a buffered response or a stream. */
|
||||
export type PipelineResult = ResponseShape | StreamResult;
|
||||
|
||||
export function isStreamResult(r: PipelineResult): r is StreamResult {
|
||||
return 'stream' in r;
|
||||
/** What a route's declared transport requires its handler to return. */
|
||||
export type ReturnContract = 'buffer' | 'stream' | 'either';
|
||||
|
||||
/** Return contract per transport. A new transport just adds a row. `ws` never reaches runPipeline (filtered earlier). */
|
||||
export const TRANSPORT_RETURN: Record<Transport, ReturnContract> = {
|
||||
buffer: 'buffer',
|
||||
sse: 'stream',
|
||||
ndjson: 'stream',
|
||||
ws: 'stream',
|
||||
negotiate: 'either',
|
||||
};
|
||||
|
||||
/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */
|
||||
export function isStreamResult(result: PipelineResult): result is StreamResult {
|
||||
return 'stream' in result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `steps` in order, merging each step's output into the context and emitting
|
||||
* `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,
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
|
||||
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
|
||||
* Errors are caught, emitted on `bus`, and converted to an error response.
|
||||
*/
|
||||
export async function runPipeline(args: {
|
||||
steps: PipelineStep[];
|
||||
handler: (ctx: any) => unknown;
|
||||
transformer: TransformerFn;
|
||||
seed: Record<string, unknown>;
|
||||
bus: Bus;
|
||||
transport: Transport;
|
||||
onError?: ErrorRenderer;
|
||||
correlation?: Correlation;
|
||||
}): Promise<PipelineResult> {
|
||||
const { steps, handler, transformer, seed, bus } = args;
|
||||
let ctx: any = { ...seed };
|
||||
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args;
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
let context: any = { ...seed };
|
||||
|
||||
try {
|
||||
for (const s of steps) {
|
||||
bus.emit('request:step:enter', { name: s.name, scope: s.origin });
|
||||
const out = await s.run(ctx);
|
||||
ctx = { ...ctx, ...out };
|
||||
bus.emit('request:step:leave', { name: s.name, scope: s.origin });
|
||||
context = await runSteps(steps, context, bus, correlation);
|
||||
const result = await handler(context);
|
||||
const streaming = isAsyncIterable(result);
|
||||
const contract = TRANSPORT_RETURN[transport];
|
||||
|
||||
if (contract === 'buffer' && streaming) {
|
||||
throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string });
|
||||
}
|
||||
const result = await handler(ctx);
|
||||
if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed
|
||||
const r = transformer(result);
|
||||
return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body };
|
||||
|
||||
if (contract === 'stream' && !streaming) {
|
||||
throw new TransportMismatchError(transport, 'value', context.req as { method?: string; url?: string });
|
||||
}
|
||||
|
||||
if (streaming) return { stream: result }; // stream path: transformer bypassed
|
||||
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 });
|
||||
return errorToResponse(error);
|
||||
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
|
||||
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
|
||||
// what produces a trace that says a request failed without saying where.
|
||||
if (bus.hasListeners('request:failed'))
|
||||
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
|
||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||
return renderError(
|
||||
error,
|
||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||
onError,
|
||||
);
|
||||
}
|
||||
}
|
||||
+32
-5
@@ -1,5 +1,7 @@
|
||||
import { Bus } from './bus';
|
||||
import type { TeardownFn } from './lifecycle';
|
||||
|
||||
/** A step or provider a plugin contributes to the graph. */
|
||||
export interface ScopeNode {
|
||||
kind: 'step' | 'provider';
|
||||
name: string;
|
||||
@@ -8,13 +10,38 @@ export interface ScopeNode {
|
||||
run: (ctx: any) => any;
|
||||
}
|
||||
|
||||
export interface ScopeApi { add(node: ScopeNode): void }
|
||||
export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi }
|
||||
/** The narrow surface a plugin uses to register nodes into the host graph. */
|
||||
export interface ScopeApi {
|
||||
add(node: ScopeNode): void;
|
||||
}
|
||||
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
|
||||
export interface PluginApi {
|
||||
bus: { on: Bus['on'] };
|
||||
scope: ScopeApi;
|
||||
/**
|
||||
* Run something before the app closes — closing a pool, stopping a timer, flushing a buffer.
|
||||
*
|
||||
* Takes no arguments: whatever needs closing is already in the closure of the plugin that opened
|
||||
* it. It is awaited, unlike a `bus.on` listener, and a failure is logged rather than swallowed.
|
||||
*/
|
||||
onShutdown(fn: TeardownFn): void;
|
||||
}
|
||||
/** A plugin: a function that wires itself up through the provided PluginApi. */
|
||||
export type Plugin = (api: PluginApi) => void;
|
||||
|
||||
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 };
|
||||
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
|
||||
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi, onShutdown: (fn: TeardownFn) => void): void {
|
||||
// Hand the plugin ONLY on(), add() and onShutdown(). No emit, no other scope, no container.
|
||||
//
|
||||
// "Isolation is structural" means this list and nothing else — it is a guarantee about the
|
||||
// *registration surface*, not about the request context. A plugin's step receives the live
|
||||
// context like any other step and can overwrite keys in it (`src/pipeline.ts`, `Object.assign`),
|
||||
// which is a separate, pre-existing question this list has never covered.
|
||||
//
|
||||
// `onShutdown` is the first capability here the framework must *wait* for: nothing a plugin did
|
||||
// before could delay the process. It cannot delay it without bound — `close()`'s deadline still
|
||||
// caps the whole shutdown.
|
||||
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope, onShutdown };
|
||||
plugin(api);
|
||||
bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' });
|
||||
}
|
||||
+12
-2
@@ -1,11 +1,21 @@
|
||||
import { channel, type Channel } from './channel';
|
||||
|
||||
/** Registry of named broadcast channels, lazily created and shared by name. */
|
||||
export class Rooms {
|
||||
private readonly hubs = new Map<string, Channel<unknown>>();
|
||||
/** Returns the channel for `name`, creating it on first access. */
|
||||
room<T = unknown>(name: string): Channel<T> {
|
||||
let hub = this.hubs.get(name);
|
||||
if (!hub) { hub = channel<unknown>(); this.hubs.set(name, hub); }
|
||||
|
||||
if (!hub) {
|
||||
hub = channel<unknown>();
|
||||
this.hubs.set(name, hub);
|
||||
}
|
||||
|
||||
return hub as unknown as Channel<T>;
|
||||
}
|
||||
names(): string[] { return [...this.hubs.keys()]; }
|
||||
/** Lists the names of all rooms created so far. */
|
||||
names(): string[] {
|
||||
return [...this.hubs.keys()];
|
||||
}
|
||||
}
|
||||
+77
-43
@@ -1,6 +1,14 @@
|
||||
// src/security.ts — pure header computation, no server deps
|
||||
export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string }
|
||||
|
||||
/** TLS material for an HTTPS server. */
|
||||
export interface TlsOptions {
|
||||
key: Buffer | string;
|
||||
cert: Buffer | string;
|
||||
ca?: Buffer | string;
|
||||
passphrase?: string;
|
||||
}
|
||||
|
||||
/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */
|
||||
export interface CorsOptions {
|
||||
origins: string | string[] | '*' | ((origin: string) => boolean);
|
||||
methods?: string[];
|
||||
@@ -10,6 +18,7 @@ export interface CorsOptions {
|
||||
maxAge?: number;
|
||||
}
|
||||
|
||||
/** Security header policy. Each field toggles or configures one response header. */
|
||||
export interface SecurityOptions {
|
||||
hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
|
||||
frameOptions?: 'SAMEORIGIN' | 'DENY' | false;
|
||||
@@ -23,32 +32,47 @@ type Headers = Record<string, string>;
|
||||
const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
|
||||
|
||||
// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
|
||||
// Control-char ranges (\x00-\x1f\x7f) are intentional: reject control chars in Origin headers.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i;
|
||||
export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); }
|
||||
|
||||
/** True if `origin` is a well-formed Origin header value (scheme://host or literal `null`). */
|
||||
export function isValidOrigin(origin: string): boolean {
|
||||
return ORIGIN_RE.test(origin);
|
||||
}
|
||||
|
||||
/** Append `add` to a `Vary` header value, case-insensitively deduplicated. */
|
||||
export function mergeVary(existing: string | undefined, add: string): string {
|
||||
const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []);
|
||||
if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add);
|
||||
const parts = existing
|
||||
? existing
|
||||
.split(',')
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
if (!parts.some((part) => part.toLowerCase() === add.toLowerCase())) parts.push(add);
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
/** Build security response headers (HSTS, frame options, CSP, etc.). `secure` gates HSTS. */
|
||||
export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers {
|
||||
if (opts === false) return {};
|
||||
const o: SecurityOptions = opts === true ? {} : opts;
|
||||
const h: Headers = {};
|
||||
if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff';
|
||||
if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN';
|
||||
if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer';
|
||||
if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off';
|
||||
if (o.csp) h['content-security-policy'] = o.csp;
|
||||
if (secure && o.hsts !== false) {
|
||||
const hs = o.hsts && o.hsts !== true ? o.hsts : {};
|
||||
let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
|
||||
if (hs.includeSubDomains) v += '; includeSubDomains';
|
||||
if (hs.preload) v += '; preload';
|
||||
h['strict-transport-security'] = v;
|
||||
const options: SecurityOptions = opts === true ? {} : opts;
|
||||
const headers: Headers = {};
|
||||
if (options.noSniff !== false) headers['x-content-type-options'] = 'nosniff';
|
||||
if (options.frameOptions !== false) headers['x-frame-options'] = options.frameOptions ?? 'SAMEORIGIN';
|
||||
if (options.referrerPolicy !== false) headers['referrer-policy'] = options.referrerPolicy ?? 'no-referrer';
|
||||
if (options.dnsPrefetchControl !== false) headers['x-dns-prefetch-control'] = 'off';
|
||||
if (options.csp) headers['content-security-policy'] = options.csp;
|
||||
|
||||
if (secure && options.hsts !== false) {
|
||||
const hsts = options.hsts && options.hsts !== true ? options.hsts : {};
|
||||
let value = `max-age=${hsts.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
|
||||
if (hsts.includeSubDomains) value += '; includeSubDomains';
|
||||
if (hsts.preload) value += '; preload';
|
||||
headers['strict-transport-security'] = value;
|
||||
}
|
||||
return h;
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||
@@ -58,36 +82,46 @@ function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||
return spec === origin;
|
||||
}
|
||||
|
||||
// req: minimal shape { headers: { origin? } }
|
||||
export function resolveCors(opts: CorsOptions, req: { headers: Record<string, string | string[] | undefined> }): Headers {
|
||||
const h: Headers = {};
|
||||
const raw = req.headers['origin'];
|
||||
const origin = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h;
|
||||
/** 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> },
|
||||
): 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;
|
||||
|
||||
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
|
||||
if (opts.credentials) {
|
||||
h['access-control-allow-origin'] = origin;
|
||||
h['access-control-allow-credentials'] = 'true';
|
||||
h['vary'] = mergeVary(h['vary'], 'Origin');
|
||||
headers['access-control-allow-origin'] = origin;
|
||||
headers['access-control-allow-credentials'] = 'true';
|
||||
headers['vary'] = mergeVary(headers['vary'], 'Origin');
|
||||
} else if (opts.origins === '*') {
|
||||
h['access-control-allow-origin'] = '*';
|
||||
headers['access-control-allow-origin'] = '*';
|
||||
} else {
|
||||
h['access-control-allow-origin'] = origin;
|
||||
h['vary'] = mergeVary(h['vary'], 'Origin');
|
||||
}
|
||||
if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
|
||||
return h;
|
||||
headers['access-control-allow-origin'] = origin;
|
||||
headers['vary'] = mergeVary(headers['vary'], 'Origin');
|
||||
}
|
||||
|
||||
// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM.
|
||||
export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record<string, string | string[] | undefined> }): Headers {
|
||||
const h = resolveCors(opts, req);
|
||||
if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204
|
||||
h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', ');
|
||||
const reqHdrs = req.headers['access-control-request-headers'];
|
||||
h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ')
|
||||
?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*');
|
||||
if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge);
|
||||
return h;
|
||||
if (opts.exposedHeaders?.length) headers['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. */
|
||||
export function corsPreflightHeaders(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
): Headers {
|
||||
const headers = resolveCors(opts, req);
|
||||
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(
|
||||
', ',
|
||||
);
|
||||
const requestedHeaders = req.headers['access-control-request-headers'];
|
||||
headers['access-control-allow-headers'] =
|
||||
opts.allowedHeaders?.join(', ') ??
|
||||
(Array.isArray(requestedHeaders) ? requestedHeaders.join(', ') : (requestedHeaders ?? '*'));
|
||||
if (opts.maxAge != null) headers['access-control-max-age'] = String(opts.maxAge);
|
||||
return headers;
|
||||
}
|
||||
+48
-8
@@ -1,34 +1,74 @@
|
||||
import type { StandardIssue } from './standard-schema';
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message?: string,
|
||||
readonly body?: unknown,
|
||||
readonly headers?: Record<string, string>,
|
||||
) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
this.name = new.target.name;
|
||||
}
|
||||
}
|
||||
|
||||
/** 401 Unauthorized. */
|
||||
export class Unauthorized extends HttpError {
|
||||
constructor(message?: string) { super(401, message); }
|
||||
constructor(message?: string) {
|
||||
super(401, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 404 Not Found. */
|
||||
export class NotFound extends HttpError {
|
||||
constructor(message?: string) { super(404, message); }
|
||||
constructor(message?: string) {
|
||||
super(404, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 304 Not Modified. */
|
||||
export class NotModified extends HttpError {
|
||||
constructor() { super(304); }
|
||||
constructor() {
|
||||
super(304);
|
||||
}
|
||||
}
|
||||
|
||||
/** 302 redirect to `location`. */
|
||||
export class Redirect extends HttpError {
|
||||
constructor(readonly location: string) { super(302); }
|
||||
constructor(readonly location: string) {
|
||||
super(302, undefined, undefined, { location });
|
||||
}
|
||||
}
|
||||
|
||||
/** 422 raised when request input fails Standard Schema validation. */
|
||||
export class ValidationError extends HttpError {
|
||||
constructor(public issues: StandardIssue[], public source: string) {
|
||||
constructor(
|
||||
public issues: StandardIssue[],
|
||||
public source: string,
|
||||
) {
|
||||
super(422, 'Validation failed');
|
||||
}
|
||||
}
|
||||
|
||||
export function isHttpError(e: unknown): e is HttpError {
|
||||
return e instanceof HttpError;
|
||||
/** Thrown when a handler's return value contradicts its route's declared transport (a programming error). */
|
||||
export class TransportMismatchError extends HttpError {
|
||||
constructor(transport: string, got: 'stream' | 'value', req?: { method?: string; url?: string }) {
|
||||
const where = req?.method && req?.url ? ` (${req.method} ${req.url})` : '';
|
||||
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
||||
const fix =
|
||||
got === 'stream'
|
||||
? 'buffered routes (@Get/@Head/@Post/@Put/@Patch/@Delete/@Options) must return a value — to stream, declare @Sse, @Stream, or @Ws'
|
||||
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
|
||||
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard: true if `error` is an {@link HttpError}. */
|
||||
export function isHttpError(error: unknown): error is HttpError {
|
||||
return error instanceof HttpError;
|
||||
}
|
||||
+14
-8
@@ -1,4 +1,6 @@
|
||||
// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports.
|
||||
|
||||
/** Standard Schema v1 interface (spec.standardschema.dev): a validator under the `~standard` key. */
|
||||
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
||||
readonly '~standard': {
|
||||
readonly version: 1;
|
||||
@@ -8,27 +10,31 @@ export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
||||
};
|
||||
}
|
||||
|
||||
/** Validation outcome: either a parsed `value` or a list of `issues`. */
|
||||
export type StandardResult<T> =
|
||||
| { readonly value: T; readonly issues?: undefined }
|
||||
| { readonly issues: ReadonlyArray<StandardIssue> };
|
||||
{ readonly value: T; readonly issues?: undefined } | { readonly issues: ReadonlyArray<StandardIssue> };
|
||||
|
||||
/** A single validation issue with a message and optional path to the offending field. */
|
||||
export interface StandardIssue {
|
||||
readonly message: string;
|
||||
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;
|
||||
}
|
||||
|
||||
export function isStandardSchema(x: unknown): x is StandardSchemaV1 {
|
||||
/** Type guard: true if `value` implements Standard Schema v1 (has a callable `~standard.validate`). */
|
||||
export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
|
||||
return (
|
||||
typeof x === 'object' && x !== null &&
|
||||
'~standard' in x &&
|
||||
typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'~standard' in value &&
|
||||
typeof (value as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/** Render an issue's path as a dotted string (e.g. `user.email`); empty if pathless. */
|
||||
export function flattenPath(issue: StandardIssue): string {
|
||||
if (!issue.path) return '';
|
||||
return issue.path
|
||||
.map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg))
|
||||
.map((k) => String(k))
|
||||
.map((segment) => (typeof segment === 'object' && segment !== null && 'key' in segment ? segment.key : segment))
|
||||
.map((key) => String(key))
|
||||
.join('.');
|
||||
}
|
||||
+41
-9
@@ -1,33 +1,65 @@
|
||||
import { isHttpError, Redirect, ValidationError } from './signals';
|
||||
import { isHttpError, ValidationError } from './signals';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import { flattenPath } from './standard-schema';
|
||||
|
||||
/** A ready-to-send HTTP response. */
|
||||
export interface ErrorResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */
|
||||
export interface ErrorRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* User hook to render errors however you like (HTML, custom JSON, RFC 7807, …).
|
||||
* Return a response to take over, or `undefined`/`void` to fall back to the default JSON.
|
||||
*/
|
||||
export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void;
|
||||
|
||||
/** Default transformer: serialize a handler's return value as a JSON `200` response. */
|
||||
export const JsonTransformer: TransformerFn = (value) => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(value),
|
||||
});
|
||||
|
||||
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
||||
if (e instanceof ValidationError) {
|
||||
/**
|
||||
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
|
||||
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
|
||||
*/
|
||||
export function errorToResponse(error: unknown): ErrorResponse {
|
||||
if (error instanceof ValidationError) {
|
||||
return {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
error: 'Validation failed',
|
||||
source: e.source,
|
||||
issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })),
|
||||
source: error.source,
|
||||
issues: error.issues.map((issue) => ({ path: flattenPath(issue), message: issue.message })),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (isHttpError(e)) {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
||||
if (e instanceof Redirect) headers.location = e.location;
|
||||
return { status: e.status, headers, body: JSON.stringify({ error: e.message }) };
|
||||
|
||||
if (isHttpError(error)) {
|
||||
const headers = { 'content-type': 'application/json', ...error.headers };
|
||||
const payload = error.body !== undefined ? error.body : { error: error.message };
|
||||
return { status: error.status, headers, body: JSON.stringify(payload) };
|
||||
}
|
||||
|
||||
return {
|
||||
status: 500,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ error: 'Internal Server Error' }),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders.
|
||||
// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem).
|
||||
|
||||
import type { TransformerFn } from './metadata';
|
||||
import type { HtmlMeta } from './metadata';
|
||||
|
||||
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
|
||||
export function escapeHtml(s: string): string {
|
||||
const map: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return s.replace(/[&<>"']/g, (c) => map[c]);
|
||||
}
|
||||
|
||||
function stringify(v: unknown): string {
|
||||
return v === null || v === undefined ? '' : String(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw,
|
||||
* `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials.
|
||||
*/
|
||||
export function render(source: string, data: unknown): string {
|
||||
const lookup = (key: string): unknown =>
|
||||
key.split('.').reduce<any>((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data);
|
||||
return source
|
||||
.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key)))
|
||||
.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key))));
|
||||
}
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */
|
||||
export function contentTypeFor(ext: string): string {
|
||||
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
|
||||
}
|
||||
|
||||
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const;
|
||||
|
||||
/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */
|
||||
export interface ViewsContext {
|
||||
views?: string;
|
||||
viewEngine?: (source: string, data: unknown) => string;
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
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 base = views ?? process.cwd();
|
||||
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
|
||||
|
||||
try {
|
||||
return fs.readFileSync(full, 'utf8');
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** A static-file hit: the raw bytes and the content-type to send. */
|
||||
export interface StaticHit {
|
||||
body: Buffer;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
||||
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
||||
|
||||
/**
|
||||
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
|
||||
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
|
||||
*/
|
||||
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
let fs: typeof import('node:fs');
|
||||
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');
|
||||
} catch {
|
||||
throw new Error(
|
||||
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
|
||||
);
|
||||
}
|
||||
|
||||
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
|
||||
|
||||
return async (urlPath) => {
|
||||
let rel: string;
|
||||
|
||||
try {
|
||||
rel = decodeURIComponent(urlPath.split('?')[0]);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (rel === '' || rel.endsWith('/')) rel += 'index.html';
|
||||
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
||||
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
||||
|
||||
try {
|
||||
const stat = await fs.promises.stat(full);
|
||||
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
|
||||
const body = await fs.promises.readFile(target);
|
||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */
|
||||
export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn {
|
||||
if (!meta.path) {
|
||||
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) });
|
||||
}
|
||||
|
||||
const source = readViewFile(ctx.views, meta.path);
|
||||
|
||||
if (meta.template) {
|
||||
const engine = ctx.viewEngine ?? render;
|
||||
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) });
|
||||
}
|
||||
|
||||
return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source });
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index';
|
||||
import { channel } from '../src/channel';
|
||||
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
@Step({ provides: 'tag' })
|
||||
class Tagger {
|
||||
run() {
|
||||
return { tag: 't' };
|
||||
}
|
||||
}
|
||||
@Route('/tagged')
|
||||
class TaggedCtl {
|
||||
@Ws('/echo')
|
||||
echo(@needs('tag') tag: string, @ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `${tag}:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] })
|
||||
class Tagged {}
|
||||
|
||||
function fakeSocket() {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
const sent: string[] = [];
|
||||
const socket: WsSocket = {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
isOpen: true,
|
||||
send: (d) => sent.push(d),
|
||||
close: () => ac.abort(),
|
||||
terminate: () => ac.abort(),
|
||||
};
|
||||
return { socket, inbound, sent };
|
||||
}
|
||||
|
||||
describe('app.upgrade', () => {
|
||||
it('routes a matching ws path through the graph', async () => {
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' };
|
||||
const run = app.upgrade(req, socket);
|
||||
// let the handler's async generator start subscribing to `inbound` (channel is fan-out:
|
||||
// push before subscription is lost) before pushing — a macrotask flushes every pending
|
||||
// microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
inbound.push('hi');
|
||||
inbound.close();
|
||||
await run;
|
||||
expect(sent).toEqual(['echo:hi']);
|
||||
});
|
||||
|
||||
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 wsApp = createApp({ modules: [Tagged], plugins: [logger] });
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' };
|
||||
const run = wsApp.upgrade(req, socket);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
inbound.push('hi');
|
||||
inbound.close();
|
||||
await run;
|
||||
|
||||
expect(sent).toEqual(['t:hi']);
|
||||
expect(seen).toEqual(['enter:tag', 'leave:tag']);
|
||||
});
|
||||
|
||||
it('closes 1008 on an unknown ws path', async () => {
|
||||
const { socket } = fakeSocket();
|
||||
let closedCode: number | undefined;
|
||||
socket.close = (c) => {
|
||||
closedCode = c;
|
||||
};
|
||||
const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' };
|
||||
await app.upgrade(req, socket);
|
||||
expect(closedCode).toBe(1008);
|
||||
});
|
||||
});
|
||||
+406
-58
@@ -1,13 +1,17 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it, test, vi } from 'vitest';
|
||||
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
|
||||
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
|
||||
import { JsonTransformer } from '../src/transformers';
|
||||
import { Unauthorized } from '../src/signals';
|
||||
import { createApp } from '../src/app';
|
||||
import { needs, param, query } from '../src/params';
|
||||
import { needs, param, query, body } from '../src/params';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Auth {
|
||||
@@ -22,7 +26,9 @@ class Auth {
|
||||
class UserCtl {
|
||||
@Get('/:id')
|
||||
@Transformer(JsonTransformer)
|
||||
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { id, user };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
|
||||
@@ -34,6 +40,20 @@ test('inspect lists the ordered chain with origins', () => {
|
||||
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
|
||||
});
|
||||
|
||||
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
|
||||
// The point: code holding an `App` should not have to know whether it is a mesh app.
|
||||
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
const booted: string[] = [];
|
||||
app.bus.on('boot:provider:start', (p) => booted.push(p.name));
|
||||
|
||||
const before = app.graph().nodes.length;
|
||||
await app.ready();
|
||||
|
||||
expect(app.graph().nodes.length).toBe(before);
|
||||
expect(booted).toEqual([]);
|
||||
});
|
||||
|
||||
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));
|
||||
@@ -54,7 +74,11 @@ test('a logger plugin observes step:enter without mutating the chain', async ()
|
||||
|
||||
test('required provider failure aborts boot', () => {
|
||||
@Provider({ provides: 'broken' })
|
||||
class Broken { provide() { throw new Error('cannot connect'); } }
|
||||
class Broken {
|
||||
provide() {
|
||||
throw new Error('cannot connect');
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
|
||||
class BrokenModule {}
|
||||
|
||||
@@ -65,15 +89,27 @@ test('required provider failure aborts boot', () => {
|
||||
test('optional provider failure warns but does not abort boot', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
@Provider({ provides: 'cache', optional: true })
|
||||
class FlakyCache { provide() { throw new Error('cache down'); } }
|
||||
class FlakyCache {
|
||||
provide() {
|
||||
throw new Error('cache down');
|
||||
}
|
||||
}
|
||||
@Route('/ping')
|
||||
class PingCtl { @Get('/') ping() { return { ok: true }; } }
|
||||
class PingCtl {
|
||||
@Get('/') ping() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
|
||||
class SysModule {}
|
||||
|
||||
const app = createApp({ modules: [SysModule] });
|
||||
expect(app.degraded()).toEqual([]); // nothing degraded until boot runs
|
||||
const server = await app.listen(0); // must NOT throw
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
|
||||
// boot ends with a summary of everything running degraded, and it is queryable on the app
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache'));
|
||||
expect(app.degraded()).toEqual(['cache']);
|
||||
server.close();
|
||||
warn.mockRestore();
|
||||
});
|
||||
@@ -82,7 +118,9 @@ test('handler receives @query value through a live request', async () => {
|
||||
@Route('/search')
|
||||
class SearchCtl {
|
||||
@Get('/')
|
||||
run(@query('q') q: string) { return { q }; }
|
||||
run(@query('q') q: string) {
|
||||
return { q };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
|
||||
class SearchModule {}
|
||||
@@ -99,19 +137,31 @@ test('boot fails when a handler needs something nothing provides', () => {
|
||||
@Route('/things')
|
||||
class ThingCtl {
|
||||
@Get('/')
|
||||
list(@needs('missing') _m: any) { return []; }
|
||||
list(@needs('missing') _m: any) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
|
||||
class ThingModule {}
|
||||
|
||||
expect(() => createApp({ modules: [ThingModule] }))
|
||||
.toThrow(/handler 'list' needs 'missing'/);
|
||||
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
|
||||
});
|
||||
|
||||
it('boot error for a misspelled @needs suggests the closest token', () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('usr') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
|
||||
});
|
||||
|
||||
@@ -124,10 +174,14 @@ describe('app streaming wiring', () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () { yield { t: 1 }; yield { t: 2 }; })();
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -143,11 +197,15 @@ describe('app streaming wiring', () => {
|
||||
class Ctl {
|
||||
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })();
|
||||
(async () => {
|
||||
for await (const m of inc) out.push(`re:${m}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -157,7 +215,8 @@ describe('app streaming wiring', () => {
|
||||
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
|
||||
client.send('yo');
|
||||
expect(await got).toBe('re:yo');
|
||||
client.close(); server.close();
|
||||
client.close();
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -165,13 +224,23 @@ describe('per-route subgraph slicing', () => {
|
||||
it('a route that does not @needs a step does not run it', async () => {
|
||||
const ran: string[] = [];
|
||||
@Step({ provides: 'tracked', needs: [] })
|
||||
class Tracked { run() { ran.push('tracked'); return { tracked: true }; } }
|
||||
class Tracked {
|
||||
run() {
|
||||
ran.push('tracked');
|
||||
return { tracked: true };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/needs') needs(@needs('tracked') t: any) { return { t }; }
|
||||
@Get('/free') free() { return { ok: true }; }
|
||||
@Get('/needs') needs(@needs('tracked') t: any) {
|
||||
return { t };
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {}
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -187,10 +256,25 @@ 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 = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'obs',
|
||||
needs: [],
|
||||
provides: [],
|
||||
run: () => {
|
||||
ran.push('obs');
|
||||
return {};
|
||||
},
|
||||
});
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -201,12 +285,31 @@ 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 = (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() { return { user: { id: 'u1' } }; } }
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: { id: 'u1' } };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
} // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -221,10 +324,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz';
|
||||
|
||||
describe('app.graph / explain', () => {
|
||||
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
|
||||
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 1 };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/:id') get(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const g = app.graph();
|
||||
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
|
||||
@@ -235,9 +354,20 @@ describe('app.graph / explain', () => {
|
||||
});
|
||||
|
||||
it('explain() returns the rich chain with origin and a handler entry', async () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const e = app.explain('/api/u/me');
|
||||
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
|
||||
@@ -249,34 +379,101 @@ describe('app.graph / explain', () => {
|
||||
describe('devGraph endpoint', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('serves /__graph__ as HTML when devGraph:true', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true });
|
||||
const s = await app.listen(0);
|
||||
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
|
||||
expect(html).toContain('class="mermaid"');
|
||||
expect(html).toContain('flowchart');
|
||||
expect(html).toContain('cytoscape');
|
||||
expect(html).toContain('/api/u/me');
|
||||
const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
|
||||
expect(mmd.headers.get('content-type')).toContain('text/plain');
|
||||
expect(await mmd.text()).toContain('flowchart');
|
||||
s.close();
|
||||
});
|
||||
it('does NOT mount /__graph__ without devGraph', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
|
||||
expect(res.status).toBe(404);
|
||||
s.close();
|
||||
});
|
||||
|
||||
it('serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)', async () => {
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true, devOpenapi: true });
|
||||
|
||||
const graph = await app.fetch(new Request('http://x/__graph__'));
|
||||
expect(graph.status).toBe(200);
|
||||
expect(await graph.text()).toContain('cytoscape');
|
||||
|
||||
const openapi = await app.fetch(new Request('http://x/__openapi__'));
|
||||
expect(openapi.status).toBe(200);
|
||||
expect(((await openapi.json()) as { openapi: string }).openapi).toBe('3.1.0');
|
||||
|
||||
// still absent when the flags are off, on the fetch path too
|
||||
const off = createApp({ modules: [M] });
|
||||
expect((await off.fetch(new Request('http://x/__graph__'))).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
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 { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -289,31 +486,102 @@ 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', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { real: true } };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
|
||||
s.close();
|
||||
});
|
||||
it('overrides with a function runner', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 'real' };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
|
||||
s.close();
|
||||
});
|
||||
it('rejects an override for an unknown token', async () => {
|
||||
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { nope: 1 } });
|
||||
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||
});
|
||||
@@ -321,8 +589,14 @@ describe('overrides', () => {
|
||||
|
||||
describe('rooms auto-provide', () => {
|
||||
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/r')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('rooms') rooms: Rooms) {
|
||||
return { ok: rooms instanceof Rooms };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const port = (s.address() as any).port;
|
||||
@@ -330,9 +604,83 @@ describe('rooms auto-provide', () => {
|
||||
s.close();
|
||||
});
|
||||
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
|
||||
@Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'rooms' })
|
||||
class MyRooms {
|
||||
provide() {
|
||||
return { rooms: { custom: true } };
|
||||
}
|
||||
}
|
||||
@Route('/r')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('rooms') rooms: any) {
|
||||
return rooms;
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
|
||||
class M {}
|
||||
expect(() => createApp({ modules: [M] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
test('per-route maxBodyBytes overrides the server default', async () => {
|
||||
@Route('/up')
|
||||
class C {
|
||||
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
@Post('/big') big(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
|
||||
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
|
||||
|
||||
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
|
||||
expect(tight.status).toBe(413); // per-route cap of 10 bytes
|
||||
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
|
||||
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
|
||||
|
||||
server.close();
|
||||
});
|
||||
|
||||
describe('route table validation', () => {
|
||||
it('rejects routes with the same method and effective pattern', () => {
|
||||
@Route('/users')
|
||||
class DuplicateCtl {
|
||||
@Get('/:id') byId() {
|
||||
return {};
|
||||
}
|
||||
@Get('/:name') byName() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
|
||||
class DuplicateModule {}
|
||||
|
||||
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
|
||||
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the same effective pattern under different methods', () => {
|
||||
@Route('/users')
|
||||
class MethodsCtl {
|
||||
@Get('/:id') get() {
|
||||
return {};
|
||||
}
|
||||
@Post('/:name') post() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
|
||||
class MethodsModule {}
|
||||
|
||||
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
// Reconnection under the real Bun runtime.
|
||||
//
|
||||
// Separate from the Node and Deno suites deliberately. Bun's WebSocket lifecycle is a third
|
||||
// implementation — its socket events land on a server-level handler rather than the socket — and a
|
||||
// link that swaps its socket underneath a live graph is precisely where three implementations
|
||||
// stop behaving the same. Defining this on Node and hoping is not enough.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { runtime: 'bun' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
|
||||
function freePort(): number {
|
||||
const probe = Bun.serve({ port: 0, fetch: () => new Response('') });
|
||||
const { port } = probe;
|
||||
probe.stop(true);
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
|
||||
function startTeapot(port: number) {
|
||||
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = serveBun(app, { port });
|
||||
|
||||
return {
|
||||
stop: async () => {
|
||||
server.stop(true);
|
||||
await app.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
|
||||
const port = freePort();
|
||||
let teapot = startTeapot(port);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: {
|
||||
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
|
||||
heartbeatMs: 50,
|
||||
timeoutMs: 2000,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||
expect(before.status).toBe(200);
|
||||
|
||||
await teapot.stop();
|
||||
await settle(100);
|
||||
|
||||
// the down window answers immediately rather than waiting out timeoutMs
|
||||
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||
expect(down.status).toBe(503);
|
||||
|
||||
teapot = startTeapot(port);
|
||||
await settle(400);
|
||||
|
||||
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||
expect(after.status).toBe(200);
|
||||
expect((await after.json()).auth).toEqual({ token: 'xyz' });
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// Real Bun integration test for mesh: a teapot exporting its scopes 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
|
||||
// rather than the socket — so the control channel reaching app.upgrade here is a distinct
|
||||
// path from the Deno test, not a duplicate of it.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { region: 'mx', runtime: 'bun' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
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 teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
|
||||
});
|
||||
const cServer = serveBun(teacup, { port: 0 });
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
config: { region: 'mx', runtime: 'bun' },
|
||||
auth: { token: 'abc' },
|
||||
});
|
||||
} finally {
|
||||
await teacup.close();
|
||||
cServer.stop(true);
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
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 teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: 'WRONG' }], timeoutMs: 1000 },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// Real Bun integration test for the bounded close() serveBun returns. app.close() cannot do this
|
||||
// job on Bun — it returns at its `if (!server)` guard, because a Bun app is served through
|
||||
// app.fetch and never through listen() — so the deadline lives on the transport that owns the
|
||||
// handle. See issue #15.
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Get, Module } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/hang')
|
||||
hang() {
|
||||
return new Promise(() => {}); // never resolves — a stuck handler
|
||||
}
|
||||
@Get('/slow')
|
||||
async slow() {
|
||||
await Bun.sleep(200); // finite, so draining has something real to wait out
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
test('serveBun close({ timeoutMs }) gives up on a stuck handler and resolves', async () => {
|
||||
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
fetch(`http://127.0.0.1:${server.port}/hang`).catch(() => {});
|
||||
await Bun.sleep(50); // let the request actually reach the handler
|
||||
|
||||
const start = Date.now();
|
||||
await server.close({ timeoutMs: 300 });
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
// The assertion that matters is the upper bound: without the deadline this never returns.
|
||||
expect(elapsed).toBeLessThan(2000);
|
||||
expect(elapsed).toBeGreaterThanOrEqual(250);
|
||||
});
|
||||
|
||||
test('serveBun close() drains an in-flight request rather than cutting it', async () => {
|
||||
const server = serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
|
||||
const inFlight = fetch(`http://127.0.0.1:${server.port}/slow`).then((r) => r.json());
|
||||
await Bun.sleep(50); // the request must be *in* the handler before we close, or it never got in
|
||||
|
||||
await server.close({ timeoutMs: 5000 });
|
||||
|
||||
expect(await inFlight).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
// D7 of the teardown design: proving the Node path works proves nothing here, because app.close()
|
||||
// returns at its no-server guard on Bun. The teardown has to run from the close() Bun actually uses.
|
||||
test('serveBun close() runs registered teardown', async () => {
|
||||
const closed: string[] = [];
|
||||
const app = createApp({
|
||||
modules: [M],
|
||||
hooks: [{ onShutdown: () => void closed.push('hook') }],
|
||||
plugins: [(api) => api.onShutdown(async () => {
|
||||
await Bun.sleep(10);
|
||||
closed.push('plugin');
|
||||
})],
|
||||
});
|
||||
const server = serveBun(app, { port: 0 });
|
||||
|
||||
await server.close({ timeoutMs: 2000 });
|
||||
|
||||
// Reverse registration order: the plugin registered after the hook, so it tears down first.
|
||||
expect(closed).toEqual(['plugin', 'hook']);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// Real Bun integration test for serveBun: boots an app under the actual Bun runtime
|
||||
// and round-trips both HTTP (app.fetch) and WebSocket (Bun's server-level websocket
|
||||
// handler -> app.upgrade).
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Get('/hello')
|
||||
hello() {
|
||||
return { ok: true };
|
||||
}
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
|
||||
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
expect(httpRes.status).toBe(200);
|
||||
expect((await httpRes.json()).ok).toBe(true);
|
||||
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.onopen = () => ws.send('hi');
|
||||
ws.onmessage = (e) => {
|
||||
resolve(String(e.data));
|
||||
ws.close();
|
||||
};
|
||||
ws.onerror = () => reject(new Error('ws error'));
|
||||
});
|
||||
expect(got).toBe('echo:hi');
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user